Compare commits

5 Commits
Author SHA1 Message Date
Aemeath 466ca6c7b0 Dawnline 0.8.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Every field says what is wrong as you type, in the router's own words,
  and Save refuses what the router would: UDP port when editing a server,
  MTU, keep-alive, public address, DNS for devices, person name, device
  limit, end date and data limit, device names (the next free "Phone 2"
  is offered), home services, circles, portal title, redirect and other
  addresses, defaults, update time
- Cyrillic names give Latin ids, hostnames and file names; names are
  counted in characters, the rule names the characters it refuses; end
  dates must exist on the calendar; a mistyped extra portal address is
  refused instead of dropped
- The public address is checked on the router as it is typed: points at
  this router, at another address, behind Cloudflare, or the WAN is
  private or CGNAT; the wizard says so before the first step, never
  pre-fills a private WAN address and says where its suggestion came
  from; the Connection card says when the server was last reached from
  the internet; IPv6 names and literals work throughout
- A person can be moved to another server from their page; a server's
  tunnel network can be changed in the Danger zone (devices are
  renumbered and marked "Update config"); WAN and LAN zones come from the
  router's actual devices; when the public IPv4 changed, one click puts
  the new one in
- Over the data limit or outside the allowed hours the tunnel stays
  connected and the portal explains why nothing gets through, instead of
  a silent handshake failure; Health's "devices loaded" compares the
  peers themselves, not their count
- Portal: install links for this platform, two first steps on a first
  visit, the phone's back button closes a sheet, the file goes through
  the share sheet into the app, two QR codes (AmneziaVPN camera, AmneziaWG
  and WireGuard apps), the sheet notices the first connection
- Admin: Enter submits a dialog, arrow keys walk the menus, Find in People
  ("/" focuses it), a device of a paused, ended or over-limit person says
  so, "Keep access" past its end date is said on the Overview, Allowed
  hours enforce nothing until saved, the invite card shares the link
- Health warns when another package's policy routing (mwan3, pbr) sends
  tunnel traffic past the home-device path
- CLI: person ls, device ls, log with -n, --since, --level, --src and
  --json; exit code 2 for an unknown command and 1 when health finds an
  error; person rm asks for --yes when devices would go; devices added
  from the command line get their event and "issued" marker like the
  UI's
- Three disguises: Off, Balanced and Maximum. Standard and Strong (1.0-style
  junk only, which networks learned to spot) are no longer offered; a server
  still on one keeps running and its card says to switch. A new server gets
  the strongest disguise its router can run
- Portal: setting up a device is one sheet with two steps. Get the app
  (AmneziaVPN first; AmneziaWG, and WireGuard with the disguise off, behind
  "Another app") from the store of the device in hand, with the GitHub release
  where no store has it and the version the server needs said once; then add
  the connection (open in AmneziaVPN, copy the key, share or download the
  file). A device set up from another device gets its link to take there, as a
  QR code for a phone; a phone set up from a computer also gets the connection
  as a code, one code revealed at a time so the camera cannot read the wrong one
- Portal motion: the first visit comes in once (blocks in reading order,
  meters fill, the sun rises in the logo); a repaint glides cards to their
  new places and brings changed values into focus; sheets slide up on
  phones and can be pulled down, come into focus on a computer, follow
  their content's height and turn into the next sheet in place; tabs and
  segments slide, menus, tooltips and toasts grow out of what opened them,
  copy buttons turn into a check, buttons waiting for the router spin;
  with reduced motion only the fades remain
- Portal: while a device is set up, a card at the top shows the way from
  it to the router with a light running along it; on the first connection
  the way fills green, the steps fold away and the sheet closes by itself.
  The first connection is the first fresh handshake, so it is no longer
  missed while the watcher catches up (or after new keys), and the device's
  card goes on to Connected
- Portal: QR codes are light dots on a black card, fuller on dense keys,
  with "Show a light code" for scanners that read only dark on light (every
  code switches, the choice is kept); the link and code a set-up sheet
  hands to another device open that device's set-up there at once
- Portal: Remove and New keys ask in a small alert with the action's icon;
  the open one of two cards is not a button; device names are no longer
  repeated in every line of the set-up sheet; the code card lines up with
  the rest of its card (a class clash gave it the page's padding); text
  keeps the arrow cursor, store badges and link buttons are not underlined
2026-10-18 23:28:10 +03:00
Aemeath fd9543ce68 Dawnline 0.7.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Balanced, a new disguise for AmneziaWG 2.0 apps (AmneziaVPN 4.8.12 and
  newer): junk packets, padded cookie and data packets and DNS-shaped
  signature packets, for networks that learned to spot 1.0-style junk;
  offered when both the tools and the kernel module are 2.0 or newer
- The junk count and sizes in a device's configuration are the device's own
  (shifted a little, deterministically), so two phones of one family do not
  share one profile; they never require importing again
- Components remembers which AmneziaWG build was installed on which kernel;
  after a firmware upgrade Health says the build was for the old one and
  offers the build for the new firmware. A SNAPSHOT firmware is told there are
  no builds for it
- Location lookups moved off the agent's 1-second watcher to its minute tick,
  a few per minute within a time budget; the cache lives in tmpfs and goes to
  flash hourly, and addresses still shown on the map are never pushed out of
  it (and looked up again)
- The map library from the CDN is checked against its expected hash before it
  runs inside the LuCI page
- The activity log is copied to flash only when something was logged; the
  person page and the device drawer fetch only that person's events
- Admin UI: live updates survive the theme's in-page navigation, pollers stop
  with their page and sleep while the tab is hidden, the map is freed when
  leaving the Overview, a router that stops answering is said once (and when
  it is back), and an update of Dawnline under an open page asks for a reload
- Watchdog: no repairs while an update runs; a target that keeps failing keeps
  its back-off (repairs are forgotten after ten good minutes, not one); the
  LuCI link is reloaded or restarted three times at most, not every hour for
  good; the one-click "ifup" fix accepts only Dawnline's own tunnels
- Health warns when the router's flash is nearly full (settings would stop
  saving); the portal runs two processes instead of four on routers with
  little memory
- "Remove their devices" at an end date is never done on a clock that has not
  been set yet
2026-10-18 16:04:58 +03:00
Aemeath 31a2065f05 Dawnline 0.6.0
- Access rules fail closed: when the table cannot load, no device is loaded
  into the tunnels (the firewall alone would let every loaded device reach
  everything); an older table that survived a failed rebuild keeps its rules
  and a revoked device still leaves. The agent re-syncs within a minute when
  the table is gone
- A change the router saved but could not put into effect (access rules that
  did not load, a server that refused its devices) is said in the admin UI
  instead of a plain "Saved"
- The guard judges every packet, not only a connection's first: a change of
  access, a pause or a limit now cuts open connections too
- Each server's home networks are its own: with several servers, "all home"
  on one no longer reaches the other's networks where firewall zones overlap
- People limited to some home networks reach the router only on the
  addresses in those networks (LuCI and SSH on the main LAN stay closed)
- Internet-only people can open their personal portal with the VPN on
- Tunnel DNS reaches the resolver and the LAN's DNS from servers that do not
  forward to those zones on their own (Home-only names on servers without
  "like a home device", LAN DNS on servers with no home network)
- A new personal link offers to remove the devices added through the old one,
  so a leaked link is really contained
- Import and restore refuse an inconsistent file (devices with addresses
  outside their server, shared addresses, malformed keys, broken references);
  Health reports one, and the sync leaves such a device out instead of
  failing its server. A config write that did not reach flash is an error,
  not a silent success
- Backups are kept per kind (nightly ones no longer push out manual or
  pre-delete ones), nightly and pre-change backups hold the config only,
  archives are written whole or not at all, and a failed nightly backup is
  logged. A restore no longer has its history overwritten by the agent's
  in-memory counters
- Settings defaults and ranges come from one place (dawnline.schema)
- Portal: anything not shaped like a personal link is answered by a shell
  before ucode starts (a scan on the root costs nothing); 4 portal processes
  at once instead of 16; a link may make 40 changes a quarter hour; over
  plain HTTP the page shows but configurations, new devices and new keys are
  refused with the HTTPS twin of the link; the connect sheet polls only while
  the first connection is awaited, with backoff, and stops once the link
  stopped working
- Updates: after Dawnline's own package changes, a shell checks that LuCI
  reaches it and the agent runs, and puts the kept previous version back when
  they do not (automatic runs always keep it); the AmneziaWG module reload
  verifies rmmod and modprobe; installs check free space; on apk a reinstall
  that changed nothing is an error; uninstall.sh hands the update lock to the
  removal it calls; an upgrade restarts the service only where it was
  enabled; the release workflow pins the SDK images by digest and the actions
  by commit
- AmneziaWG: features count only when both the tools and the kernel module
  have them; a server whose disguise this build cannot run (a 3.1 preset
  after a rollback to 2.0) is kept down and reported; Components tells 1.0
  builds from 2.0 ones; `awg show dump` is parsed by shape; Maximum's
  DNS-shaped signature packets are made for each server and its keep-alive
  is a 25-35 s range
- CI compiles every ucode file and runs the new tests/ucode unit tests (54
  tests on the real libuci) in OpenWrt 24.10 and 25.12 rootfs containers;
  scripts/compile-ucode.sh does the same wherever ucode runs and
  scripts/ucode-container.sh locally with docker; lint-ucode checks POSIX
  regexes and module layering; a tag builds only after CI passes
2026-10-18 15:32:27 +03:00
Aemeath 2b98abdba4 Dawnline 0.5.2
- Fixed: a new server with the Maximum disguise could not be created ("jmin=10
  (64-1024)"): the 3.1 preset's small junk packets failed Dawnline's own check
- Fixed: guesses from a shared address (every visitor behind Cloudflare) could
  lock people with valid links out of the portal for 15 minutes; a valid link
  always opens now, only wrong guesses are counted
- Fixed: a disabled Dawnline still loaded every device into the tunnels when
  netifd brought them up, with nothing enforcing end dates or limits afterwards
- Fixed: an MTU of 1380 chosen by hand was deleted on every apply (the one-time
  switch to automatic MTU now runs once)
- Locations (city lookups) are off by default on new installs: they send
  people's addresses to a third party. Routers that had them on keep them on
- "Don't warn" before an end date is honoured, and the warning window is the
  one chosen for the person on the Overview, People, the person page and the
  portal alike (People and Overview used to warn 3 days before whatever was set)
- "Ends today" and "ends tomorrow" instead of "ends in 1 day"
- Renaming a person keeps the dialog open when the router refuses the name
- Settings → Portal no longer saves a listening port its own help line marks
  as taken
- "Remove Dawnline" is live only once "remove" is typed
- Downloaded .conf files are named after the device first, and two devices
  whose names only differ past the 15th character no longer get the same file
  (and tunnel name in the app)
2026-10-18 14:42:01 +03:00
Aemeath 1a2f0b327e README: new screenshots for 0.5.1
- scripts/capture-screenshots.mjs takes the raw screenshots from a live router (headless Chromium over DevTools, 2x PNG), hides the domain with --mask and public IPs
- Overview now shows the whole connection map; the separate map screenshot is gone
- frame-screenshots.py frames 2x captures
2026-10-17 07:39:24 +03:00
137 changed files with 7939 additions and 996 deletions

No files matched your search

+19 -10
View File
@@ -12,10 +12,19 @@ on:
workflow_dispatch:
# Read-only by default; only the release job may write (publish the release).
# Everything that runs here is pinned to a digest or a commit: the packages
# it publishes are installed as root on every router with automatic updates
# on, so a re-pointed tag must not be able to change what gets built.
permissions:
contents: read
jobs:
# The same checks as on main (ci.yml), on the tag itself: nothing is built or
# published until they pass.
ci:
name: CI
uses: ./.github/workflows/ci.yml
version:
name: Version
runs-on: ubuntu-24.04
@@ -23,7 +32,7 @@ jobs:
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
persist-credentials: false
@@ -44,21 +53,21 @@ jobs:
build:
name: Build ${{ matrix.type }}
runs-on: ubuntu-24.04
needs: version
needs: [version, ci]
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' }
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6@sha256:a6bd28c380b251ebdb1d6d5f83e55ecb0a3c1808b5a8f4841424abc8019a903f' }
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
with:
node-version: '22'
cache: npm
@@ -77,7 +86,7 @@ jobs:
run: scripts/build-packages.sh ${{ matrix.type }}
- name: Upload
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: package-${{ matrix.type }}
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }}
@@ -94,7 +103,7 @@ jobs:
steps:
# The whole history and the tags: the notes list the commits since the previous tag.
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
persist-credentials: false
fetch-depth: 0
@@ -105,7 +114,7 @@ jobs:
cat notes.md
- name: Download packages
uses: actions/download-artifact@v4
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
pattern: package-*
path: release
@@ -118,7 +127,7 @@ jobs:
cat sha256sums.txt
- name: Publish the release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
name: Dawnline ${{ github.ref_name }}
tag_name: ${{ github.ref_name }}
+63 -14
View File
@@ -1,9 +1,12 @@
name: CI
# Every push to main and every pull request; also called by build.yml, so a
# tag never publishes a release without these checks passing on it.
on:
push:
branches: [main]
pull_request:
workflow_call:
permissions:
contents: read
@@ -43,6 +46,7 @@ jobs:
exit 1
fi
# Sources and the test files (tsconfig.test.json).
- name: Type check
id: types
run: npm run --silent typecheck
@@ -51,12 +55,17 @@ jobs:
id: tests
run: npm test
# The bundles under package/ are committed: a build must change nothing
# and leave no new file behind (an output nobody added to git would be
# missing from the package).
- 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."
changed="$(git status --porcelain --untracked-files=all -- ../package)"
if [ -n "$changed" ]; then
echo "$changed"
echo "::error::The committed bundles are out of date or the build left new files. Run 'npm run build' in web/ and commit the result."
exit 1
fi
@@ -83,17 +92,25 @@ jobs:
with:
persist-credentials: false
# Every shell script by its shebang (the init script's is "/bin/sh
# /etc/rc.common"), so a new hotplug or libexec script is covered the
# day it appears. Files without a shebang (keep.d lists) are not shell.
- name: ShellCheck
run: |
shellcheck --version
shellcheck -S warning \
install.sh \
uninstall.sh \
package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \
files="$(grep -rlIE '^#!(/usr)?/bin/(sh|bash|env (sh|bash))( |$)' \
install.sh uninstall.sh package/luci-app-dawnline/root scripts tests | sort)"
echo "$files"
for f in package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
package/luci-app-dawnline/root/usr/libexec/dawnline/resolver \
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
scripts/*.sh
package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate \
package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal; do
echo "$files" | grep -qx "$f" || { echo "::error file=$f::not found by the shebang scan"; exit 1; }
done
# shellcheck disable=SC2086
shellcheck -S warning $files
ucode:
name: ucode static checks
@@ -104,20 +121,52 @@ jobs:
with:
persist-credentials: false
- name: Use before definition
- name: Lint (use before definition, exports, POSIX regexes, rpcd methods)
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 usr/libexec/dawnline/heartbeat \
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat usr/libexec/dawnline/postupdate \
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal usr/share/dawnline/portal/cgi.uc; do
[ -x "package/luci-app-dawnline/root/$f" ] || { echo "::error file=package/luci-app-dawnline/root/$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
done
for f in scripts/check-ucode.sh scripts/compile-ucode.sh scripts/ucode-container.sh tests/ucode/run.sh tests/ucode/fixtures/bin/awg; 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
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; }
python3 - "$v" <<'PY'
import json, sys
v = sys.argv[1]
lock = json.load(open('web/package-lock.json'))
got = (lock.get('version'), lock.get('packages', {}).get('', {}).get('version'))
if got != (v, v):
print(f"::error::web/package-lock.json says {got}, the Makefile {v}: run 'npm install' in web/")
sys.exit(1)
PY
echo "Version $v"
ucode-compile:
# scripts/compile-ucode.sh and tests/ucode on the release's own ucode and
# libuci, in the OpenWrt rootfs containers scripts/ucode-container.sh pins
# by digest (24.10 = opkg, 25.12 = apk: the two the packages are built for).
name: ucode compiles and tests pass (OpenWrt ${{ matrix.release }})
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
release: ['24.10', '25.12']
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Compile every ucode file and run tests/ucode
run: scripts/ucode-container.sh ${{ matrix.release }}
+7 -4
View File
@@ -17,13 +17,16 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`.
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
- `scripts/` — `lint-ucode.py`, `check-ucode.sh` (compiles every module on the router without installing), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
## Checks before a commit or deploy
- `python3 scripts/lint-ucode.py` and `scripts/check-ucode.sh` (needs the router); new ucode entry points are added to the compile list there and to the executables list in `.github/workflows/ci.yml`.
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build` — and commit the rebuilt bundles.
- `shellcheck -S warning` for the shell scripts (CI runs it).
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm test`, `npm run build` — and commit the rebuilt bundles (CI fails on a changed or new file under `package/`).
- `shellcheck -S warning` for the shell scripts (CI finds them by shebang).
- A tag builds only after CI passes on it (`build.yml` calls `ci.yml`).
## Releases
+2 -3
View File
@@ -24,8 +24,6 @@ limits, live traffic and a LuCI admin that follows a modern design.
|---|---|
| ![Personal portal](docs/screenshots/portal.png) | ![Access](docs/screenshots/access.png) |
![Where people connect from](docs/screenshots/map.png)
## Features
- **People, not peers.** One card per person with device chips, live status,
@@ -209,7 +207,8 @@ 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
scripts/capture-screenshots.mjs # capture docs/screenshots/raw/*.png from a router
scripts/frame-screenshots.py # frame them for this README
```
The web bundles are committed: CI fails when they are out of date. Pushing a
Binary file not shown.

Before

Width:  |  Height:  |  Size: 287 KiB

After

Width:  |  Height:  |  Size: 525 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 427 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 908 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 639 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

After

Width:  |  Height:  |  Size: 825 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 274 KiB

After

Width:  |  Height:  |  Size: 615 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 162 KiB

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

After

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 327 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 170 KiB

+1 -1
View File
@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.5.1
PKG_VERSION:=0.8.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT
@@ -5,25 +5,25 @@
'require poll';
'require rpc';
'require ui';
var cr=Object.create;var to=Object.defineProperty;var pr=Object.getOwnPropertyDescriptor;var ur=Object.getOwnPropertyNames;var mr=Object.getPrototypeOf,hr=Object.prototype.hasOwnProperty;var fr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var gr=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ur(e))!hr.call(n,r)&&r!==o&&to(n,r,{get:()=>e[r],enumerable:!(a=pr(e,r))||a.enumerable});return n};var vr=(n,e,o)=>(o=n!=null?cr(mr(n)):{},gr(e||!n||!n.__esModule?to(o,"default",{value:n,enumerable:!0}):o,n));var ho=fr((uo,mo)=>{"use strict";var po=(function(){var n=function(E,y){var S=236,b=17,x=E,M=o[y],h=null,f=0,R=null,C=[],I={},Z=function(_,A){f=x*4+17,h=(function($){for(var N=new Array($),T=0;T<$;T+=1){N[T]=new Array($);for(var j=0;j<$;j+=1)N[T][j]=null}return N})(f),G(0,0),G(f-7,0),G(0,f-7),q(),z(),de(_,A),x>=7&&X(_),R==null&&(R=U(x,M,C)),fe(R,A)},G=function(_,A){for(var $=-1;$<=7;$+=1)if(!(_+$<=-1||f<=_+$))for(var N=-1;N<=7;N+=1)A+N<=-1||f<=A+N||(0<=$&&$<=6&&(N==0||N==6)||0<=N&&N<=6&&($==0||$==6)||2<=$&&$<=4&&2<=N&&N<=4?h[_+$][A+N]=!0:h[_+$][A+N]=!1)},V=function(){for(var _=0,A=0,$=0;$<8;$+=1){Z(!0,$);var N=r.getLostPoint(I);($==0||_>N)&&(_=N,A=$)}return A},z=function(){for(var _=8;_<f-8;_+=1)h[_][6]==null&&(h[_][6]=_%2==0);for(var A=8;A<f-8;A+=1)h[6][A]==null&&(h[6][A]=A%2==0)},q=function(){for(var _=r.getPatternPosition(x),A=0;A<_.length;A+=1)for(var $=0;$<_.length;$+=1){var N=_[A],T=_[$];if(h[N][T]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?h[N+j][T+Y]=!0:h[N+j][T+Y]=!1}},X=function(_){for(var A=r.getBCHTypeNumber(x),$=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[Math.floor($/3)][$%3+f-8-3]=N}for(var $=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[$%3+f-8-3][Math.floor($/3)]=N}},de=function(_,A){for(var $=M<<3|A,N=r.getBCHTypeInfo($),T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<6?h[T][8]=j:T<8?h[T+1][8]=j:h[f-15+T][8]=j}for(var T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<8?h[8][f-T-1]=j:T<9?h[8][15-T-1+1]=j:h[8][15-T-1]=j}h[f-8][8]=!_},fe=function(_,A){for(var $=-1,N=f-1,T=7,j=0,Y=r.getMaskFunction(A),J=f-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var pe=0;pe<2;pe+=1)if(h[N][J-pe]==null){var be=!1;j<_.length&&(be=(_[j]>>>T&1)==1);var ee=Y(N,J-pe);ee&&(be=!be),h[N][J-pe]=be,T-=1,T==-1&&(j+=1,T=7)}if(N+=$,N<0||f<=N){N-=$,$=-$;break}}},O=function(_,A){for(var $=0,N=0,T=0,j=new Array(A.length),Y=new Array(A.length),J=0;J<A.length;J+=1){var pe=A[J].dataCount,be=A[J].totalCount-pe;N=Math.max(N,pe),T=Math.max(T,be),j[J]=new Array(pe);for(var ee=0;ee<j[J].length;ee+=1)j[J][ee]=255&_.getBuffer()[ee+$];$+=pe;var Se=r.getErrorCorrectPolynomial(be),_e=s(j[J],Se.getLength()-1),Qn=_e.mod(Se);Y[J]=new Array(Se.getLength()-1);for(var ee=0;ee<Y[J].length;ee+=1){var Xn=ee+Qn.getLength()-Y[J].length;Y[J][ee]=Xn>=0?Qn.getAt(Xn):0}}for(var eo=0,ee=0;ee<A.length;ee+=1)eo+=A[ee].totalCount;for(var $n=new Array(eo),Ot=0,ee=0;ee<N;ee+=1)for(var J=0;J<A.length;J+=1)ee<j[J].length&&($n[Ot]=j[J][ee],Ot+=1);for(var ee=0;ee<T;ee+=1)for(var J=0;J<A.length;J+=1)ee<Y[J].length&&($n[Ot]=Y[J][ee],Ot+=1);return $n},U=function(_,A,$){for(var N=l.getRSBlocks(_,A),T=c(),j=0;j<$.length;j+=1){var Y=$[j];T.put(Y.getMode(),4),T.put(Y.getLength(),r.getLengthInBits(Y.getMode(),_)),Y.write(T)}for(var J=0,j=0;j<N.length;j+=1)J+=N[j].dataCount;if(T.getLengthInBits()>J*8)throw"code length overflow. ("+T.getLengthInBits()+">"+J*8+")";for(T.getLengthInBits()+4<=J*8&&T.put(0,4);T.getLengthInBits()%8!=0;)T.putBit(!1);for(;!(T.getLengthInBits()>=J*8||(T.put(S,8),T.getLengthInBits()>=J*8));)T.put(b,8);return O(T,N)};I.addData=function(_,A){A=A||"Byte";var $=null;switch(A){case"Numeric":$=d(_);break;case"Alphanumeric":$=p(_);break;case"Byte":$=u(_);break;case"Kanji":$=w(_);break;default:throw"mode:"+A}C.push($),R=null},I.isDark=function(_,A){if(_<0||f<=_||A<0||f<=A)throw _+","+A;return h[_][A]},I.getModuleCount=function(){return f},I.make=function(){if(x<1){for(var _=1;_<40;_++){for(var A=l.getRSBlocks(_,M),$=c(),N=0;N<C.length;N++){var T=C[N];$.put(T.getMode(),4),$.put(T.getLength(),r.getLengthInBits(T.getMode(),_)),T.write($)}for(var j=0,N=0;N<A.length;N++)j+=A[N].dataCount;if($.getLengthInBits()<=j*8)break}x=_}Z(!1,V())},I.createTableTag=function(_,A){_=_||2,A=typeof A>"u"?_*4:A;var $="";$+='<table style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: "+A+"px;",$+='">',$+="<tbody>";for(var N=0;N<I.getModuleCount();N+=1){$+="<tr>";for(var T=0;T<I.getModuleCount();T+=1)$+='<td style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: 0px;",$+=" width: "+_+"px;",$+=" height: "+_+"px;",$+=" background-color: ",$+=I.isDark(N,T)?"#000000":"#ffffff",$+=";",$+='"/>';$+="</tr>"}return $+="</tbody>",$+="</table>",$},I.createSvgTag=function(_,A,$,N){var T={};typeof arguments[0]=="object"&&(T=arguments[0],_=T.cellSize,A=T.margin,$=T.alt,N=T.title),_=_||2,A=typeof A>"u"?_*4:A,$=typeof $=="string"?{text:$}:$||{},$.Line truncated
`}return $%2&&_>0?_e.substring(0,_e.length-$-1)+Array($+1).join("▀"):_e.substring(0,_e.length-1)};return I.createASCII=function(_,A){if(_=_||1,_<2)return oe(A);_-=1,A=typeof A>"u"?_*2:A;var $=I.getModuleCount()*_+A*2,N=A,T=$-A,j,Y,J,pe,be=Array(_+1).join("██"),ee=Array(_+1).join(" "),Se="",_e="";for(j=0;j<$;j+=1){for(J=Math.floor((j-N)/_),_e="",Y=0;Y<$;Y+=1)pe=1,N<=Y&&Y<T&&N<=j&&j<T&&I.isDark(J,Math.floor((Y-N)/_))&&(pe=0),_e+=pe?be:ee;for(J=0;J<_;J+=1)Se+=_e+`
`}return Se.substring(0,Se.length-1)},I.renderTo2dContext=function(_,A){A=A||2;for(var $=I.getModuleCount(),N=0;N<$;N++)for(var T=0;T<$;T++)_.fillStyle=I.isDark(N,T)?"black":"white",_.fillRect(N*A,T*A,A,A)},I};n.stringToBytesFuncs={default:function(E){for(var y=[],S=0;S<E.length;S+=1){var b=E.charCodeAt(S);y.push(b&255)}return y}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,y){var S=(function(){for(var x=k(E),M=function(){var z=x.read();if(z==-1)throw"eof";return z},h=0,f={};;){var R=x.read();if(R==-1)break;var C=M(),I=M(),Z=M(),G=String.fromCharCode(R<<8|C),V=I<<8|Z;f[G]=V,h+=1}if(h!=y)throw h+" != "+y;return f})(),b=63;return function(x){for(var M=[],h=0;h<x.length;h+=1){var f=x.charCodeAt(h);if(f<128)M.push(f);else{var R=S[x.charAt(h)];typeof R=="number"?(R&255)==R?M.push(R):(M.push(R>>>8),M.push(R&255)):M.push(b)}}return M}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[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]],y=1335,S=7973,b=21522,x={},M=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return x.getBCHTypeInfo=function(h){for(var f=h<<10;M(f)-M(y)>=0;)f^=y<<M(f)-M(y);return(h<<10|f)^b},x.getBCHTypeNumber=function(h){for(var f=h<<12;M(f)-M(S)>=0;)f^=S<<M(f)-M(S);return h<<12|f},x.getPatternPosition=function(h){return E[h-1]},x.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(f,R){return(f+R)%2==0};case a.PATTERN001:return function(f,R){return f%2==0};case a.PATTERN010:return function(f,R){return R%3==0};case a.PATTERN011:return function(f,R){return(f+R)%3==0};case a.PATTERN100:return function(f,R){return(Math.floor(f/2)+Math.floor(R/3))%2==0};case a.PATTERN101:return function(f,R){return f*R%2+f*R%3==0};case a.PATTERN110:return function(f,R){return(f*R%2+f*R%3)%2==0};case a.PATTERN111:return function(f,R){return(f*R%3+(f+R)%2)%2==0};default:throw"bad maskPattern:"+h}},x.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),R=0;R<h;R+=1)f=f.multiply(s([1,i.gexp(R)],0));return f},x.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){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:"+h}else if(f<27)switch(h){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:"+h}else if(f<41)switch(h){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:"+h}else throw"type:"+f},x.getLostPoint=function(h){for(var f=h.getModuleCount(),R=0,C=0;C<f;C+=1)for(var I=0;I<f;I+=1){for(var Z=0,G=h.isDark(C,I),V=-1;V<=1;V+=1)if(!(C+V<0||f<=C+V))for(var z=-1;z<=1;z+=1)I+z<0||f<=I+z||V==0&&z==0||G==h.isDark(C+V,I+z)&&(Z+=1);Z>5&&(R+=3+Z-5)}for(var C=0;C<f-1;C+=1)for(var I=0;I<f-1;I+=1){var q=0;h.isDark(C,I)&&(q+=1),h.isDark(C+1,I)&&(q+=1),h.isDark(C,I+1)&&(q+=1),h.isDark(C+1,I+1)&&(q+=1),(q==0||q==4)&&(R+=3)}for(var C=0;C<f;C+=1)for(var I=0;I<f-6;I+=1)h.isDark(C,I)&&!h.isDark(C,I+1)&&h.isDark(C,I+2)&&h.isDark(C,I+3)&&h.isDark(C,I+4)&&!h.isDark(C,I+5)&&h.isDark(C,I+6)&&(R+=40);for(var I=0;I<f;I+=1)for(var C=0;C<f-6;C+=1)h.isDark(C,I)&&!h.isDark(C+1,I)&&h.isDark(C+2,I)&&h.isDark(C+3,I)&&h.isDark(C+4,I)&&!h.isDark(C+5,I)&&h.isDark(C+6,I)&&(R+=40);for(var X=0,I=0;I<f;I+=1)for(var C=0;C<f;C+=1)h.isDark(C,I)&&(X+=1);var de=Math.abs(100*X/f/f-50)/5;return R+=de*10,R},x})(),i=(function(){for(var E=new Array(256),y=new Array(256),S=0;S<8;S+=1)E[S]=1<<S;for(var S=8;S<256;S+=1)E[S]=E[S-4]^E[S-5]^E[S-6]^E[S-8];for(var S=0;S<255;S+=1)y[E[S]]=S;var b={};return b.glog=function(x){if(x<1)throw"glog("+x+")";return y[x]},b.gexp=function(x){for(;x<0;)x+=255;for(;x>=256;)x-=255;return E[x]},b})();function s(E,y){if(typeof E.length>"u")throw E.length+"/"+y;var S=(function(){for(var x=0;x<E.length&&E[x]==0;)x+=1;for(var M=new Array(E.length-x+y),h=0;h<E.length-x;h+=1)M[h]=E[h+x];return M})(),b={};return b.getAt=function(x){return S[x]},b.getLength=function(){return S.length},b.multiply=function(x){for(var M=new Array(b.getLength()+x.getLength()-1),h=0;h<b.getLength();h+=1)for(var f=0;f<x.getLength();f+=1)M[h+f]^=i.gexp(i.glog(b.getAt(h))+i.glog(x.getAt(f)));return s(M,0)},b.mod=function(x){if(b.getLength() Line truncated
`)}function Tr(n){let e=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ue(n,e,o,a="",r=[]){let i=Tr(n),s=[...e.map(p=>({ts:p.ts,category:_t(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Pe(p)??""})),...r.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Tt[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){Ee(c,JSON.stringify(s,null,2),"application/json");return}Ee(c,xo(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Cr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],wo=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function qe(n,e,o,a,r,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...ft.map(c=>t("option",{value:c,selected:c===r?"selected":null},at[c])),i?t("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Cr.map(([c,d])=>t("option",{value:c},d)));re(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[le()," ",D("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await P.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){Q(ve(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await P.serviceLogClear(l.value)).removed}catch(d){ce(),Q(`${s.value==="system"?"":`Activity: ${wo(c).toLowerCase()}. `}The service log was not cleared: ${ve(d)}`,"error",1e4),a();return}ce(),Q(wo(c),"success",3e3),a()},"negative")])}function gt(n,e,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";re(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},r)],[le()," ",D("Reset",async()=>{await W(()=>P.usageClear(n,e),"Traffic history reset")&&(ce(),a())},"negative")])}function ge(n,e,o){let a=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!a.classList.contains("on");Tn(a,r),o?.(r)}},t("i"));return a}function Tn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Me=n=>n.classList.contains("on");function xe(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let a=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function We(n,e,o,a={}){return t("button",{type:"button",...a,class:`dl-chipbtn${e?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Kt(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Pr={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Dr={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 Ar(n){let e={};for(let[o,a]of Object.entries(Dr))n[o]!=null&&n[o]!==""&&(e[a]=String(n[o]));return e}function zr(n,e){let o=n.amnezia,a=o.obfuscation??{},r=c=>a[c]!=null&&a[c]!==""?String(a[c]):Pr[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Ar(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Hr(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nr(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),a=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Cn(n,e,o=!0){let a=new TextEncoder().encode(JSON.stringify(zr(n,e))),r=o?await Nr(a):null;return`vpn://${Hr(r??a)}`}var ko=[{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"}],Ct=n=>ko.find(e=>e.id===n),Rr={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)."},Ir={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function yo(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function Jt(n,e,o,a,r=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ko.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===a?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[yo(l.stealth,"Stealth"),yo(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[v("phone"),t("span",{},l.apps)]:[v("alert"),t("span",{},(r?Rr:Ir)[l.needs])])])}));return s(),i}function $o(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Eo=[["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 Br(n){let e=d=>n[d]!=null&&n[d]!=="",o=Eo.filter(([d])=>e(d));if(!o.length)return null;let a=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),r=(d,p,u,w)=>{let g=Eo.filter(([m])=>w.includes(m)&&e(m));return g.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},g.map(([m,k])=>a(m,k)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
`),c=t("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),c])}function Lo(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",a&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Or(n){let e=!1,o=t("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
var Va=Object.create;var Eo=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,Xa=Object.prototype.hasOwnProperty;var ei=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ti=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Za(e))!Xa.call(n,a)&&a!==o&&Eo(n,a,{get:()=>e[a],enumerable:!(r=Ya(e,a))||r.enumerable});return n};var ni=(n,e,o)=>(o=n!=null?Va(Qa(n)):{},ti(e||!n||!n.__esModule?Eo(o,"default",{value:n,enumerable:!0}):o,n));var Qo=ei((Yo,Zo)=>{"use strict";var Vo=(function(){var n=function(x,v){var $=236,E=17,y=x,z=o[v],h=null,f=0,T=null,S=[],N={},G=function(P,D){f=y*4+17,h=(function(_){for(var B=new Array(_),M=0;M<_;M+=1){B[M]=new Array(_);for(var j=0;j<_;j+=1)B[M][j]=null}return B})(f),q(0,0),q(f-7,0),q(0,f-7),J(),R(),le(P,D),y>=7&&Q(P),T==null&&(T=ne(y,z,S)),he(T,D)},q=function(P,D){for(var _=-1;_<=7;_+=1)if(!(P+_<=-1||f<=P+_))for(var B=-1;B<=7;B+=1)D+B<=-1||f<=D+B||(0<=_&&_<=6&&(B==0||B==6)||0<=B&&B<=6&&(_==0||_==6)||2<=_&&_<=4&&2<=B&&B<=4?h[P+_][D+B]=!0:h[P+_][D+B]=!1)},V=function(){for(var P=0,D=0,_=0;_<8;_+=1){G(!0,_);var B=a.getLostPoint(N);(_==0||P>B)&&(P=B,D=_)}return D},R=function(){for(var P=8;P<f-8;P+=1)h[P][6]==null&&(h[P][6]=P%2==0);for(var D=8;D<f-8;D+=1)h[6][D]==null&&(h[6][D]=D%2==0)},J=function(){for(var P=a.getPatternPosition(y),D=0;D<P.length;D+=1)for(var _=0;_<P.length;_+=1){var B=P[D],M=P[_];if(h[B][M]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[B+j][M+Z]=!0:h[B+j][M+Z]=!1}},Q=function(P){for(var D=a.getBCHTypeNumber(y),_=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[Math.floor(_/3)][_%3+f-8-3]=B}for(var _=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[_%3+f-8-3][Math.floor(_/3)]=B}},le=function(P,D){for(var _=z<<3|D,B=a.getBCHTypeInfo(_),M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<6?h[M][8]=j:M<8?h[M+1][8]=j:h[f-15+M][8]=j}for(var M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<8?h[8][f-M-1]=j:M<9?h[8][15-M-1+1]=j:h[8][15-M-1]=j}h[f-8][8]=!P},he=function(P,D){for(var _=-1,B=f-1,M=7,j=0,Z=a.getMaskFunction(D),Y=f-1;Y>0;Y-=2)for(Y==6&&(Y-=1);;){for(var ce=0;ce<2;ce+=1)if(h[B][Y-ce]==null){var xe=!1;j<P.length&&(xe=(P[j]>>>M&1)==1);var ee=Z(B,Y-ce);ee&&(xe=!xe),h[B][Y-ce]=xe,M-=1,M==-1&&(j+=1,M=7)}if(B+=_,B<0||f<=B){B-=_,_=-_;break}}},ue=function(P,D){for(var _=0,B=0,M=0,j=new Array(D.length),Z=new Array(D.length),Y=0;Y<D.length;Y+=1){var ce=D[Y].dataCount,xe=D[Y].totalCount-ce;B=Math.max(B,ce),M=Math.max(M,xe),j[Y]=new Array(ce);for(var ee=0;ee<j[Y].length;ee+=1)j[Y][ee]=255&P.getBuffer()[ee+_];_+=ce;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[Y],De.getLength()-1),ko=Ae.mod(De);Z[Y]=new Array(De.getLength()-1);for(var ee=0;ee<Z[Y].length;ee+=1){var $o=ee+ko.getLength()-Z[Y].length;Z[Y][ee]=$o>=0?ko.getAt($o):0}}for(var Co=0,ee=0;ee<D.length;ee+=1)Co+=D[ee].totalCount;for(var On=new Array(Co),Qt=0,ee=0;ee<B;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<j[Y].length&&(On[Qt]=j[Y][ee],Qt+=1);for(var ee=0;ee<M;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<Z[Y].length&&(On[Qt]=Z[Y][ee],Qt+=1);return On},ne=function(P,D,_){for(var B=l.getRSBlocks(P,D),M=c(),j=0;j<_.length;j+=1){var Z=_[j];M.put(Z.getMode(),4),M.put(Z.getLength(),a.getLengthInBits(Z.getMode(),P)),Z.write(M)}for(var Y=0,j=0;j<B.length;j+=1)Y+=B[j].dataCount;if(M.getLengthInBits()>Y*8)throw"code length overflow. ("+M.getLengthInBits()+">"+Y*8+")";for(M.getLengthInBits()+4<=Y*8&&M.put(0,4);M.getLengthInBits()%8!=0;)M.putBit(!1);for(;!(M.getLengthInBits()>=Y*8||(M.put($,8),M.getLengthInBits()>=Y*8));)M.put(E,8);return ue(M,B)};N.addData=function(P,D){D=D||"Byte";var _=null;switch(D){case"Numeric":_=d(P);break;case"Alphanumeric":_=p(P);break;case"Byte":_=u(P);break;case"Kanji":_=w(P);break;default:throw"mode:"+D}S.push(_),T=null},N.isDark=function(P,D){if(P<0||f<=P||D<0||f<=D)throw P+","+D;return h[P][D]},N.getModuleCount=function(){return f},N.make=function(){if(y<1){for(var P=1;P<40;P++){for(var D=l.getRSBlocks(P,z),_=c(),B=0;B<S.length;B++){var M=S[B];_.put(M.getMode(),4),_.put(M.getLength(),a.getLengthInBits(M.getMode(),P)),M.write(_)}for(var j=0,B=0;B<D.length;B++)j+=D[B].dataCount;if(_.getLengthInBits()<=j*8)break}y=P}G(!1,V())},N.createTableTag=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _="";_+='<table style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: "+D+"px;",_+='">',_+="<tbody>";for(var B=0;B<N.getModuleCount();B+=1){_+="<tr>";for(var M=0;M<N.getModuleCount();M+=1)_+='<td style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: 0px;",_+=" width: "+P+"px;",_+=" height: "+P+"px;",_+=" background-color: ",_+=N.isDark(B,M)?"#000000":"#ffffff",_+=";",_+='"/>';_+="</tr>"}return _+="</tbody>",_+="</table>",_},N.createSvgTag=function(P,D,_,B){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,B=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{Line truncated
`}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return F(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,B=D,M=_-D,j,Z,Y,ce,xe=Array(P+1).join("██"),ee=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(Y=Math.floor((j-B)/P),Ae="",Z=0;Z<_;Z+=1)ce=1,B<=Z&&Z<M&&B<=j&&j<M&&N.isDark(Y,Math.floor((Z-B)/P))&&(ce=0),Ae+=ce?xe:ee;for(Y=0;Y<P;Y+=1)De+=Ae+`
`}return De.substring(0,De.length-1)},N.renderTo2dContext=function(P,D){D=D||2;for(var _=N.getModuleCount(),B=0;B<_;B++)for(var M=0;M<_;M++)P.fillStyle=N.isDark(B,M)?"black":"white",P.fillRect(B*D,M*D,D,D)},N};n.stringToBytesFuncs={default:function(x){for(var v=[],$=0;$<x.length;$+=1){var E=x.charCodeAt($);v.push(E&255)}return v}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(x,v){var $=(function(){for(var y=m(x),z=function(){var R=y.read();if(R==-1)throw"eof";return R},h=0,f={};;){var T=y.read();if(T==-1)break;var S=z(),N=z(),G=z(),q=String.fromCharCode(T<<8|S),V=N<<8|G;f[q]=V,h+=1}if(h!=v)throw h+" != "+v;return f})(),E=63;return function(y){for(var z=[],h=0;h<y.length;h+=1){var f=y.charCodeAt(h);if(f<128)z.push(f);else{var T=$[y.charAt(h)];typeof T=="number"?(T&255)==T?z.push(T):(z.push(T>>>8),z.push(T&255)):z.push(E)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var x=[[],[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]],v=1335,$=7973,E=21522,y={},z=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return y.getBCHTypeInfo=function(h){for(var f=h<<10;z(f)-z(v)>=0;)f^=v<<z(f)-z(v);return(h<<10|f)^E},y.getBCHTypeNumber=function(h){for(var f=h<<12;z(f)-z($)>=0;)f^=$<<z(f)-z($);return h<<12|f},y.getPatternPosition=function(h){return x[h-1]},y.getMaskFunction=function(h){switch(h){case r.PATTERN000:return function(f,T){return(f+T)%2==0};case r.PATTERN001:return function(f,T){return f%2==0};case r.PATTERN010:return function(f,T){return T%3==0};case r.PATTERN011:return function(f,T){return(f+T)%3==0};case r.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case r.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case r.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case r.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+h}},y.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),T=0;T<h;T+=1)f=f.multiply(s([1,i.gexp(T)],0));return f},y.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){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:"+h}else if(f<27)switch(h){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:"+h}else if(f<41)switch(h){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:"+h}else throw"type:"+f},y.getLostPoint=function(h){for(var f=h.getModuleCount(),T=0,S=0;S<f;S+=1)for(var N=0;N<f;N+=1){for(var G=0,q=h.isDark(S,N),V=-1;V<=1;V+=1)if(!(S+V<0||f<=S+V))for(var R=-1;R<=1;R+=1)N+R<0||f<=N+R||V==0&&R==0||q==h.isDark(S+V,N+R)&&(G+=1);G>5&&(T+=3+G-5)}for(var S=0;S<f-1;S+=1)for(var N=0;N<f-1;N+=1){var J=0;h.isDark(S,N)&&(J+=1),h.isDark(S+1,N)&&(J+=1),h.isDark(S,N+1)&&(J+=1),h.isDark(S+1,N+1)&&(J+=1),(J==0||J==4)&&(T+=3)}for(var S=0;S<f;S+=1)for(var N=0;N<f-6;N+=1)h.isDark(S,N)&&!h.isDark(S,N+1)&&h.isDark(S,N+2)&&h.isDark(S,N+3)&&h.isDark(S,N+4)&&!h.isDark(S,N+5)&&h.isDark(S,N+6)&&(T+=40);for(var N=0;N<f;N+=1)for(var S=0;S<f-6;S+=1)h.isDark(S,N)&&!h.isDark(S+1,N)&&h.isDark(S+2,N)&&h.isDark(S+3,N)&&h.isDark(S+4,N)&&!h.isDark(S+5,N)&&h.isDark(S+6,N)&&(T+=40);for(var Q=0,N=0;N<f;N+=1)for(var S=0;S<f;S+=1)h.isDark(S,N)&&(Q+=1);var le=Math.abs(100*Q/f/f-50)/5;return T+=le*10,T},y})(),i=(function(){for(var x=new Array(256),v=new Array(256),$=0;$<8;$+=1)x[$]=1<<$;for(var $=8;$<256;$+=1)x[$]=x[$-4]^x[$-5]^x[$-6]^x[$-8];for(var $=0;$<255;$+=1)v[x[$]]=$;var E={};return E.glog=function(y){if(y<1)throw"glog("+y+")";return v[y]},E.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return x[y]},E})();function s(x,v){if(typeof x.length>"u")throw x.length+"/"+v;var $=(function(){for(var y=0;y<x.length&&x[y]==0;)y+=1;for(var z=new Array(x.length-y+v),h=0;h<x.length-y;h+=1)z[h]=x[h+y];return z})(),E={};return E.getAt=function(y){return $[y]},E.getLength=function(){return $.length},E.multiply=function(y){for(var z=new Array(E.getLength()+y.getLength()-1),h=0;h<E.getLength();h+=1)for(var f=0;f<y.getLength();f+=1)z[h+f]^=i.gexp(i.glog(E.getAt(h))+i.glog(y.getAt(f)));return s(z,0)},E.mod=function(y){if(E.getLength() Line truncated
`)}function $i(n){let e=new Map(n.people.map(r=>[r.id,r.name])),o=new Map(n.people.flatMap(r=>r.devices.map(a=>[a.id,a.name])));return{people:e,devices:o}}function Fe(n,e,o,r="",a=[]){let i=$i(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${r?`-${r}`:""}-${l}.${o}`;if(o==="json"){Se(c,JSON.stringify(s,null,2),"application/json");return}Se(c,rr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ci=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],ar=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,o,r,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Et.map(c=>t("option",{value:c,selected:c===a?"selected":null},pt[c])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ci.map(([c,d])=>t("option",{value:c},d)));te(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ae()," ",H("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await A.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){U(be(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await A.serviceLogClear(l.value)).removed}catch(d){oe(),U(`${s.value==="system"?"":`Activity: ${ar(c).toLowerCase()}. `}The service log was not cleared: ${be(d)}`,"error",1e4),r();return}oe(),U(ar(c),"success",3e3),r()},"negative")])}function Lt(n,e,o,r){let a=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";te(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},a)],[ae()," ",H("Reset",async()=>{await W(()=>A.usageClear(n,e),"Traffic history reset")&&(oe(),r())},"negative")])}function ve(n,e,o){let r=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!r.classList.contains("on");Qn(r,a),o?.(a)}},t("i"));return r}function Qn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let r=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),a=()=>r.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===r.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)r.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==r.dataset.value&&(o.optimistic!==!1&&(r.dataset.value=i,a()),o.onChange?.(i))}},s));return a(),r}function qe(n,e,o,r={}){return t("button",{type:"button",...r,class:`dl-chipbtn${e?" on":""}${r.class?` ${r.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function pn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function ie(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ei={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Li={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 Mi(n){let e={};for(let[o,r]of Object.entries(Li))n[o]!=null&&n[o]!==""&&(e[r]=String(n[o]));return e}function Ti(n,e){let o=n.amnezia,r=o.obfuscation??{},a=c=>r[c]!=null&&r[c]!==""?String(r[c]):Ei[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Mi(r),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Si(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _i(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(o).arrayBuffer()),a=new Uint8Array(4+r.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(r,4),a}catch{return null}}async function Xn(n,e,o=!0){let r=new TextEncoder().encode(JSON.stringify(Ti(n,e))),a=o?await _i(r):null;return`vpn://${Si(a??r)}`}var sr=[{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:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{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"}],jt=n=>sr.find(e=>e.id===n),un=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Pi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Di={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ir(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function mn(n,e,o,r,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,sr.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===r?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ir(l.stealth,"Stealth"),ir(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Pi:Di)[l.needs])])])}));return s(),i}function lr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var dr=[["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 Ai(n){let e=d=>n[d]!=null&&n[d]!=="",o=dr.filter(([d])=>e(d));if(!o.length)return null;let r=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),a=(d,p,u,w)=>{let C=dr.filter(([g])=>w.includes(g)&&e(g));return C.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},C.map(([g,m])=>r(g,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
`),c=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("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"]),a("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 t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),c])}function cr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let r=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",r&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Hi(n){let e=!1,o=t("pre",{class:"dl-conf"}),r=()=>dom.content(o,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,Lo(s,e)]:[Lo(s,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([v("download")," Download"],()=>Ee(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),o])])}async function jr(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Cn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>t("div",{class:"dl-qr-pane"},[Fe(ht(n.conf),"dl-qr"),t("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),D("Copy",()=>ue(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Or(n)},r=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(r,a[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,r])}async function Ur(n,e,o,a){let r=Ct(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await ae(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await W(()=>P.serverObfuscation(e.id,o),a?"New values applied":`${r.title} applied`)&&(Q("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Wr(n,e){let o=n.st,a=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=`${e.mtus.computer} for computers and routers, ${e.mtus.phone} for phones and tablets`,s=e.mtu?`Now ${i}. Empty = automatic.`:`Automatic by device type and disguise: now ${i}. Lower it if some sites hang.`,l=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),c=Ct(e.preset)?e.preset:void 0,d=c??"standard",p=D("",()=>Ur(n,e,d,d===c),"neutral"),u=()=>dom.content(p,d===c?[v("reset")," Generate new values"]:[`Switch to ${Ct(d).title}`]);u();let w=o.awg_state?.tools!==!1;return St("",[$o("AmneziaWG",e.ifname),he("globe","Listening","Where devices reach this core from the internet",[ne("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ne("MTU",r,s),ne("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Jt(o.awg,d,g=>{d=g,u()},c,w),w&&!o.awg.v3?mt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Br(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),p])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ne("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ne("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ne("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),D([v("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:l.value},"AmneziaWG saved"),"positive")])}function Gr(n){let e=Ct(n.preset),o=n.obf??{},a=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(c=>t("i",{class:c<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2" Line truncated
`),"Log copied"))]),p,u]),[w],"wide"),m([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let H=o??null,B=o?.id,E,y=0,S=h=>{B!==h.id&&(B=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await P.updatesStatus().catch(()=>null);E=h?.job?.id,y=h?.now??0;let f=await P.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==E&&(H=f.job,S(f.job))}catch(h){return g=[ve(h)],p.textContent=g[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},ve(h))])),m([k(!0)]),Q(ve(h),"error"),null}let b=null,x=0;for(;;){if(await ta(1e3),b=await P.updatesStatus().catch(()=>null),!b){if(++x>60)break;continue}x=0;let h=b.job;if(!h||!ea(h,B,E,y)){if(Date.now()-i>15e3)break;continue}if(S(h),H=h,h.log.length){g=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=g.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Qo(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=Zo((h.finished??b.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!H||H.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),m([k()]),e.onDone?.(b),H;if(H.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},H.error??"Operation failed"),r?"":". Nothing else was changed."])])),m([D("Copy log",()=>ue(g.join(`
`),"Log copied")),k(!0)]),Q(`${sn[a]??"Update"}: ${H.error??"failed"}`,"error"),e.onDone?.(b),H;if(c.className="dl-pill ok",c.textContent="Finished",r&&b){let h=Xo(b,a);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[v(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),Q(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(b),h.update&&e.onUpdate){let f=b;m([k(),D(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else m([k()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return H}if(a==="app"&&H.to){let h=H.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let R=()=>{ui.menu?.flushCache(),location.reload()};m([k(),D("Reload now",R,"positive")]),Q(`Dawnline updated to ${h}`,"success",6e3);for(let C=1;C<=30;C++)if(f.textContent=`Waiting for the router to restart its services (${C} of 30)…`,await ta(1500),(await P.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(R,800),H;return f.textContent="Services restarted. Reload the page to use the new version.",H}let M=a==="pkgs"?`Updated ${[...H.result?.pkgs?.updated??[],...H.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${H.to?` ${H.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},M)])),m([k()]),Q(M,"success"),e.onDone?.(b),H}var bi={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function na(n,e,o,a){return!await ae(`Install ${e}?`,o,"Install")||(await Nt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function dn(n){return na("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Rt(n,e,o){return n==="awg"?dn(o):e.length?na(`pkgs:${e.join(",")}`,bi[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function oa(n,e){if(n==="awg")return dn(e);let o=await W(()=>P.updatesStatus());return o?Rt(n,o.needs?.[n]??[],e):!1}var xi=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],wi={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function aa(n,e,o){let a=n.id,r=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,g=Jo(r,a,o),m=new Set,k="",H=()=>JSON.stringify([p,l,l?"":c,d,[...m].sort()]),B=()=>s.detected.lan||s.saved.lan||"",E=()=>(l?s.detected.wan||s.saved.wan:c)||"",y=()=>new Map(s.devices.map(z=>[z.name,z])),S=()=>{let z=y();return[...d&&B()?[B()]:[],...[...m].filter(X=>X!==B())].filter(X=>X!==E()).map(X=>z.get(X)??{name:X,nets:[],missing:!0})},b=(z,q)=>{s=z,q&&(l=z.config.auto_wan,c=z.config.wan_device||z.detected.wan||z.saved.wan||"",d=z.config.auto_lan,p=z.config.lan_like,u=z.config.mesh??(z.config.device_mesh?"all":"off"),m=new Set(z.config.lan_devices),k=H()),G()},x=async z=>{let q=await P.interfaces(a).catch(X=>(Q(X.message,"error"),null));q&&b(q,z)};function M(z){let q=d&&z.name===B(),X=!!z.own||!!z.master||z.name===E()||q;return q||m.has(z.name)||!X&&(z.nets.length>0||!!z.missing)}function h(z){let q=d&&z.name===B(),X=z.name===E(),de=!q&&m.has(z.name),O=!(!!z.own||!!z.master||X||q)&&(z.nets.length>0||de||!!z.missing),U=(de||q)&&!z.zone&&!z.missing,F=z.missing?"Not present right now":z.own?"This server":z.master?`Port of ${z.master}`:X?`Internet${z.zone?` · zone ${z.zone}`:""}`:z.nets.length?z.nets.join(", "):"No IPv4 network",oe=t("button",{type:"button",class:`dl-if${de?" sel":""}${q?" auto":""}${!O&&!de&&!q?" off":""}${U?" warn":""}`,"aria-pressed":de||q?"true":"false","aria-disabled":O?null:"true",click:()=>{O&&(m.has(z.name)?m.delete(z.name):m.add(z.name),G())}},[t("span",{class:"dl-if-ic"},v(wi[z.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},z.name),t("span",{class:"dl-if-sub"},F)]),q?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return me(oe,()=>[t("div",{class:"dl-tip-title"},z.name),t("div",{class:"dl-muted"},[z.logical?`Interface ${z.logical}`:"No netifd interface",z.zone?` · zone ${z.zone}`:" · no firewall zone"]),z.members.length?t("div",{class:"dl-muted"},`Ports: ${z.members.join(", ")}`):"",z.nets.length?t("div",{class:"dl-mono"},z.nets.join(", ")):"",U?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",z.master?t("div",{class:"dl-muted"},`Choose ${z.master} to include it.`):""]),oe}function f(){let z=s.like_home;return!p||!s.config.lan_like Line truncated
`,cr(s,e)]:[cr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),r()}},[b("key"),"Show key"]);r();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Se(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),o])])}function eo(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([r,a])=>a==null||a===""||a===(o[r]??"0"))}async function zi(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Xn(n,`${n.server} · ${n.person} · ${n.name}`),r={qr:()=>t("div",{class:"dl-qr-pane"},[Xe(Ct(n.conf),"dl-qr"),t("span",{class:"dl-sub"},eo(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),H("Copy",()=>pe(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Hi(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(a,r[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function Ni(n,e,o,r){let a=jt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await se(r?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":o==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,r?"Generate and apply":"Switch and apply",!0)&&await W(()=>A.serverObfuscation(e.id,o),r?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Ri(n,e){let o=n.st,r=ie(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=ie(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ie(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??un(o.awg),c=H("",()=>Ni(n,e,l,l===s),"neutral"),d=()=>dom.content(c,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);d();let p=o.awg_state?.tools!==!1,u=[],w=fe("UDP port",r,()=>It(Number(r.value),u,`Opened on the WAN firewall automatically.${Number(r.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],w.refresh()}).catch(()=>{});let C=fe("MTU",a,()=>Bo(a.value,e.mtus)),g=fe("Keep-alive",i,()=>Oo(i.value));return Rt("",[lr("AmneziaWG",e.ifname),ge("globe","Listening","Where devices reach this core from the internet",[w]),ge("file","In every device configuration","Changing these marks devices “Update config” until they import again",[C,g]),ge("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?ct("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",mn(o.awg,l,m=>{l=m,d()},s,p),p&&!o.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Ai(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),c])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[de("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),de("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet) Line truncated
`),"Log copied"))]),p,u]),[w],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let k=o??null,I=o?.id,x,v=0,$=h=>{I!==h.id&&(I=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await A.updatesStatus().catch(()=>null);x=h?.job?.id,v=h?.now??0;let f=await A.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==x&&(k=f.job,$(f.job))}catch(h){return C=[be(h)],p.textContent=C[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(h))])),g([m(!0)]),U(be(h),"error"),null}let E=null,y=0;for(;;){if(await Br(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++y>60)break;continue}y=0;let h=E.job;if(!h||!Ir(h,I,x,v)){if(Date.now()-i>15e3)break;continue}if($(h),k=h,h.log.length){C=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=C.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Nr(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=zr((h.finished??E.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!k||k.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),g([m()]),e.onDone?.(E),k;if(k.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},k.error??"Operation failed"),a?"":". Nothing else was changed."])])),g([H("Copy log",()=>pe(C.join(`
`),"Log copied")),m(!0)]),U(`${Cn[r]??"Update"}: ${k.error??"failed"}`,"error"),e.onDone?.(E),k;if(c.className="dl-pill ok",c.textContent="Finished",a&&E){let h=Rr(E,r);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[b(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),U(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(E),h.update&&e.onUpdate){let f=E;g([m(),H(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else g([m()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&oe(),1200);return k}if(r==="app"&&k.to){let h=k.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let T=()=>{ui.menu?.flushCache(),location.reload()};g([m(),H("Reload now",T,"positive")]),U(`Dawnline updated to ${h}`,"success",6e3);for(let S=1;S<=30;S++)if(f.textContent=`Waiting for the router to restart its services (${S} of 30)…`,await Br(1500),(await A.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(T,800),k;return f.textContent="Services restarted. Reload the page to use the new version.",k}let z=r==="pkgs"?`Updated ${[...k.result?.pkgs?.updated??[],...k.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:r==="amneziawg"?`AmneziaWG${k.to?` ${k.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),g([m()]),U(z,"success"),e.onDone?.(E),k}var ss={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Or(n,e,o,r){return!await se(`Install ${e}?`,o,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>r?.(),4e3),!0)}function Ln(n){return Or("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Vt(n,e,o){return n==="awg"?Ln(o):e.length?Or(`pkgs:${e.join(",")}`,ss[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function jr(n,e){if(n==="awg")return Ln(e);let o=await W(()=>A.updatesStatus());return o?Vt(n,o.needs?.[n]??[],e):!1}var ls=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],ds={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ur(n,e,o){let r=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,C=Dr(a,r,o),g=new Set,m="",k=()=>JSON.stringify([p,l,l?"":c,d,[...g].sort()]),I=()=>s.detected.lan||s.saved.lan||"",x=()=>(l?s.detected.wan||s.saved.wan:c)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),$=()=>{let R=v();return[...d&&I()?[I()]:[],...[...g].filter(Q=>Q!==I())].filter(Q=>Q!==x()).map(Q=>R.get(Q)??{name:Q,nets:[],missing:!0})},E=(R,J)=>{s=R,J&&(l=R.config.auto_wan,c=R.config.wan_device||R.detected.wan||R.saved.wan||"",d=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),g=new Set(R.config.lan_devices),m=k()),q()},y=async R=>{let J=await A.interfaces(r).catch(Q=>(U(Q.message,"error"),null));J&&E(J,R)};function z(R){let J=d&&R.name===I(),Q=!!R.own||!!R.master||R.name===x()||J;return J||g.has(R.name)||!Q&&(R.nets.length>0||!!R.missing)}function h(R){let J=d&&R.name===I(),Q=R.name===x(),le=!J&&g.has(R.name),ue=!(!!R.own||!!R.master||Q||J)&&(R.nets.length>0||le||!!R.missing),ne=(le||J)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Q?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",F=t("button",{type:"button",class:`dl-if${le?" sel":""}${J?" auto":""}${!ue&&!le&&!J?" off":""}${ne?" warn":""}`,"aria-pressed":le||J?"true":"false","aria-disabled":ue?null:"true",click:()=>{ue&&(g.has(R.name)?g.delete(R.name):g.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(ds[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),J?t("span",{class:"dl-if-badge ok"},"Auto"):le?t("span",{class:"dl-if-check"},b("check")):""]);return me(F,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ne?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),F}function f(){let R=s.like_home;return!p||!s.config.lan_ Line truncated
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(r.length&&s(),a||(a=t("ul",{}),e.push(a)),a.appendChild(t("li",{},o(p[1])))):c.trim()?(a&&(a=null),r.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function ka(n){let e=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||e.push(a)}return e.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(a.length&&s(),r||(r=t("ul",{}),e.push(r)),r.appendChild(t("li",{},o(p[1])))):c.trim()?(r&&(r=null),a.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function ia(n){let e=[],o=!1;for(let r of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(r);if(a){if(o=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(r)&&(o=!1);o||e.push(r)}return e.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function Bt(n,e,o,a){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";re(o,[i,r],[D([v("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",le("Close")],"wide");try{let l=await P.updatesNotes(n,e,a??"");s=ka(l.body||"");let c=wa(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ne(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(r,s.trim()?ya(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,t("p",{class:"dl-muted"},ve(l)))}}var $a={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Jn=n=>n?Ne(n):"";function Hi(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function La(n,e){let o=n.st,a=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Bt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ni(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,p=(w,g)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},g)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ae(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Jn(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Jn(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Ri(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[a.auto?ye("ok","On"):ye("","Off"),t("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${$a[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${$a[a.interval]}`:"checks off")]),p("Last check",o.check?[ie(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${ct(d-o.now)}`):""]:["Never"]),p("Rollback",r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function Ni(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Hi(a(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ri(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&gn(n,e)}),n.versOpen&&gn(n,e),o}async function gn(n,e){let o=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return Q("Enter a release tag like 0.3.1","warning");Ea(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),a(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),gn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${ve(p)}`),D("Try again",()=>gn(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[r,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[r,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Jn(p.published)),p.prerelease?ye("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},$e("file","What’s new",()=>Bt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?ye("ok","Installed"):D("Install",()=>Ea(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function Ea(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ae(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function Ma(n,e){let o=n.st,a=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),s=e?.current??null,l=s?r[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),a&&u.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ae(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Bt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,R)=>h!==null||f>0&&R[f-1]!==null),g=o.tunnels??[],m=g.length?`Switching restarts ${g.length===1?"the tunnel":`${g.length} tunnels`} for a few seconds: ${g.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",k=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0],H=g.length?`Switching restarts ${k} for a few seconds.`:"Switching takes a few seconds.",B=async h=>{let f=r[h];await ae(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${m}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},E=h=>{let f=r[h],R=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},R?ye("ok","Active"):f.version?D(p?"Switch":"Install",()=>B(h),p?"neutral":"positive",{disabled:n.busy}):ye("","No build"))])},y=i.map(h=>r[h]?.newer?`${r[h].label} moves to ${r[h].newer.gen} with OpenWrt ${r[h].newer.tag.replace( Line truncated
`)}r.push(p),l+=d-1}let s=D([v("more")],()=>we(s,[{label:"Export CSV",icon:v("download"),run:()=>Ue(o,a,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Ue(o,a,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>qe(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),t("span",{class:"dl-spacer"}),s]),r.length?r:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var bn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,a,r]=await Promise.all([P.status(30),e?P.events(5e3).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let a=t("div",{},[t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:xt(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:xt(o.server)},"People"),t("span",{},"/"),t("span",{},o.name)]),this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>Be(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>rt(this.p,this.deviceOpts()),50),this.poller=Je({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=xt(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let a=await W(()=>P.personUpdate(this.p.id,e),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Re(this.series.length?this.series:this.st.series)}get core(){return vt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(e=!1){Le(this.parts.head,Ha(this),e),Le(this.parts.traffic,Na(this),e),Le(this.parts.devices,Ra(this),e),Le(this.parts.limits,Ga(this),e),this.paintPlaces(e),Le(this.parts.activity,qa(this),e)}paintPlaces(e=!1){let o=Fa(this);o&&Le(this.parts.places,o,e&&!this.mapOpen)}};var Ki={ok:"check",warn:"alert",error:"x",skip:"pause"},xn=class{constructor(e,o,a,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(e){let o=e?await mn(e):await P.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,a=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?mt("error",`${o} problem${o>1?"s":""} need attention.`):a?mt("warn",`${a} warning${a>1?"s":""}.`):mt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id Line truncated
`);function lr(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=ps,n}function st(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async a=>{let r=await e.render(a),i=document.createElement("div");return i.className="dl-root",i.append(lr(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var $g=st(It),Eg=st(it),Lg=st(It),Mg=st(fn),Sg=st(bn),_g=st(kn),Tg=st(vn);function dr(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Cg=dr(""),Pg=dr("log");return baseclass.extend({ activity: Pg, diagnostics: _g, health: Cg, overview: $g, people: Eg, person: Sg, server: Lg, settings: Mg, updates: Tg });
`).trim()}async function Zt(n,e,o,r){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";te(o,[i,a],[H([b("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",ae("Close")],"wide");try{let l=await A.updatesNotes(n,e,r??"");s=ia(l.body||"");let c=ra(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",b("open")]):""]),dom.content(a,s.trim()?aa(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},bo=n=>n?Ue(n):"";function Cs(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function da(n,e){let o=n.st,r=o.policy,a=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Zt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Es(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=r.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[r.interval]??24)*3600:0,p=(w,C)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},C)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},b("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${bo(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${bo(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[H("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),H("What’s new",s(i))]):"",Ls(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[b("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[r.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},r.auto?r.mode==="immediate"?"as soon as found":`${sa[r.interval]==="weekly"?"weekly":"daily"} at ${r.time}`:r.check?`checks ${sa[r.interval]}`:"checks off")]),p("Last check",o.check?[re(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${vt(d-o.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},r.keep?"Kept after the next update":"Off")])])])}function Es(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let r=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await A.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await A.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Cs(r(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ls(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[b("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&An(n,e)}),n.versOpen&&An(n,e),o}async function An(n,e){let o=ie("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),r=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");la(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),r(o.value))});let a=t("div",{class:"dl-comp-tag"},[o,H("Install",()=>r(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),An(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await A.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),H("Try again",()=>An(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[a,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},bo(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?Ee("ok","Installed"):H("Install",()=>la(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function la(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function ca(n,e){let o=n.st,r=o.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),r&&u.push({label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${r.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,T)=>h!==null||f>0&&T[f-1]!==null),C=o.tunnels??[],g=C.length?`Switching restarts ${C.length===1?"the tunnel":`${C.length} tunnels`} for a few seconds: ${C.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=C.length>1?`${C.slice(0,-1).join(", ")} and ${C[C.length-1]}`:C[0],k=C.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",I=async h=>{let f=a[h];await se(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${g}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},x=h=>{let f=a[h],T=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},T?Ee("ok","Active"):f.version?H(p?"Switch":"Install",()=>I(h),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},v=i.map(h=>a[h]?.newer?`${a[h].label} moves to ${a[h].newer.gen} with OpenWrt ${a[h].newer.tag.replace( Line truncated
`)}a.push(p),l+=d-1}let s=H([b("more")],()=>Ce(s,[{label:"Export CSV",icon:b("download"),run:()=>Fe(o,r,"csv",e.id)},{label:"Export JSON",icon:b("download"),run:()=>Fe(o,r,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:b("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},r.length>10?`latest 10 of ${r.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var zn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,r,a]=await Promise.all([A.status(30),e?A.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?A.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:r?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let r=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&o.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>We(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>r.isConnected,apply:(s,l)=>this.apply(s,l)}),r}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let r=this.st.people.find(a=>a.id===this.id);if(!r){o||(location.href=St(this.p?.server));return}this.p=r,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let r=await W(()=>A.personUpdate(this.p.id,e),o);if(!r)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=r.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=r.person),this.p=r.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return Mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:St(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:St(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Te(this.parts.crumbs,this.crumbs(),e),Te(this.parts.head,wa(this),e),Te(this.parts.traffic,ya(this),e),Te(this.parts.devices,ka(this),e),Te(this.parts.limits,Sa(this),e),this.paintPlaces(e),Te(this.parts.activity,Pa(this),e)}paintPlaces(e=!1){let o=_a(this);o&&Te(this.parts.places,o,e&&!this.mapOpen)}};var Ns={ok:"check",warn:"alert",error:"x",skip:"pause"},Nn=class{constructor(e,o,r,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=r,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,r)}async run(e){let o=e?await _n(e):await A.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,r=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ct("error",`${o} problem${o>1?"s":""} need attention.`):r?ct("warn",`${r} warnLine truncated
`);function Ka(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=el,n}function mt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async r=>{let a=await e.render(r),i=document.createElement("div");return i.className="dl-root",i.append(Ka(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Iv=mt(Yt),Bv=mt(ut),Ov=mt(Yt),jv=mt(Dn),Uv=mt(zn),Wv=mt(Bn),Gv=mt(Hn);function Ja(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var Fv=Ja(""),qv=Ja("log");return baseclass.extend({ activity: qv, diagnostics: Wv, health: Fv, overview: Iv, people: Bv, person: Uv, server: Ov, settings: jv, updates: Gv });
@@ -5,5 +5,7 @@ case "$ACTION" in ifup|ifdown|ifup-failed) ;; *) exit 0 ;; esac
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
# In order (a quick down/up must not log up first).
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
[ "$ACTION" = ifup ] && /usr/bin/dawnline sync >/dev/null 2>&1 &
# A disabled Dawnline leaves the tunnels empty: nothing would enforce end
# dates, limits or hours once the devices were loaded.
[ "$ACTION" = ifup ] && /etc/init.d/dawnline enabled && /usr/bin/dawnline sync >/dev/null 2>&1 &
exit 0
@@ -21,9 +21,15 @@ start_portal() {
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
# Portal processes at once: each loads the whole model (a burst of 16 could
# empty a 128 MB router), so four, and two on a router with little memory;
# the rest of 64 connections wait their turn.
local procs=4 mem
mem="$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)"
[ -n "$mem" ] && [ "$mem" -le 160 ] && procs=2
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 \
-D -n "$procs" -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
@@ -1,6 +1,13 @@
#!/bin/sh
# Dawnline first-run / upgrade housekeeping.
# Locations are off by default since 0.5.2 (lookups send addresses to a third
# party); a router that had them on by the old default keeps them on.
if [ -f /etc/config/dawnline ] && [ -z "$(uci -q get dawnline.settings.geo_enabled)" ]; then
uci -q set dawnline.settings.geo_enabled=1
uci -q commit dawnline
fi
[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG'
config settings 'settings'
option portal_enabled '0'
@@ -50,6 +57,12 @@ grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root || {
# 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
# A fresh install starts the service; an upgrade restarts it only where the
# admin had it on (a disabled Dawnline stays that way).
if [ "$PKG_UPGRADE" = 1 ]; then
/etc/init.d/dawnline enabled && /etc/init.d/dawnline restart
else
/etc/init.d/dawnline enable
/etc/init.d/dawnline restart
fi
exit 0
+165 -30
View File
@@ -12,11 +12,31 @@ import * as pc from 'dawnline.portalcert';
import * as watchdog from 'dawnline.watchdog';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import {
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util';
const args = ARGV;
/** Options that take no value. */
const FLAGS = [ 'json', 'yes', 'conf' ];
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
const opts = {};
const args = [];
for (let i = 0; i < length(ARGV); i++) {
let a = ARGV[i];
if (a == '-n')
a = '--n';
if (substr(a, 0, 2) == '--') {
let name = substr(a, 2);
if (index(FLAGS, name) >= 0)
opts[name] = true;
else
opts[name] = ARGV[++i] ?? '';
}
else
push(args, a);
}
const cmd = args[0] ?? 'help';
function out(v) {
@@ -24,10 +44,41 @@ function out(v) {
}
function opt(name, dflt) {
for (let i = 1; i < length(args); i++)
if (args[i] == `--${name}`)
return args[i + 1];
return dflt;
return opts[name] ?? dflt;
}
/** Fixed-width columns: a header, then one line per row. */
function table(cols, rows) {
let w = map(cols, (c) => length(c));
for (let r in rows)
for (let i, v in r)
w[i] = max(w[i], length(`${v}`));
let line = (r) => rtrim(join(' ', map(r, (v, i) => sprintf(`%-${w[i]}s`, `${v}`))));
out(line(cols));
for (let r in rows)
out(line(r));
}
/** `--since 30m|2h|3d|YYYY-MM-DD` as a time, or null. */
function since_time(s) {
if (!s)
return null;
let m = match(s, /^([0-9]+)([mhd])$/);
if (m)
return time() - +m[1] * { m: 60, h: 3600, d: 86400 }[m[2]];
m = match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
if (m)
return timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 0, min: 0, sec: 0 });
die('--since takes 30m, 2h, 3d or a date like 2026-10-18.');
}
/** "5m", "3h", "2d": how long ago, for the lists. */
function ago(secs) {
return secs < 3600 ? `${int(secs / 60)}m` : secs < 86400 ? `${int(secs / 3600)}h` : `${int(secs / 86400)}d`;
}
function the_person(m, slug) {
return m.people[slug ?? ''] ?? die(slug ? `Unknown person: ${slug}.` : 'Which person? Give their id (dawnline person ls).');
}
function help() {
@@ -39,19 +90,24 @@ Usage: dawnline <command>
sync Push devices and access rules to the tunnels
status People and devices with live state (JSON)
health Run health checks (JSON)
person ls [--json] Everyone: id, name, access, state, devices, last seen
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]
[--expires YYYY-MM-DD] [--quota GB] [--server id]
person link <id> Print the personal portal link
person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
device ls [person] [--json]
device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
device conf <id> Print a device configuration (.conf)
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
log Service log: tunnel and service starts, stops, repairs (newest first)
log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
Service log: tunnel and service starts, stops, repairs (newest first)
teardown Remove everything Dawnline created on the router
version`);
version
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
}
/*
@@ -106,40 +162,100 @@ try {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
}
else if (cmd == 'health')
out(health.health());
else if (cmd == 'health') {
let checks = health.health();
out(checks);
if (length(filter(checks, (c) => c.status == 'error')))
exit(1);
}
else if (cmd == 'person' && args[1] == 'ls') {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
if (opts.json)
out(people);
else
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
]));
}
else if (cmd == 'person' && args[1] == 'add') {
let id = store.transact((c, m) => core.create_person(c, m, {
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
}));
let m2 = core.load();
out(core.portal_url(m2, m2.people[id]) ?? id);
live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
out(`Added ${m2.people[id].name} (${id})`);
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
}
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.');
let p = the_person(m, args[2]);
out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
}
else if (cmd == 'person' && args[1] == 'rm') {
store.transact((c, m) => core.delete_person(c, m, args[2]));
apply.sync();
let m = core.load();
let p = the_person(m, args[2]);
let n = length(p.devices);
if (n && !opts.yes)
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
store.transact((c, m) => core.delete_person(c, m, p.id));
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
let s = apply.sync();
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
if (s.warning)
warn(`dawnline: ${s.warning}\n`);
}
else if (cmd == 'device' && args[1] == 'ls') {
let m = core.load(), d = live.dump(m);
let who = args[2] ? the_person(m, args[2]) : null;
let rows = [];
for (let id, dev in m.devices) {
let p = m.people[dev.person];
if (!p || (who && p.id != who.id))
continue;
let peer = d.peers[dev.public_key];
let online = live.online(d, id, peer);
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
online, handshake: +(peer?.handshake ?? 0) });
}
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
if (opts.json)
out(rows);
else
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
r.id, r.person, r.name, r.kind, r.address,
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
]));
}
else if (cmd == 'device' && args[1] == 'add') {
// Keys first: generating them runs the awg tool, not worth holding the config lock for.
let keys = awg.new_keys();
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys }));
apply.sync();
out(id);
// Through the same door as LuCI and the portal: event, "issued" marker, capability check.
let m = core.load();
let p = the_person(m, args[2]);
if (!args[3])
die('Which name? dawnline device add <person> <name>.');
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
if (opts.conf)
print(r.config.conf);
else
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
}
else if (cmd == 'device' && args[1] == 'conf') {
let m = core.load();
let d = m.devices[args[2]] ?? die('Unknown device.');
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
awg.mark_issued(m, d.id);
print(awg.client_config(m, d).conf);
}
else if (cmd == 'device' && args[1] == 'rm') {
store.transact((c, m) => core.delete_device(c, m, args[2]));
apply.sync();
let m = core.load();
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
let r = devices.remove(d.id, { by: 'admin' });
out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
}
else if (cmd == 'backup')
out(backup.backup_create(opt('reason')));
@@ -153,7 +269,22 @@ try {
out(`${core.portal_http_port(m)}`);
}
else if (cmd == 'log') {
for (let e in watchdog.view(core.load()).log) {
let n = +opt('n', 0) || 0;
let since = since_time(opt('since'));
let level = opt('level'), src = opt('src');
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
die('--level takes error, down, repair, up or info.');
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
die('--src takes awg, dawnline or portal.');
let log = filter(slog_read(n && !since && !level && !src ? n : null),
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
if (n && length(log) > n)
log = slice(log, 0, n);
if (opts.json) {
out(log);
exit(0);
}
for (let e in log) {
let t = localtime(e.ts);
let text = e.by == 'admin'
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
@@ -197,8 +328,12 @@ try {
apply.teardown();
else if (cmd == 'version')
out(VERSION);
else
else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
help();
else {
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
exit(2);
}
}
catch (e) {
warn(`dawnline: ${e.message}\n`);
@@ -13,7 +13,7 @@
import * as uloop from 'uloop';
import { open, readfile, writefile, stat, unlink } from 'fs';
import {
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -141,8 +141,9 @@ function check_people(m, states, events) {
let by_admin = (x) => x == 'paused' || x == 'server_off';
if (prev != null && prev != st && !by_admin(prev) && !by_admin(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)) {
// "Remove their devices" when the end date passes: irreversible, so never
// on a clock that has not been set yet (a router before NTP is in 1970).
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices) && localtime(ts).year >= 2025) {
store.transact((c, mm) => {
for (let d in mm.people[id]?.devices ?? [])
core.delete_device(c, mm, d);
@@ -154,17 +155,26 @@ function check_people(m, states, events) {
}
let last_home = 0;
// Addresses the watcher saw connect since the last tick: looked up first.
let geo_pending = {};
/** Locate new client addresses for the admin map (a couple per minute). */
/**
* Locate client addresses for the admin map: the ones that just connected
* first, then anything still shown that is missing or stale — a few per
* minute, within a time budget, so a slow service never holds the tick.
*/
function check_geo(m) {
if (!m.settings.geo_enabled)
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
let cache = geo.load();
let ips = [];
let ips = keys(geo_pending);
geo_pending = {};
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);
let changed = geo.resolve(m.settings, cache, uniq(ips), 3, 12);
if (time() - last_home > 3600) {
last_home = time();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
@@ -267,17 +277,16 @@ function watch() {
}
if (!length(keys(people)))
return;
// The status first, then what takes longer (a geo lookup may wait on the network).
save_presence(keys(people));
if (!length(events))
return;
live.collect(m, usage, d);
live.save_usage(usage, false);
if (m.settings.geo_enabled && length(ips)) {
let cache = geo.load();
if (geo.resolve(m.settings, cache, ips, length(ips)))
geo.save(cache);
}
// A location lookup waits on the network: never here, on the next tick
// (check_geo). The event carries the place when the cache already knows it.
if (m.settings.geo_enabled)
for (let ip in ips)
geo_pending[ip] = true;
for (let e in events)
if (e.type == 'connect')
e.where = place_of(e.detail);
@@ -297,6 +306,33 @@ function note(k, v) {
write_json(NOTES, notes, 0o600);
}
/*
* End dates in the activity log: a heads-up once per end date when its
* warning window opens, and "keep access" passing it (which changes no
* state, so nothing else would say it). Not on a clock that is not set.
*/
function check_expiry(m, events) {
let ts = time();
if (localtime(ts).year < 2025)
return;
for (let id, p in m.people) {
if (!p.expires)
continue;
let end = date_end(p.expires);
if (end == null)
continue;
let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
note(`warned:${id}`, p.expires);
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
}
if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
note(`kept:${id}`, p.expires);
push(events, { type: 'expired_kept', person: id, detail: p.expires });
}
}
}
/** "Jan 1 2027" from the certificate, or null. */
function cert_end(path) {
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
@@ -360,7 +396,10 @@ function nightly_backup() {
backup.backup_create('auto');
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
}
catch (e) {}
catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
slog('dawnline', 'error', `nightly backup failed: ${e.message}`, null, 'Backup');
}
}
}
@@ -391,7 +430,9 @@ function check_usage_reset(m) {
/*
* Push devices and access rules when people's states changed, the config
* file was written (by anyone: rpcd, the portal, the CLI, a restore), or
* file was written (by anyone: rpcd, the portal, the CLI, a restore), the
* access table is gone (a flushed ruleset: the firewall alone would let every
* device reach everything, so the sync unloads them until it is back), or
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
*/
function sync_runtime(t) {
@@ -400,7 +441,7 @@ function sync_runtime(t) {
let mt = st ? `${st.mtime}/${st.inode}` : null;
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
(conf_mtime != null && mt != conf_mtime);
if (changed || time() - last_sync > RESYNC_EVERY) {
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
apply.sync(t.m, usage);
last_sync = time();
}
@@ -450,6 +491,7 @@ const STEPS = [
{ who: 'People', run: (t) => {
t.states = apply.states_for(t.m, usage);
check_people(t.m, t.states, t.events);
check_expiry(t.m, t.events);
} },
{ who: 'Access rules', run: (t) => {
if (t.states)
@@ -491,8 +533,13 @@ function step(i, s, fn) {
function tick() {
ensure_dir(RUN_DIR);
writefile(watchdog.BEAT, `${time()}`);
// A restore or import drops the live counters; start over from flash.
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
// A restore or import put other counters on flash (dawnline.backup leaves
// a marker): start over from them, whatever the watcher wrote since.
if (stat(live.USAGE_RELOAD)) {
unlink(live.USAGE_RELOAD);
usage = live.load_usage(true);
}
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
let t = { m: null, pol: null, reset: false, events: [] };
for (let i, s in STEPS)
@@ -502,8 +549,10 @@ function tick() {
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
step('save', { who: 'Traffic' }, () => {
live.save_usage(usage, persist);
if (persist)
if (persist) {
last_flush = time();
geo.flush();
}
});
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
step('events', { who: 'Activity' }, () => {
@@ -518,6 +567,7 @@ function tick() {
function shutdown() {
live.save_usage(usage, true);
live.persist_events();
geo.flush();
slog_trim(true);
// A clean stop: the next start is not a crash.
unlink(watchdog.BEAT);
@@ -535,7 +585,13 @@ if (was != VERSION) {
writefile(`${DATA_DIR}/version`, VERSION);
}
slog_restore();
if (was && was != VERSION)
// postupdate put this (kept) version back because the new one did not come up.
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
unlink(`${RUN_DIR}/update-rolled-back`);
if (rolled)
slog('dawnline', 'error', `update to ${rolled} failed its check — rolled back to ${VERSION}`,
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.', 'Dawnline');
else if (was && was != VERSION)
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
else if (crashed)
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
@@ -0,0 +1,51 @@
#!/bin/sh
# Dawnline — after its own package was replaced: restart, check that the new
# version answers (the LuCI link and the agent), and put the kept previous
# version back when it does not. Started detached by the updater
# (usr/libexec/dawnline/updater) with the version being installed.
# postupdate <version>
# Plain shell on purpose: a release whose ucode does not compile cannot check
# or repair itself, and the admin cannot click Roll back in a page that this
# same backend serves.
RUN=/var/run/dawnline
KEEP=/etc/dawnline/keep/app
to="${1:-?}"
sleep 2
/etc/init.d/rpcd reload >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
up() {
ubus list luci.dawnline >/dev/null 2>&1 || return 1
ubus -t 10 call luci.dawnline rev >/dev/null 2>&1 || return 1
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' >/dev/null 2>&1
}
i=0
while [ "$i" -lt 12 ]; do
sleep 5
i=$((i + 1))
up && exit 0
done
logger -t dawnline "update to $to failed its check: luci.dawnline or the agent is not up"
set --
for f in "$KEEP"/*.ipk "$KEEP"/*.apk; do
[ -f "$f" ] && set -- "$@" "$f"
done
if [ "$#" -eq 0 ]; then
logger -t dawnline "no previous version is kept: nothing to roll back to"
exit 1
fi
if command -v apk >/dev/null 2>&1; then
apk add --allow-untrusted "$@" >/dev/null 2>&1
else
opkg install --force-reinstall --force-downgrade "$@" >/dev/null 2>&1
fi
/etc/init.d/rpcd restart >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
mkdir -p "$RUN"
# The restored agent reports it in the service log on its start.
echo "$to" > "$RUN/update-rolled-back"
logger -t dawnline "rolled back from $to to the kept version"
exit 0
@@ -72,6 +72,8 @@ const ctx = {
pol: POL,
work: `/tmp/dawnline-update.${PID}`,
log, phase, run, save,
// An automatic run (nobody is watching: the previous version is always kept).
auto: () => job.auto,
versions: (from, to) => {
job.from = from;
job.to = to;
@@ -241,16 +243,23 @@ function auto() {
install(todo);
}
/** The restarts the job asked for, in one go, after its final state is saved. */
/**
* The restarts the job asked for, in one go, after its final state is saved.
* Dawnline's own package is restarted by postupdate, a shell that also checks
* the new version and rolls back to the kept one when it does not come up.
*/
function restarts() {
if (after.app) {
let to = replace(`${job.to ?? ''}`, /[^A-Za-z0-9.-]/g, '');
system(`/usr/libexec/dawnline/postupdate '${to}' </dev/null >/dev/null 2>&1 &`);
return;
}
let cmds = [];
if (after.app)
push(cmds, '/etc/init.d/rpcd reload');
else if (after.apply)
if (after.apply)
push(cmds, '/usr/bin/dawnline apply');
if (after.uhttpd)
push(cmds, '/etc/init.d/uhttpd restart');
if (after.app || after.apply || after.uhttpd)
if (after.apply || after.uhttpd)
push(cmds, '/etc/init.d/dawnline restart');
if (length(cmds))
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
@@ -1 +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)}.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)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--line);border-radius:12px;background:var(--card);font-size:14px;line-height:20px}.alert-ic{width:30px;height:30px;border-radius:9px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:var(--warn-wash);color:var(--warn)}.alert-ic.bad{background:var(--bad-wash);color:var(--bad)}.alert-ic .ic-svg{width:15px;height:15px}.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{backgrouLine truncated
@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{--ease-out: cubic-bezier(.23, 1, .32, 1);--ease-in: cubic-bezier(.55, 0, 1, .45);--ease-drawer: cubic-bezier(.32, .72, 0, 1);--spring: linear( 0, .022, .079, .158, .249, .344, .438, .527, .61, .684, .749, .805, .852, .891, .923, .949, .969, .984, .996, 1.004, 1.009, 1.013, 1.014, 1.015, 1.015, 1.014, 1.013, 1.012, 1.01, 1.009, 1.008, 1.006, 1.005, 1.004, 1.003, 1.002, 1.002, 1.001, 1.001, 1.001, 1 );--spring-pop: linear( 0, .034, .122, .244, .383, .526, .662, .785, .889, .974, 1.038, 1.083, 1.111, 1.124, 1.126, 1.119, 1.106, 1.09, 1.072, 1.054, 1.038, 1.023, 1.01, 1, .993, .988, .985, .984, .984, .985, .987, .989, .992, .994, .996, .998, .999, 1, 1.001, 1.002, 1 );--dur-press: .12s;--dur-hover: .15s;--dur-pop: .18s;--dur-swap: .26s;--dur-enter: .44s;--dur-sheet: .44s;--dur-exit: .16s;--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}html{scrollbar-gutter:stable}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;cursor:default}input,textarea,.keybox .mono,.linkrow .mono,.conf{cursor:text}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}a.btn:hover,a.badge:hover{text-decoration:none}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)}.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)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid vaLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var it=Object.create;var He=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ct(t))!ut.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(i=ot(t,u))||i.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?it(lt(e)):{},dt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var Ye=ft((qe,Ve)=>{"use strict";var Ge=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,d=[],g={},L=function(l,f){a=c*4+17,s=(function(o){for(var h=new Array(o),p=0;p<o;p+=1){h[p]=new Array(o);for(var w=0;w<o;w+=1)h[p][w]=null}return h})(a),E(0,0),E(a-7,0),E(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=at(c,m,d)),W(y,f)},E=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?s[l+o][f+h]=!0:s[l+o][f+h]=!1)},P=function(){for(var l=0,f=0,o=0;o<8;o+=1){L(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,f=o)}return f},I=function(){for(var l=8;l<a-8;l+=1)s[l][6]==null&&(s[l][6]=l%2==0);for(var f=8;f<a-8;f+=1)s[6][f]==null&&(s[6][f]=f%2==0)},G=function(){for(var l=u.getPatternPosition(c),f=0;f<l.length;f+=1)for(var o=0;o<l.length;o+=1){var h=l[f],p=l[o];if(s[h][p]==null)for(var w=-2;w<=2;w+=1)for(var C=-2;C<=2;C+=1)w==-2||w==2||C==-2||C==2||w==0&&C==0?s[h+w][p+C]=!0:s[h+w][p+C]=!1}},z=function(l){for(var f=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[Math.floor(o/3)][o%3+a-8-3]=h}for(var o=0;o<18;o+=1){var h=!l&&(f>>o&1)==1;s[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,f){for(var o=m<<3|f,h=u.getBCHTypeInfo(o),p=0;p<15;p+=1){var w=!l&&(h>>p&1)==1;p<6?s[p][8]=w:p<8?s[p+1][8]=w:s[a-15+p][8]=w}for(var p=0;p<15;p+=1){var w=!l&&(h>>p&1)==1;p<8?s[8][a-p-1]=w:p<9?s[8][15-p-1+1]=w:s[8][15-p-1]=w}s[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,p=7,w=0,C=u.getMaskFunction(f),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(s[h][_-N]==null){var O=!1;w<l.length&&(O=(l[w]>>>p&1)==1);var T=C(h,_-N);T&&(O=!O),s[h][_-N]=O,p-=1,p==-1&&(w+=1,p=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,p=0,w=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,O=f[_].totalCount-N;h=Math.max(h,N),p=Math.max(p,O),w[_]=new Array(N);for(var T=0;T<w[_].length;T+=1)w[_][T]=255&l.getBuffer()[T+o];o+=N;var Y=u.getErrorCorrectPolynomial(O),j=k(w[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ne=T+Pe.getLength()-C[_].length;C[_][T]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,T=0;T<f.length;T+=1)Re+=f[T].totalCount;for(var be=new Array(Re),he=0,T=0;T<h;T+=1)for(var _=0;_<f.length;_+=1)T<w[_].length&&(be[he]=w[_][T],he+=1);for(var T=0;T<p;T+=1)for(var _=0;_<f.length;_+=1)T<C[_].length&&(be[he]=C[_][T],he+=1);return be},at=function(l,f,o){for(var h=B.getRSBlocks(l,f),p=D(),w=0;w<o.length;w+=1){var C=o[w];p.put(C.getMode(),4),p.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(p)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].dataCount;if(p.getLengthInBits()>_*8)throw"code length overflow. ("+p.getLengthInBits()+">"+_*8+")";for(p.getLengthInBits()+4<=_*8&&p.put(0,4);p.getLengthInBits()%8!=0;)p.putBit(!1);for(;!(p.getLengthInBits()>=_*8||(p.put(b,8),p.getLengthInBits()>=_*8));)p.put(x,8);return ae(p,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=$(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return s[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=B.getRSBlocks(l,m),o=D(),h=0;h<d.length;h++){var p=d[h];o.put(p.getMode(),4),o.put(p.getLength(),u.getLengthInBits(p.getMode(),l)),p.write(o)}for(var w=0,h=0;h<f.length;h++)w+=f[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}L(!1,P())},g.createTableTag=function(l,f){l=l||2,f=typeof f=="undefined"?l*4:f;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+f+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var p=0;p<g.getModuleCount();p+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,p)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var p={};typeof arguments[0]=="object"&&(p=arguments[0],l=p.cellSize,f=p.margin,o=p.alt,h=p.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,f){if(l=l||1,l<2)return st(f);l-=1,f=typeof f=="undefined"?l*2:f;var o=g.getModuleCount()*l+f*2,h=f,p=o-f,w,C,_,N,O=Array(l+1).join("██"),T=Array(l+1).join(" "),Y="",j="";for(w=0;w<o;w+=1){for(_=Math.floor((w-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<p&&h<=w&&w<p&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?O:T;for(_=0;_<l;_+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,f){f=f||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var p=0;p<o;p++)l.fillStyle=g.isDark(h,p)?"black":"white",l.fillRect(h*f,p*f,f,f)},g};e.stringToBytesFuncs={default:function(M){for(var A=[],b=0;b<M.length;b+=1){var x=M.charCodeAt(b);A.push(x&255)}return A}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(M,A){var b=(function(){for(var c=H(M),m=function(){var I=c.read();if(I==-1)throw"eof";return I},s=0,a={};;){var y=c.read();if(y==-1)break;var d=m(),g=m(),L=m(),E=String.fromCharCode(y<<8|d),P=g<<8|L;a[E]=P,s+=1}if(s!=A)throw s+" != "+A;return a})(),x=63;return function(c){for(var m=[],s=0;s<c.length;s+=1){var a=c.charCodeAt(s);if(a<128)m.push(a);else{var y=b[c.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(x)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,b=7973,x=21522,c={},m=function(s){for(var a=0;s!=0;)a+=1,s>>>=1;return a};return c.getBCHTypeInfo=function(s){for(var a=s<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(s<<10|a)^x},c.getBCHTypeNumber=function(s){for(var a=s<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return s<<12|a},c.getPatternPosition=function(s){return M[s-1]},c.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(a,y){return(a+y)%2==0};case i.PATTERN001:return function(a,y){return a%2==0};case i.PATTERN010:return function(a,y){return y%3==0};case i.PATTERN011:return function(a,y){return(a+y)%3==0};case i.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case i.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case i.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+s}},c.getErrorCorrectPolynomial=function(s){for(var a=k([1],0),y=0;y<s;y+=1)a=a.multiply(k([1,v.gexp(y)],0));return a},c.getLengthInBits=function(s,a){if(1<=a&&a<10)switch(s){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:"+s}else if(a<27)switch(s){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:"+s}else if(a<41)switch(s){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:"+s}else throw"type:"+a},c.getLostPoint=function(s){for(var a=s.getModuleCount(),y=0,d=0;d<a;d+=1)for(var g=0;g<a;g+=1){for(var L=0,E=s.isDark(d,g),P=-1;P<=1;P+=1)if(!(d+P<0||a<=d+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||E==s.isDark(d+P,g+I)&&(L+=1);L>5&&(y+=3+L-5)}for(var d=0;d<a-1;d+=1)for(var g=0;g<a-1;g+=1){var G=0;s.isDark(d,g)&&(G+=1),s.isDark(d+1,g)&&(G+=1),s.isDark(d,g+1)&&(G+=1),s.isDark(d+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var d=0;d<a;d+=1)for(var g=0;g<a-6;g+=1)s.isDark(d,g)&&!s.isDark(d,g+1)&&s.isDark(d,g+2)&&s.isDark(d,g+3)&&s.isDark(d,g+4)&&!s.isDark(d,g+5)&&s.isDark(d,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var d=0;d<a-6;d+=1)s.isDark(d,g)&&!s.isDark(d+1,g)&&s.isDark(d+2,g)&&s.isDark(d+3,g)&&s.isDark(d+4,g)&&!s.isDark(d+5,g)&&s.isDark(d+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var d=0;d<a;d+=1)s.isDark(d,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),v=(function(){for(var M=new Array(256),A=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)A[M[b]]=b;var x={};return x.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},x.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},x})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),s=0;s<M.length-c;s+=1)m[s]=M[s+c];return m})(),x={};return x.getAt=function(c){return b[c]},x.getLength=function(){return b.length},x.multiply=function(c){for(var m=new Array(x.getLength()+c.getLength()-1),s=0;s<x.getLength();s+=1)for(var a=0;a<c.getLength();a+=1)m[s+a]^=v.gexp(v.glog(x.getAt(s))+v.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen Line truncated
`),hostName:v,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},B={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:v};return r.dns[0]&&(B.dns1=r.dns[0]),r.dns[1]&&(B.dns2=r.dns[1]),B}function wt(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Mt(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),i=new Uint8Array(await new t.Response(r).arrayBuffer()),u=new Uint8Array(4+i.length);return new DataView(u.buffer).setUint32(0,e.length,!1),u.set(i,4),u}catch{return null}}async function Ae(e,t,r=!0){let i=new TextEncoder().encode(JSON.stringify(xt(e,t))),u=r?await Mt(i):null;return`vpn://${wt(u!=null?u:i)}`}var De=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:ve(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[v,k]of Object.entries(t))k==null||k===!1||(v.startsWith("on")&&typeof k=="function"?i.addEventListener(v.slice(2),k):v==="class"?i.className=String(k):k===!0?i.setAttribute(v,""):i.setAttribute(v,String(k)));let u=v=>{v==null||v===!1||(Array.isArray(v)?v.forEach(u):i.appendChild(typeof v=="string"?document.createTextNode(v):v))};return r.forEach(u),i}function K(e){let t=n("span",{class:"ic"});return t.innerHTML=Fe(e,"ic-svg"),t}var kt='<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>',Ee=document.getElementById("app"),We,me=(We=Ee.dataset.base)!=null?We:"",At=Ee.dataset.title||"Dawnline",Ce=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,_t=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Te=class extends Error{constructor(r,i){super(i);this.status=r}};async function ne(e,t){var u;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),i=null;try{i=await r.json()}catch{}if(!r.ok)throw new Te(r.status,(u=i==null?void 0:i.error)!=null?u:`Request failed (${r.status})`);return i}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function ce(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let i=document.execCommand("copy");if(r.remove(),!i)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function Ze(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),i=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(r),i.remove()},1e3)}var Z=null;function Xe(e,t){let r=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,v)=>n("div",{class:v?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Ct(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((i,u)=>{let v=n("i",{class:i?"":"zero"});v.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;Xe(v,()=>[k===0?"Today":k===1?"Yesterday":pe(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(v)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let i=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},K("x"))),n("div",{class:"sheet-body"},...r)),v=n("div",{class:"sheet",onclick:k=>{k.target===v&&ee()}},u);return document.body.appendChild(v),document.body.classList.add("locked"),i?v.classList.add("open"):requestAnimationFrame(()=>v.classList.add("open")),o Line truncated
`).flatMap((v,k)=>k?[`
`,Qe(v,t)]:[Qe(v,t)])),u=n("button",{class:"btn small",onclick:v=>{v.preventDefault(),t=!t,u.replaceChildren(K(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),i()}},K("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>Ze(e.filename,e.conf)},K("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},K("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:v=>{v.preventDefault(),ce(e.conf,"Configuration copied")}},K("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Se(e);if(!i)return;let u=await Ae(i,`${i.server} · ${i.name}`),v=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},K("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=ze(i.conf),n("div",{class:"pane center"},H,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},u),n("button",{class:"btn small",onclick:()=>ce(u,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Ht(i)},B=v?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},$=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),$.replaceChildren(k[H]())};for(let H of B)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},D[H]));J(t&&B.includes(t)?t:B[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${xe(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);fe(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,v?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,$,U),le=()=>{clearInterval(F),S&&de(S)}}function It(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");fe(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:i=>{i.preventDefault(),Be(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),de(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Ot(e,t){let r=t.here===e.id;fe(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:i=>Be(i.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,de(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Kt(e){fe(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Be(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,nt=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function _e(){return nt||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Ut=[[/^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"] Line truncated
"use strict";(()=>{var Dn=Object.create;var xt=Object.defineProperty;var Hn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var In=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var On=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Rn.call(e,s)&&s!==r&&xt(e,s,{get:()=>t[s],enumerable:!(a=Hn(t,s))||a.enumerable});return e};var zn=(e,t,r)=>(r=e!=null?Dn(Nn(e)):{},On(t||!e||!e.__esModule?xt(r,"default",{value:e,enumerable:!0}):r,e));var St=In((Et,$t)=>{"use strict";var Tt=(function(){var e=function(v,f){var d=236,k=17,u=v,x=r[f],l=null,o=0,L=null,m=[],C={},B=function(p,g){o=u*4+17,l=(function(c){for(var y=new Array(c),b=0;b<c;b+=1){y[b]=new Array(c);for(var E=0;E<c;E+=1)y[b][E]=null}return y})(o),N(0,0),N(o-7,0),N(0,o-7),j(),W(),ae(p,g),u>=7&&J(p),L==null&&(L=K(u,x,m)),X(L,g)},N=function(p,g){for(var c=-1;c<=7;c+=1)if(!(p+c<=-1||o<=p+c))for(var y=-1;y<=7;y+=1)g+y<=-1||o<=g+y||(0<=c&&c<=6&&(y==0||y==6)||0<=y&&y<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=y&&y<=4?l[p+c][g+y]=!0:l[p+c][g+y]=!1)},O=function(){for(var p=0,g=0,c=0;c<8;c+=1){B(!0,c);var y=s.getLostPoint(C);(c==0||p>y)&&(p=y,g=c)}return g},W=function(){for(var p=8;p<o-8;p+=1)l[p][6]==null&&(l[p][6]=p%2==0);for(var g=8;g<o-8;g+=1)l[6][g]==null&&(l[6][g]=g%2==0)},j=function(){for(var p=s.getPatternPosition(u),g=0;g<p.length;g+=1)for(var c=0;c<p.length;c+=1){var y=p[g],b=p[c];if(l[y][b]==null)for(var E=-2;E<=2;E+=1)for(var P=-2;P<=2;P+=1)E==-2||E==2||P==-2||P==2||E==0&&P==0?l[y+E][b+P]=!0:l[y+E][b+P]=!1}},J=function(p){for(var g=s.getBCHTypeNumber(u),c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[Math.floor(c/3)][c%3+o-8-3]=y}for(var c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[c%3+o-8-3][Math.floor(c/3)]=y}},ae=function(p,g){for(var c=x<<3|g,y=s.getBCHTypeInfo(c),b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<6?l[b][8]=E:b<8?l[b+1][8]=E:l[o-15+b][8]=E}for(var b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<8?l[8][o-b-1]=E:b<9?l[8][15-b-1+1]=E:l[8][15-b-1]=E}l[o-8][8]=!p},X=function(p,g){for(var c=-1,y=o-1,b=7,E=0,P=s.getMaskFunction(g),_=o-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var q=0;q<2;q+=1)if(l[y][_-q]==null){var Q=!1;E<p.length&&(Q=(p[E]>>>b&1)==1);var H=P(y,_-q);H&&(Q=!Q),l[y][_-q]=Q,b-=1,b==-1&&(E+=1,b=7)}if(y+=c,y<0||o<=y){y-=c,c=-c;break}}},$=function(p,g){for(var c=0,y=0,b=0,E=new Array(g.length),P=new Array(g.length),_=0;_<g.length;_+=1){var q=g[_].dataCount,Q=g[_].totalCount-q;y=Math.max(y,q),b=Math.max(b,Q),E[_]=new Array(q);for(var H=0;H<E[_].length;H+=1)E[_][H]=255&p.getBuffer()[H+c];c+=q;var ee=s.getErrorCorrectPolynomial(Q),te=w(E[_],ee.getLength()-1),yt=te.mod(ee);P[_]=new Array(ee.getLength()-1);for(var H=0;H<P[_].length;H+=1){var wt=H+yt.getLength()-P[_].length;P[_][H]=wt>=0?yt.getAt(wt):0}}for(var bt=0,H=0;H<g.length;H+=1)bt+=g[H].totalCount;for(var Fe=new Array(bt),Se=0,H=0;H<y;H+=1)for(var _=0;_<g.length;_+=1)H<E[_].length&&(Fe[Se]=E[_][H],Se+=1);for(var H=0;H<b;H+=1)for(var _=0;_<g.length;_+=1)H<P[_].length&&(Fe[Se]=P[_][H],Se+=1);return Fe},K=function(p,g,c){for(var y=h.getRSBlocks(p,g),b=M(),E=0;E<c.length;E+=1){var P=c[E];b.put(P.getMode(),4),b.put(P.getLength(),s.getLengthInBits(P.getMode(),p)),P.write(b)}for(var _=0,E=0;E<y.length;E+=1)_+=y[E].dataCount;if(b.getLengthInBits()>_*8)throw"code length overflow. ("+b.getLengthInBits()+">"+_*8+")";for(b.getLengthInBits()+4<=_*8&&b.put(0,4);b.getLengthInBits()%8!=0;)b.putBit(!1);for(;!(b.getLengthInBits()>=_*8||(b.put(d,8),b.getLengthInBits()>=_*8));)b.put(k,8);return $(b,y)};C.addData=function(p,g){g=g||"Byte";var c=null;switch(g){case"Numeric":c=A(p);break;case"Alphanumeric":c=D(p);break;case"Byte":c=T(p);break;case"Kanji":c=R(p);break;default:throw"mode:"+g}m.push(c),L=null},C.isDark=function(p,g){if(p<0||o<=p||g<0||o<=g)throw p+","+g;return l[p][g]},C.getModuleCount=function(){return o},C.make=function(){if(u<1){for(var p=1;p<40;p++){for(var g=h.getRSBlocks(p,x),c=M(),y=0;y<m.length;y++){var b=m[y];c.put(b.getMode(),4),c.put(b.getLength(),s.getLengthInBits(b.getMode(),p)),b.write(c)}for(var E=0,y=0;y<g.length;y++)E+=g[y].dataCount;if(c.getLengthInBits()<=E*8)break}u=p}B(!1,O())},C.createTableTag=function(p,g){p=p||2,g=typeof g=="undefined"?p*4:g;var c="";c+='<table style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: "+g+"px;",c+='">',c+="<tbody>";for(var y=0;y<C.getModuleCount();y+=1){c+="<tr>";for(var b=0;b<C.getModuleCount();b+=1)c+='<td style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: 0px;",c+=" width: "+p+"px;",c+=" height: "+p+"px;",c+=" background-color: ",c+=C.isDark(y,b)?"#000000":"#ffffff",c+=";",c+='"/>';c+="</tr>"}return c+="</tbody>",c+="</table>",c},C.createSvgTag=function(p,g,c,y){var b={};typeof arguments[0]=="object"&&(b=arguments[0],p=b.cellSize,g=b.margin,c=b.alt,y=b.title),p=p||2,g=typeof g=="undefined"?p*4:g,c=typeof c=="string"?{text:c}:c||{},c.text=c.texLine truncated
`}return c%2&&p>0?te.substring(0,te.length-c-1)+Array(c+1).join("▀"):te.substring(0,te.length-1)};return C.createASCII=function(p,g){if(p=p||1,p<2)return qe(g);p-=1,g=typeof g=="undefined"?p*2:g;var c=C.getModuleCount()*p+g*2,y=g,b=c-g,E,P,_,q,Q=Array(p+1).join("██"),H=Array(p+1).join(" "),ee="",te="";for(E=0;E<c;E+=1){for(_=Math.floor((E-y)/p),te="",P=0;P<c;P+=1)q=1,y<=P&&P<b&&y<=E&&E<b&&C.isDark(_,Math.floor((P-y)/p))&&(q=0),te+=q?Q:H;for(_=0;_<p;_+=1)ee+=te+`
`}return ee.substring(0,ee.length-1)},C.renderTo2dContext=function(p,g){g=g||2;for(var c=C.getModuleCount(),y=0;y<c;y++)for(var b=0;b<c;b++)p.fillStyle=C.isDark(y,b)?"black":"white",p.fillRect(y*g,b*g,g,g)},C};e.stringToBytesFuncs={default:function(v){for(var f=[],d=0;d<v.length;d+=1){var k=v.charCodeAt(d);f.push(k&255)}return f}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(v,f){var d=(function(){for(var u=F(v),x=function(){var W=u.read();if(W==-1)throw"eof";return W},l=0,o={};;){var L=u.read();if(L==-1)break;var m=x(),C=x(),B=x(),N=String.fromCharCode(L<<8|m),O=C<<8|B;o[N]=O,l+=1}if(l!=f)throw l+" != "+f;return o})(),k=63;return function(u){for(var x=[],l=0;l<u.length;l+=1){var o=u.charCodeAt(l);if(o<128)x.push(o);else{var L=d[u.charAt(l)];typeof L=="number"?(L&255)==L?x.push(L):(x.push(L>>>8),x.push(L&255)):x.push(k)}}return x}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var v=[[],[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]],f=1335,d=7973,k=21522,u={},x=function(l){for(var o=0;l!=0;)o+=1,l>>>=1;return o};return u.getBCHTypeInfo=function(l){for(var o=l<<10;x(o)-x(f)>=0;)o^=f<<x(o)-x(f);return(l<<10|o)^k},u.getBCHTypeNumber=function(l){for(var o=l<<12;x(o)-x(d)>=0;)o^=d<<x(o)-x(d);return l<<12|o},u.getPatternPosition=function(l){return v[l-1]},u.getMaskFunction=function(l){switch(l){case a.PATTERN000:return function(o,L){return(o+L)%2==0};case a.PATTERN001:return function(o,L){return o%2==0};case a.PATTERN010:return function(o,L){return L%3==0};case a.PATTERN011:return function(o,L){return(o+L)%3==0};case a.PATTERN100:return function(o,L){return(Math.floor(o/2)+Math.floor(L/3))%2==0};case a.PATTERN101:return function(o,L){return o*L%2+o*L%3==0};case a.PATTERN110:return function(o,L){return(o*L%2+o*L%3)%2==0};case a.PATTERN111:return function(o,L){return(o*L%3+(o+L)%2)%2==0};default:throw"bad maskPattern:"+l}},u.getErrorCorrectPolynomial=function(l){for(var o=w([1],0),L=0;L<l;L+=1)o=o.multiply(w([1,i.gexp(L)],0));return o},u.getLengthInBits=function(l,o){if(1<=o&&o<10)switch(l){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:"+l}else if(o<27)switch(l){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:"+l}else if(o<41)switch(l){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:"+l}else throw"type:"+o},u.getLostPoint=function(l){for(var o=l.getModuleCount(),L=0,m=0;m<o;m+=1)for(var C=0;C<o;C+=1){for(var B=0,N=l.isDark(m,C),O=-1;O<=1;O+=1)if(!(m+O<0||o<=m+O))for(var W=-1;W<=1;W+=1)C+W<0||o<=C+W||O==0&&W==0||N==l.isDark(m+O,C+W)&&(B+=1);B>5&&(L+=3+B-5)}for(var m=0;m<o-1;m+=1)for(var C=0;C<o-1;C+=1){var j=0;l.isDark(m,C)&&(j+=1),l.isDark(m+1,C)&&(j+=1),l.isDark(m,C+1)&&(j+=1),l.isDark(m+1,C+1)&&(j+=1),(j==0||j==4)&&(L+=3)}for(var m=0;m<o;m+=1)for(var C=0;C<o-6;C+=1)l.isDark(m,C)&&!l.isDark(m,C+1)&&l.isDark(m,C+2)&&l.isDark(m,C+3)&&l.isDark(m,C+4)&&!l.isDark(m,C+5)&&l.isDark(m,C+6)&&(L+=40);for(var C=0;C<o;C+=1)for(var m=0;m<o-6;m+=1)l.isDark(m,C)&&!l.isDark(m+1,C)&&l.isDark(m+2,C)&&l.isDark(m+3,C)&&l.isDark(m+4,C)&&!l.isDark(m+5,C)&&l.isDark(m+6,C)&&(L+=40);for(var J=0,C=0;C<o;C+=1)for(var m=0;m<o;m+=1)l.isDark(m,C)&&(J+=1);var ae=Math.abs(100*J/o/o-50)/5;return L+=ae*10,L},u})(),i=(function(){for(var v=new Array(256),f=new Array(256),d=0;d<8;d+=1)v[d]=1<<d;for(var d=8;d<256;d+=1)v[d]=v[d-4]^v[d-5]^v[d-6]^v[d-8];for(var d=0;d<255;d+=1)f[v[d]]=d;var k={};return k.glog=function(u){if(u<1)throw"glog("+u+")";return f[u]},k.gexp=function(u){for(;u<0;)u+=255;for(;u>=256;)u-=255;return v[u]},k})();function w(v,f){if(typeof v.length=="undefined")throw v.length+"/"+f;var d=(function(){for(var u=0;u<v.length&&v[u]==0;)u+=1;for(var x=new Array(v.length-u+f),l=0;l<v.length-u;l+=1)x[l]=v[l+u];return x})(),k={};return k.getAt=function(u){return d[u]},k.getLength=function(){return d.length},k.multiply=function(u){for(var x=new Array(k.getLength()+u.getLength()-1),l=0;l<k.getLength();l+=1)for(var o=0;o<u.getLength();o+=1)x[l+o]^=i.gexp(i.glog(k.getAt(l))+i.glog(u.getAt(o)));return w(x,0)},k.mod=function(u){if(k.ge Line truncated
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},h={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(w),port:String(r.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return r.dns[0]&&(h.dns1=r.dns[0]),r.dns[1]&&(h.dns2=r.dns[1]),h}function Yn(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Qn(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(r).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,e.length,!1),s.set(a,4),s}catch{return null}}async function Be(e,t,r=!0){let a=new TextEncoder().encode(JSON.stringify(Vn(e,t))),s=r?await Qn(a):null;return`vpn://${Yn(s!=null?s:a)}`}function n(e,t={},...r){let a=document.createElement(e);for(let[i,w]of Object.entries(t))w==null||w===!1||(i.startsWith("on")&&typeof w=="function"?a.addEventListener(i.slice(2),w):i==="class"?a.className=String(w):w===!0?a.setAttribute(i,""):a.setAttribute(i,String(w)));let s=i=>{i==null||i===!1||(Array.isArray(i)?i.forEach(s):a.appendChild(typeof i=="string"?document.createTextNode(i):i))};return r.forEach(s),a}function I(e){let t=n("span",{class:"ic"});return t.innerHTML=He(e,"ic-svg"),t}var ie=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,oe={out:"cubic-bezier(0.23, 1, 0.32, 1)",in:"cubic-bezier(0.55, 0, 1, 0.45)",drawer:"cubic-bezier(0.32, 0.72, 0, 1)"};function Ht(e){var r;let t=e.closest(".sheet-panel");return t?(t.dataset.hold=String(+((r=t.dataset.hold)!=null?r:0)+1),()=>{var s;let a=+((s=t.dataset.hold)!=null?s:1)-1;a>0?t.dataset.hold=String(a):delete t.dataset.hold}):()=>{}}function jn(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Jn(e,t,r){return e<=0||t<-.1?!1:t>.4||e>r/3}var Bt=e=>Math.round(Math.min(380,Math.max(220,200+e*.35)));function ne(e,t){e.classList.remove(t),e.offsetWidth,e.classList.add(t)}function Nt(e,t){let r=0,a=0,s=!1,i=null,w=new ResizeObserver(()=>{if(e.dataset.hold){i==null||i.cancel(),e.classList.remove("morphing","morphing-w"),r=e.offsetHeight,a=e.offsetWidth;return}let h=getComputedStyle(e),M=i?parseFloat(h.height):r,A=i?parseFloat(h.width):a;i==null||i.cancel(),e.classList.remove("morphing","morphing-w");let D=e.offsetHeight,T=e.offsetWidth,R=e.dataset.morph==="width"||s;delete e.dataset.morph;let z=a!==0&&T!==a;if(r=D,a=T,!M||ie()||z&&!R)return;let U=Math.abs(D-M),F=R?Math.abs(T-A):0;if(U<2&&F<2)return;s=F>=2,e.classList.add("morphing"),e.classList.toggle("morphing-w",s);let V=e.animate(s?[{height:`${M}px`,width:`${A}px`},{height:`${D}px`,width:`${T}px`}]:[{height:`${M}px`},{height:`${D}px`}],{duration:Bt(Math.max(U,F)),easing:oe.out});i=V;let G=()=>{i===V&&(i=null,s=!1,e.classList.remove("morphing","morphing-w"))};V.onfinish=G,V.oncancel=G});return w.observe(t),()=>w.disconnect()}function et(e,t,r=0){let a=[...e.childNodes];if(!a.length||!e.isConnected){e.replaceChildren(...t);return}let s=getComputedStyle(e),i=document.createElement("div");i.className="ghost",i.setAttribute("aria-hidden","true"),i.inert=!0,Object.assign(i.style,{display:s.display==="flex"?"flex":"block",flexDirection:s.flexDirection,alignItems:s.alignItems,gap:s.gap,top:s.paddingTop,left:s.paddingLeft,right:s.paddingRight}),i.append(...a),e.replaceChildren(i,...t);let w=ie(),h=i.animate([{opacity:1,transform:"none"},{opacity:0,transform:w?"none":`translateX(${-r*8}px)`}],{duration:120,easing:oe.out,fill:"forwards"}),M=()=>i.remove();h.onfinish=M,h.oncancel=M;for(let A of t)A instanceof HTMLElement&&A.animate(w?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translate(${r*12}px, ${r?0:6}px)`,filter:"blur(4px)"},{opacity:1,transform:"none",filter:"blur(0)"}],{duration:w?160:280,delay:50,easing:oe.out,fill:"backwards"})}function Rt(e){return!e||!e.isConnected?Promise.resolve():e.animate(ie()?[{opacity:1},{opacity:0}]:[{opacity:1,transform:"none",filter:"blur(0)"},{opacity:0,transform:"scale(0.96)",filter:"blur(4px)"}],{duration:200,easing:oe.in,fill:"forwards"}).finished.then(()=>{},()=>{})}var It=e=>new Promise(t=>setTimeout(t,ie()?0:e)),Ce={ms:520,contentMs:300,blur:4,drift:6,scale:.98};async function Ot(e){if(!e.isConnected)return;let t=Ht(e),r=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden",e.style.transformOrigin="50% 0",e.inert=!0;let s=()=>{};ie()?await e.animate([{opacity:1},{opacity:0}],{duration:160,easing:oe.out,fill:"forwards"}).finished.then(s,s):(e.animate([{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:`blur(${Ce.blur}px)`,transform:`translateY(${-Ce.drift}px) scale(${Ce. Line truncated
`).flatMap((w,h)=>h?[`
`,ln(w,t)]:[ln(w,t)])),i&&r.querySelectorAll(".conf-v, .conf-mask").forEach(w=>w.classList.add("unmask"))},s=n("button",{class:"btn small",onclick:i=>{i.preventDefault(),t=!t,s.replaceChildren(I(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),ne(s,"swap"),a(!0)}},I("key"),n("span",{},"Show key"));return a(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},Te()?"For computers and routers: import it in any WireGuard app":"For computers and routers: import it in AmneziaWG or AmneziaVPN")),ut(e)?n("button",{class:"btn primary",onclick:()=>ut(e)()},I("open"),n("span",{},"Share file")):n("button",{class:"btn primary",onclick:()=>ze(e.filename,e.conf)},I("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},I("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),s,n("button",{class:"btn small",onclick:i=>{i.preventDefault(),ue(e.conf,"Configuration copied",i.currentTarget)}},I("copy"),n("span",{},"Copy"))),r))}async function pt(e,t,r){let a=r!=null?r:await Ge(e);if(!a)return;let s=await Be(a,`${a.server} · ${a.name}`),i=fn(),w=e.kind==="phone"||e.kind==="tablet",h={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:s},I("amnezia"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:on().href,target:"_blank",rel:"noopener noreferrer"},on().label),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let G=n("div",{class:"qr"}),v=n("p",{class:"muted s"}),f=n("div",{class:"seg"}),d=Te()?"conf":"vpn",k=()=>{},u=(x=!1)=>{let l=d==="vpn"?s:a.conf;vt(G,l),v.textContent=d==="vpn"?"Scan with the phone’s camera or inside AmneziaVPN.":Te()?"Scan inside the AmneziaWG, WireGuard or AmneziaVPN app.":"Scan inside the AmneziaWG app (or AmneziaVPN).",f.querySelectorAll(":scope > button").forEach(o=>o.classList.toggle("on",o.dataset.m===d)),k(),x&&(ne(G,"swap"),ne(v,"swap"))};for(let[x,l]of[["vpn","AmneziaVPN"],["conf",Te()?"WireGuard app":"AmneziaWG app"]])f.appendChild(n("button",{type:"button","data-m":x,onclick:()=>{d!==x&&(d=x,u(!0))}},l));return u(),k=tt(f),n("div",{class:"pane center"},f,G,v,dt())},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},s),n("button",{class:"btn small",onclick:G=>ue(s,"Key copied",G.currentTarget)},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>An(a)},M=i&&w?["app","qr","key","file"]:w?["qr","key","file"]:["file","key","qr"],A={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=n("div",{class:"tab-body"}),T=n("div",{class:"tabs",role:"tablist"}),R=-1,z=()=>{},U=G=>{let v=M.indexOf(G);T.querySelectorAll(":scope > button").forEach(f=>{f.classList.toggle("on",f.dataset.id===G),f.setAttribute("aria-selected",String(f.dataset.id===G))}),z(),R<0?D.replaceChildren(h[G]()):v!==R&&et(D,[h[G]()],Math.sign(v-R)),R=v};for(let G of M)T.appendChild(n("button",{role:"tab","data-id":G,onclick:()=>U(G)},A[G]));U(t&&M.includes(t)?t:M[0]),z=tt(T);let F=e.handshake||e.disabled?null:rt(e.kind),V=F?$n(e,()=>void Tn(F,[T,D]),F.gaveUp):()=>{};$e(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,i&&w?"Add it to AmneziaVPN on this phone":w?"Scan with the phone’s camera or AmneziaVPN":"Import the file in AmneziaWG or AmneziaVPN",F==null?void 0:F.el,T,D,e.handshake?mr(e):null),ce=()=>{V(),S&&ye(S)}}function mr(e){return n("div",{class:"waiting"},e.online?n("span",{class:"ok"},"Connected"):n("span",{class:"muted"},`Last connected ${Ue(e.handshake,mt())}`))}async function Tn(e,t){var r;e.connected(),(r=e.el.closest(".sheet-panel"))==null||r.scrollTo({top:0,behavior:ie()?"auto":"smooth"}),await It(400),await Promise.all(t.map(a=>Ot(a))),await new Promise(a=>setTimeout(a,2e3)),re!=null&&re.contains(e.el)&&!e.el.closest(".ghost")&&de()}function En(e,t=4){window.setTimeout(async()=>{var r;try{let a=await he("state");S=a,!re&&!ve&&ye(a),!((r=a.person.devices.find(s=>s.id===e))!=null&&r.online)&&t>1&&En(e,t-1)}catch{}},1500)}function $n(e,t,r){let a=mt(),s=0,i=0,w=!1,h=Date.now(),M=async()=>{if(s=0,!w){if(Date.now()-h>6e5){w=!0,r();return}if(document.hidden){A();return}try{let T=await he("state");S=T;let R=T.person.devices.find(z=>z.id===e.id);if(R&&R.handshake>a){w=!0,t(),R.online||En(e.id);return}}catch(T){if(T.status===404||T.status===401){w=!0;return}}i++,A()}},A=()=>{!w&&!s&&(s=window.setTimeout(M,i<6?5e3:i<12?15e3:3e4))},D=()=>{!document.hidden&&!w&&!s&&M()};return document.addEventListener("visibilitychange",D),A(),()=>{w=!0,s&&clearTimeout(s),document.removeEventListener("visibilitychange",D)}}var Sn=e=>`dl.app.${e.id}`;function gr(e){try{let t=loc Line truncated
@@ -0,0 +1,22 @@
#!/usr/bin/ucode
// Dawnline personal portal as a CGI script: the request handling itself is
// dawnline.portal. www/cgi-bin/portal (a shell) runs it for requests shaped
// like a personal link and answers the rest itself.
'use strict';
import { stdin } from 'fs';
import { serve } from 'dawnline.portal';
let env = {};
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
serve({
env,
headers: {},
read: (n) => stdin.read(n),
write: (s) => print(s),
});
@@ -1,21 +1,51 @@
#!/usr/bin/ucode
// Dawnline personal portal as a CGI script: the request handling itself is
// dawnline.portal.
'use strict';
#!/bin/sh
# Dawnline personal portal, the door: uhttpd runs this for every request.
# Anything that is not shaped like a personal link (/<word-code>[/…]) gets
# the portal's bare answer from here, in a shell that costs nothing, so a
# scanner or a flood on the root never starts ucode (compiling the portal's
# module graph is ~140 ms of CPU). Links go on to the portal itself
# (/usr/share/dawnline/portal/cgi.uc), which judges the code.
#
# The answer here is byte for byte the portal's own not_found(): keep both
# in step (dawnline.portal headers(), SECURITY_HEADERS, not_found()).
import { stdin } from 'fs';
import { serve } from 'dawnline.portal';
path="${REQUEST_URI%%\?*}"
w='[a-z][a-z][a-z][a-z][a-z][a-z]'
# The expansion is meant as a pattern (a word of six letters), not literally.
# shellcheck disable=SC2254
case "$path" in
/$w-$w-$w|/$w-$w-$w/*) exec /usr/bin/ucode /usr/share/dawnline/portal/cgi.uc ;;
esac
let env = {};
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
# HSTS pins the whole name: only when the visitor is on the standard port.
hsts=
if [ "$HTTPS" = on ]; then
port="${HTTP_HOST##*:}"
case "$HTTP_HOST" in *:*) ;; *) port=443 ;; esac
case "$HTTP_HOST" in *\]) port=443 ;; esac
[ "$port" = 443 ] && hsts=1
fi
serve({
env,
headers: {},
read: (n) => stdin.read(n),
write: (s) => print(s),
});
# Files always get the 404: a missing asset must not turn into someone's website.
file=
case "$path" in
/luci-static|/luci-static/*|/cgi-bin|/cgi-bin/*|/ubus|/ubus/*) file=1 ;;
*) case "${path##*/}" in *.*) file=1 ;; esac ;;
esac
redirect=
[ -n "$file" ] || redirect="$(uci -q get dawnline.settings.portal_redirect)"
if [ -n "$redirect" ]; then
printf 'Status: 302 Found\r\n'
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
printf 'Location: %s\r\nContent-Type: text/plain\r\n' "$redirect"
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
printf '\r\nMoved\n'
else
printf 'Status: 404 Not Found\r\n'
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
printf 'Content-Type: text/plain\r\n'
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
printf '\r\nNot found\n'
fi
exit 0
@@ -18,6 +18,8 @@
"settings_get",
"portal_info",
"interfaces",
"server_ports",
"endpoint_probe",
"events"
]
}
@@ -154,12 +154,20 @@ function from_device(m, d, t, states, dmp, snap) {
// The router itself.
if (index(router_addrs(snap), t.ip) >= 0) {
if (home_access(p))
push(steps, step(true, `${t.ip} is this router`, 'Home access includes the router.'));
else if (t.port == 53)
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
if (t.port == 53)
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
else
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS on the router.`));
else if (portal)
push(steps, step(true, `${t.ip} is this router: the personal portal is open to everyone`, ''));
else if (!home_access(p))
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS and the portal on the router.`));
else {
// Like any home address: only on the networks the person reaches.
let h = core.person_home(srv, p, snap);
if (!h.all && !in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is this router on a network ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is this router`, h.all ? 'Home access includes the router.' : `On one of the networks ${p.name} reaches.`));
}
push(steps, via(t.ip));
return steps;
}
@@ -35,19 +35,17 @@ function log(who, msg, level, detail) {
/* ---------- 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 && ip2int(d.address) != null)
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
for (let pid, p in m.people) {
// One label per device, unique within the person (the UI shows the same).
let labels = core.device_labels(m, p);
for (let id in p.devices) {
let d = m.devices[id];
if (ip2int(d.address) != null)
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
}
}
let ls = loop.status();
if (ls.active)
@@ -82,37 +80,44 @@ export function access_sets(m, usage, states) {
return nft.access_sets(m, usage, states);
};
/** Log an access-table failure once per distinct error; true when the table is in place. */
function nft_result(err) {
/**
* Log an access-table failure once per distinct error (with what it means
* for the devices: none loaded while the table is missing, the previous rules
* kept when an older one survived the failed rebuild); the error, or null.
*/
function nft_result(err, present) {
let was = readfile(NFT_ERR);
if (err == null) {
if (was != null)
unlink(NFT_ERR);
return true;
return null;
}
if (was != err) {
log('Access rules', "couldn't load — devices aren't loaded into the tunnels until they do", 'error', err);
log('Access rules', present
? "couldn't be updated — the previous rules stay, and changes to access wait until they load"
: "couldn't load — no device is loaded into the tunnels until they do", 'error', err);
ensure_dir(RUN_DIR);
writefile(NFT_ERR, err);
}
return false;
return err;
}
/**
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
* when that fails (no table yet at boot, or an older shape) — an error only
* when the rebuild fails too.
* when that fails (no table yet at boot, or an older shape). Null, or the
* error when the rebuild fails too.
*/
function load_table(m, sets, full) {
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
if (err != null && !full)
err = nft.rebuild(m, sets);
return nft_result(err);
return nft_result(err, err != null && nft.present());
}
/** Full table rebuild (structure changes: servers, LAN subnets). */
/** Full table rebuild (structure changes: servers, LAN subnets); true when it loaded. */
export function rebuild_nft(m, sets) {
return nft_result(nft.rebuild(m, sets));
let err = nft.rebuild(m, sets);
return nft_result(err, err != null && nft.present()) == null;
};
/** Atomically replace set contents only. */
@@ -131,32 +136,57 @@ export function firewall_drift(m) {
/* ---------- runtime sync ---------- */
/**
* What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices. Null when all went in.
*/
function sync_warning(m, table, peers) {
let out = [];
if (table != null)
push(out, nft.present()
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.`
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`);
for (let id, r in peers)
if (r != 'ok' && r != 'down')
push(out, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`);
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null;
}
/*
* With the lock held: access sets first, and devices into the tunnels only
* once the table that limits them is in place.
* With the lock held: access sets first, then devices into the tunnels.
* Fail closed: without the table the firewall would let every loaded device
* reach everything, so while it is missing no device is loaded at all. An
* older table that survived a failed rebuild keeps limiting them with the
* sets it has, and the devices still follow people's states (a revoked one
* leaves).
*/
function locked_sync(m, usage, full) {
let states = states_for(m, usage);
let sets = nft.access_sets(m, usage, states);
let peers = {};
if (load_table(m, sets, full))
peers = awg.sync_peers(m, states);
let table = load_table(m, sets, full);
let peers = awg.sync_peers(m, table == null || nft.present() ? states : {});
sync_hosts(m);
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/states.json`, states, 0o644);
return { peers, states };
return { peers, states, table, warning: sync_warning(m, table, peers) };
}
/**
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
* hostnames. Cheap; safe to call often. The model is always read again under
* the lock (`m` is accepted for older callers and not used); `usage` is the
* caller's (the agent holds the live counters).
* caller's (the agent holds the live counters). The result carries `warning`
* (a sentence for the admin) when the sync did not fully take.
*/
export function sync(m, usage) {
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
};
/** Is the access table loaded (the agent's tick re-syncs when it is not). */
export function table_present() {
return nft.present();
};
/**
* 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
@@ -209,10 +239,10 @@ export function apply(opts) {
let s = locked_sync(m, usage, true);
ensure_dir(RUN_DIR);
write_file(NET_SIG, net_signature(m), 0o644);
return { network, firewall, lp, peers: s.peers };
return { network, firewall, lp, peers: s.peers, warning: s.warning };
});
loop.remember(r.lp);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers };
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning };
};
/** Remove everything Dawnline created (used by the uninstaller). */
@@ -6,11 +6,13 @@
import { readfile, stat, unlink } from 'fs';
import {
q, sh, sh_out, rand_int, rand_bytes, valid_key, ensure_dir, write_file, read_json, write_json, lock, unlock,
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, translit, ensure_dir, write_file, read_json, write_json, lock, unlock,
slog, iface_status, DATA_DIR, RUN_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
@@ -118,7 +120,9 @@ export function server_keys() {
/* ---------- 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 ] };
// Junk packets may be tiny (the 3.1 preset sends 10-50 bytes, as AmneziaVPN
// does); the ceiling keeps them under the path MTU.
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 0, 1024 ], jmax: [ 0, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
function rand_h(used) {
for (let i = 0; i < 50; i++) {
@@ -130,31 +134,106 @@ function rand_h(used) {
}
}
// caps() answers from here while the tool, the protocol script and the module file are the same.
const CAPS = `${RUN_DIR}/awg-caps.json`;
/**
* What the installed AmneziaWG can do, from the netifd protocol script (the
* options it passes on) and the `awg` tool (the keys it accepts):
* What the installed AmneziaWG can do: the netifd protocol script (the
* options it passes on) and the `awg` tool (the keys it accepts) say what the
* tools know, the kernel module's package version what the kernel runs, and
* a feature counts only when both have it (tools 3.1 over a 2.0 module would
* configure header protection that the kernel silently lacks):
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
* mismatch — the two differ
*/
export function caps() {
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? '';
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`;
let cached = read_json(CAPS, null);
if (cached?.key == key && cached.caps)
return cached.caps;
let script = readfile(PROTO) ?? '';
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 };
let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
// A module installed by hand has no package: then the tools are believed.
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
let out = {
v2: t2 && (kmod == null || kmod != '1.0'),
v3: t3 && (kmod == null || kmod == '3.1'),
tools, kmod, mismatch: tools != null && kmod != null && tools != kmod,
};
ensure_dir(RUN_DIR);
write_json(CAPS, { key, caps: out }, 0o644);
return out;
};
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
/**
* Why this AmneziaWG cannot run a server's disguise values, or null: a 3.1
* preset after a rollback to a 2.0 build would come up without the header
* protection every device expects, so such a server is kept down instead
* (dawnline.netifd).
*/
export function obf_unsupported(o) {
let c = caps();
let has = (keys) => length(filter(keys, (k) => o?.[k] != null && o[k] != '')) > 0;
let v3 = [ 'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ];
let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0;
if (has(v3) && !c.v3)
return `its disguise needs AmneziaWG 3.1 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
if ((has(v2) || ranged) && !c.v2)
return `its disguise needs AmneziaWG 2.0 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
return null;
};
/**
* Signature packets shaped like DNS, made fresh for each server: the same
* fixed bytes on every router (AmneziaVPN's own 3.1 default is one constant
* answer about icloud.com) would be one rule for a DPI to match. A query and
* an answer about a name of this server's own, with its own TTL and address.
* <r N> random bytes, <rc N> random letters, <b 0x..> fixed bytes
*/
function dns_name_hex() {
let hex = (s) => {
let out = '';
for (let i = 0; i < length(s); i++)
out += sprintf('%02x', ord(s, i));
return out;
};
let tld = [ 'com', 'net', 'org', 'io' ][rand_int(0, 3)];
let n = rand_int(5, 9);
return { labels: `<b 0x${sprintf('%02x', n)}><rc ${n}><b 0x${sprintf('%02x', length(tld))}${hex(tld)}00>`, len: n + length(tld) + 2 };
}
function dns_query() {
let name = dns_name_hex();
// id, flags (standard query, recursion desired), 1 question, name, type A, class IN
return `<r 2><b 0x01000001000000000000>${name.labels}<b 0x00010001>`;
}
function dns_answer() {
let name = dns_name_hex();
let ttl = sprintf('%08x', rand_int(300, 86400));
// id, flags (answer, authoritative, recursion), 1 question, 1 answer, name, A IN, pointer, A IN, ttl, 4 bytes
return `<r 2><b 0x85800001000100000000>${name.labels}<b 0x00010001c00c00010001${ttl}0004><r 4>`;
}
/**
* 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)
* balanced AmneziaWG 2.0: junk packets, random headers, padded cookie and
* data packets, DNS-shaped signature packets
* 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
* Servers made before 0.8 may still carry the old "standard" or "strong"
* values (1.0-style junk only): they keep running as they are, the picker
* offers Balanced or Maximum instead.
*/
export function obf_preset(name) {
if (name == 'max')
@@ -162,7 +241,7 @@ export function obf_preset(name) {
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,
i1: dns_query(), i2: dns_answer(),
header_protection_key: sh_out('awg genkey'),
content_padding_addition: '10-100',
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
@@ -171,12 +250,11 @@ export function obf_preset(name) {
};
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.jc = `${rand_int(4, 8)}`;
let jmin = rand_int(64, 128);
o.jmin = `${jmin}`;
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
o.jmax = `${jmin + rand_int(150, 400)}`;
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
while (s1 + 56 == s2)
s2 = rand_int(15, 64);
@@ -185,20 +263,26 @@ export function obf_preset(name) {
let used = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
o[k] = rand_h(used);
// AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept
// small: core.tunnel_mtu) and DNS-shaped signature packets before each
// handshake — what 1.0 traffic lacks and gets recognised by.
o.s3 = `${rand_int(8, 48)}`;
o.s4 = `${rand_int(4, 16)}`;
o.i1 = dns_query();
o.i2 = dns_answer();
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')))
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1])
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)
@@ -252,6 +336,56 @@ export function obf_neutral(o) {
return true;
};
/*
* The .conf file name doubles as the tunnel name in WireGuard apps (15
* characters at most): the device first, so a person's devices stay apart,
* and a number when the cut would still make two of them alike.
*/
function conf_filename(m, p, dev) {
let label = (d) => trim(substr(trim(replace(lc(translit(d.name + '-' + p.id)), /[^a-z0-9]+/g, '-'), '-'), 0, 15), '-');
let order = sort(map(p.devices, (id) => m.devices[id]),
(a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
let seen = {};
for (let d in order) {
let l = label(d);
let n = seen[l] = (seen[l] ?? 0) + 1;
if (d.id == dev.id)
return (n > 1 ? trim(substr(l, 0, 15 - length(`-${n}`)), '-') + `-${n}` : l) + '.conf';
}
return label(dev) + '.conf';
}
/**
* The junk a device sends is its own: within the preset's own ranges, the
* count and sizes are shifted a little by the device (deterministic, so the
* configuration keeps its fingerprint), so two phones of one family do not
* share one profile. Server-side values (headers, padding sizes, the header
* protection key) stay the server's.
*/
function client_obf(srv, dev) {
let o = { ...srv.obf };
if (obf_neutral(o) || !(+o.jc > 0))
return o;
let key = `${srv.id}/${dev.id}/${srv.obf.h1 ?? ''}`;
let seed = 2166136261;
for (let i = 0; i < length(key); i++)
seed = ((seed ^ ord(key, i)) * 16777619) & 0x7fffffff;
let pick = (n) => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed % n;
};
let jc = +o.jc, jmin = +o.jmin, jmax = +o.jmax;
o.jc = `${max(1, min(10, jc + pick(3) - 1))}`;
if (jmax > jmin + 32) {
let d = pick(17);
o.jmin = `${jmin + d}`;
o.jmax = `${jmax - pick(17)}`;
if (+o.jmax <= +o.jmin)
o.jmax = `${+o.jmin + 32}`;
}
return o;
}
export function client_config(m, dev) {
let p = m.people[dev.person];
let srv = p ? m.servers[p.server] : null;
@@ -270,23 +404,26 @@ export function client_config(m, dev) {
push(lines, `MTU = ${mtu}`);
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
// out, so any WireGuard app accepts the file.
if (!obf_neutral(srv.obf))
let obf = client_obf(srv, dev);
if (!obf_neutral(obf))
for (let k in core.OBF_KEYS)
if (srv.obf[k] != null && srv.obf[k] != '')
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
if (obf[k] != null && obf[k] != '')
push(lines, `${OBF_CONF[k]} = ${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}`);
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
// other timers; a fixed beat would be the one regular thing left.
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : 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`,
filename: conf_filename(m, p, dev),
conf: join('\n', lines) + '\n',
has_private_key: dev.private_key != '',
amnezia: {
@@ -301,7 +438,7 @@ export function client_config(m, dev) {
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
obfuscation: srv.obf,
obfuscation: obf,
},
};
};
@@ -327,6 +464,9 @@ export function netifd_options(srv) {
return o;
};
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
@@ -342,7 +482,12 @@ export function sync_peers(m, states) {
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)
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it). Over the data limit or
// outside the allowed hours the tunnel stays: the access table blocks
// everything but the portal, which says why (a silent handshake failure
// would look like a broken VPN).
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
continue;
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
@@ -362,17 +507,24 @@ export function sync_peers(m, states) {
/**
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
* lines always have 9. The tool fails when any one interface can't be read,
* but still prints the others: those are kept and `ok` is false, so only the
* interfaces listed in `ifaces` are known.
* Lines are told apart by their shape, not their length (each AmneziaWG
* generation adds fields to the interface line): an interface line carries
* its private and public key and a port, a peer line the peer's key, a
* preshared key or "(none)" and an endpoint. The tool fails when any one
* interface can't be read, but still prints the others: with `wanted` (the
* ifnames that matter) `ok` means those were all read, so another tunnel's
* trouble is not ours.
*/
export function dump() {
export function dump(wanted) {
let r = sh('awg show all dump');
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) == 9) {
if (length(f) < 5 || !valid_key(f[1]))
continue;
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
@@ -382,10 +534,9 @@ export function dump() {
tx: +f[7],
};
}
else if (length(f) >= 5) {
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
}
}
if (!out.ok && type(wanted) == 'array')
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
return out;
};
@@ -475,10 +626,15 @@ function fnv32(str) {
return sprintf('%08x', h);
}
/** What a device holds, minus its private key: changes when it must import again. */
/**
* What a device holds, minus its private key: changes when it must import
* again. The junk count and sizes (Jc, Jmin, Jmax) are the device's own and
* never have to match the server, so they are left out: a change there is
* no reason to 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;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
@@ -4,6 +4,7 @@
import { readfile } from 'fs';
import { connect } from 'ubus';
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
import * as pkg from 'dawnline.pkg';
export const SOURCES = {
@@ -28,7 +29,36 @@ export function firmware() {
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
if (!rel.version || length(target) != 2 || !arch)
return null;
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext() };
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext(),
snapshot: match(rel.version, /SNAPSHOT/) != null };
};
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
export const RECORD = `${DATA_DIR}/awg.json`;
/**
* Remember which build was installed on which kernel. After a firmware
* upgrade the module is gone (it was built for that kernel): Health can then
* say so and offer the build for the new one (dawnline.health).
*/
export function record(source, tag, packages) {
ensure_dir(DATA_DIR, 0o700);
write_json(RECORD, {
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
source, tag, packages, installed: time(),
}, 0o600);
};
/**
* The firmware the recorded AmneziaWG build was for, when it is not this one
* (and the module is gone): { was, now, tag, source }, else null.
*/
export function kernel_changed() {
let r = read_json(RECORD, null);
let now = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
if (!r?.osrelease || r.osrelease == now)
return null;
return { was: r.osrelease, now, tag: r.tag, source: r.source };
};
/** The file name of a package in a build. */
@@ -41,9 +71,21 @@ export function for_tag(fw, tag) {
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
};
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
/**
* AmneziaWG generation of a package version: 3.x packages carry 3.1; 1.0.x
* ones are 2.0 (S3/S4, I1-I5, header ranges) from July 2025 on, and the
* first generation before that. A kernel module's version carries the kernel
* release in front (6.12.94.3.1.20260906): the AmneziaWG part is at the end.
*/
export function gen(version) {
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
if (version == null)
return null;
let v = match(`${version}`, /([0-9]+\.[0-9]+\.[0-9]{8})(-r?[0-9]+)?$/)?.[1] ?? `${version}`;
if (match(v, /^3\./))
return '3.1';
if (match(v, /^1\.0\.2024/) || match(v, /^1\.0\.20250[1-6]/))
return '1.0';
return '2.0';
};
/** The installed AmneziaWG packages: { name: version | null }. */
@@ -3,7 +3,7 @@
// only Dawnline's own regular files, and servers that cannot take over one of
// the router's own interfaces or networks.
import { readfile, stat, unlink, lsdir } from 'fs';
import { readfile, stat, unlink, lsdir, rename } from 'fs';
import { cursor } from 'uci';
import {
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
@@ -15,24 +15,36 @@ import * as net from 'dawnline.net';
import * as health from 'dawnline.health';
const BACKUP_DIR = `${DATA_DIR}/backups`;
const KEEP_BACKUPS = 10;
/**
* How many backups of each kind stay (the newest): the nightly ones must not
* push out what the admin made by hand or what a removal left behind.
*/
const KEEP = { manual: 10, auto: 7, 'pre-delete': 5, 'pre-remove': 3, 'pre-update': 3, 'pre-restore': 3, 'pre-import': 3 };
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
/** What a backup holds (paths inside the archive, relative to /). */
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
/**
* Kinds that hold the config alone (about 20 KB): the history can be a
* megabyte or more, and these are made often and never to bring history
* back. Manual, pre-restore and pre-import backups protect the data that is
* about to be replaced, so they take everything.
*/
const CONFIG_ONLY = [ 'auto', 'pre-delete', 'pre-remove', 'pre-update' ];
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
const MAX_UNPACKED = 16 * 1024 * 1024;
/* ---------- checking a configuration before it is used ---------- */
/**
* What is wrong with the servers of a configuration about to replace the
* current one (cursor `c` holds it): each must have a valid, unique interface
* What is wrong with a configuration about to replace the current one
* (cursor `c` holds it): each server must have a valid, unique interface
* name that is not one of the router's own interfaces, a free subnet and a
* unique port. [] when it can be used.
* unique port, and the people and devices must be consistent
* (core.model_errors). [] when it can be used.
*/
export function config_errors(c) {
let m = core.load(c);
let errs = [];
let errs = core.model_errors(m);
let nc = cursor();
nc.load('network');
let foreign = health.foreign_subnets();
@@ -92,30 +104,41 @@ export function backup_list() {
};
/**
* Make a backup now; returns its name. The oldest beyond KEEP_BACKUPS are
* removed, except `keep` (the backup being restored, which must survive the
* backup made just before restoring it).
* Make a backup now; returns its name. Written whole or not at all (a half
* archive from a full flash never shows up as a backup). Of each kind the
* oldest beyond KEEP are removed, except `keep` (the backup being restored,
* which must survive the backup made just before restoring it).
*/
export function backup_create(reason, keep) {
let kind = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? reason : 'manual';
let config_only = index(CONFIG_ONLY, kind) >= 0;
// Flush live counters first so the backup has current usage.
if (!config_only) {
let u = read_json(`${RUN_DIR}/usage.json`, null);
if (u)
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
live.persist_events();
}
ensure_dir(BACKUP_DIR, 0o700);
let t = localtime();
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
let files = join(' ', map(filter(FILES, (f) => file_exists(`/${f}`)), q));
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
if (r.code != 0)
die(`Backup failed: ${trim(r.out)}`);
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, kind == 'manual' ? '' : `-${kind}`);
let want = config_only ? [ FILES[0] ] : FILES;
let files = join(' ', map(filter(want, (f) => file_exists(`/${f}`)), q));
// Not a NAME until it is complete.
let tmp = `${BACKUP_DIR}/.${name}.tmp`;
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
unlink(tmp);
die(`Backup failed: ${trim(r.out) || 'the archive could not be written (is the flash full?)'}`);
}
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let all = backup_list();
let old = filter(all, (b) => b.name != keep && b.name != name);
let room = KEEP_BACKUPS - 1 - (length(old) < length(all) - 1 ? 1 : 0);
for (let i = room; i < length(old); i++)
unlink(`${BACKUP_DIR}/${old[i].name}`);
let by_kind = {};
for (let b in backup_list())
if (b.name != keep && b.name != name)
push(by_kind[b.reason] ??= [], b);
for (let k, list in by_kind)
for (let i = KEEP[k] ?? 3; i < length(list); i++)
unlink(`${BACKUP_DIR}/${list[i].name}`);
return name;
};
@@ -155,14 +178,24 @@ function check_archive(path) {
die('Backup is too large.');
}
/** Put the files unpacked in `dir` in place, under the config lock. */
/**
* Put the files unpacked in `dir` in place, under the config lock. The
* config goes first: when it cannot be written nothing else is touched, and
* a data file that fails afterwards is reported, not ignored.
*/
function install_files(dir) {
ensure_dir(DATA_DIR, 0o700);
let l = lock('config');
try {
for (let f in FILES) {
let data = readfile(`${dir}/${f}`);
if (data != null)
write_file(`/${f}`, data, 0o600);
if (data != null && !write_file(`/${f}`, data, 0o600))
die(`Couldn't write /${f}. Is the flash full?`);
}
}
catch (e) {
unlock(l);
die(e.message);
}
unlock(l);
system('chmod 600 /etc/config/dawnline');
@@ -185,9 +218,11 @@ export function backup_restore(name, path) {
die(e.message);
}
system(`rm -rf ${q(dir)}`);
// Live counters must follow the restored file.
// Live counters must follow the restored file: the agent reloads them from
// flash on its next tick (its watcher may write the old ones again before).
unlink(`${RUN_DIR}/usage.json`);
unlink(`${RUN_DIR}/events.json`);
write_file(live.USAGE_RELOAD, `${time()}`, 0o600);
return apply.apply();
};
@@ -279,7 +314,9 @@ export function import_json(data) {
system(`rm -rf ${q(dir)}`);
backup_create('pre-import');
let l = lock('config');
write_file('/etc/config/dawnline', text, 0o600);
let ok = write_file('/etc/config/dawnline', text, 0o600);
unlock(l);
if (!ok)
die("Couldn't write /etc/config/dawnline. Is the flash full?");
return apply.apply();
};
@@ -4,10 +4,11 @@
import { cursor } from 'uci';
import {
valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int,
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, NAME_RULE, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import * as net from 'dawnline.net';
import * as schema from 'dawnline.schema';
import { policy as updates_policy } from 'dawnline.updates';
export const CONFIG = 'dawnline';
@@ -68,28 +69,31 @@ export function open_cursor() {
export function load(c) {
c ??= open_cursor();
let s = c.get_all(CONFIG, 'settings') ?? {};
// Types, defaults and ranges of the settings live in dawnline.schema (one
// place): what is read here is what settings_update would have accepted.
let g = (k) => schema.get(s, k);
let m = {
settings: {
portal_enabled: bool(s.portal_enabled, false),
portal_port: toint(s.portal_port, 8443),
portal_host: s.portal_host ?? '',
portal_enabled: g('portal_enabled'),
portal_port: g('portal_port'),
portal_host: g('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',
portal_alt: g('portal_alt'),
portal_cert: g('portal_cert'),
portal_key: g('portal_key'),
portal_title: g('portal_title'),
// Where unknown portal links go instead of a bare 404 (empty = 404).
portal_redirect: s.portal_redirect ?? '',
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),
portal_redirect: g('portal_redirect'),
default_device_limit: g('default_device_limit'),
geo_enabled: g('geo_enabled'),
geo_provider: g('geo_provider'),
hostnames: g('hostnames'),
domain: g('domain'),
log_connections: g('log_connections'),
// Repair tunnels and services on its own (the agent, every minute).
watchdog: bool(s.watchdog, true),
watchdog: g('watchdog'),
// 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'),
home_dns_fallback: g('home_dns_fallback'),
// Settings → Updates (automatic checks and updates of the components).
updates: updates_policy(s),
// Raw retention values; dawnline.live policy() interprets them.
@@ -158,6 +162,8 @@ export function load(c) {
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
device_limit: toint(r.device_limit, m.settings.default_device_limit),
code: r.code ?? '',
// When the personal link was last made (0 for links from before this was kept).
code_set: toint(r.code_set, 0),
expires: r.expires ?? '',
quota_gb: num(r.quota_gb, 0),
quota_period: r.quota_period == 'total' ? 'total' : 'month',
@@ -236,23 +242,23 @@ function within_hours(h, ts) {
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) {
/** Bytes used in the person's quota period (the month of `ts`, default now). */
export function person_usage(p, usage, ts) {
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()];
let mm = u.months?.[month_key(ts)];
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) {
/** Quota in bytes for the period of `ts` (default now): base + that month's bonus, 0 = unlimited. */
export function person_quota(p, ts) {
if (!(p.quota_gb > 0))
return 0;
let gb = p.quota_gb;
if (p.bonus_gb > 0 && p.bonus_month == month_key())
if (p.bonus_gb > 0 && p.bonus_month == month_key(ts))
gb += p.bonus_gb;
return gb * 1073741824;
};
@@ -272,8 +278,8 @@ export function own_state(m, p, usage, ts) {
// "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)
let quota = person_quota(p, ts);
if (quota > 0 && person_usage(p, usage, ts) >= quota)
return 'quota';
let h = parse_hours(p.hours);
if (h && !within_hours(h, ts))
@@ -476,7 +482,7 @@ export function new_code() {
export function create_person(c, m, a) {
if (!valid_name(a.name))
fail('Enter a name (up to 48 characters).');
fail(NAME_RULE);
// 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, '_');
@@ -512,6 +518,7 @@ export function create_person(c, m, a) {
c.set(CONFIG, slug, 'access', access);
c.set(CONFIG, slug, 'device_limit', `${limit}`);
c.set(CONFIG, slug, 'code', new_code());
c.set(CONFIG, slug, 'code_set', `${time()}`);
c.set(CONFIG, slug, 'created', `${time()}`);
if (a.expires)
c.set(CONFIG, slug, 'expires', a.expires);
@@ -533,7 +540,7 @@ export function update_person(c, m, id, a) {
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).');
fail(NAME_RULE);
set('name', trim(a.name));
}
if (a.access != null) {
@@ -592,7 +599,7 @@ export function update_person(c, m, id, a) {
set('hours', a.hours);
}
if (a.note != null)
set('note', substr(trim(a.note), 0, 500));
set('note', ucut(trim(a.note), 500));
if (type(a.services) == 'array') {
for (let sid in a.services)
if (!m.services[sid])
@@ -608,6 +615,24 @@ export function update_person(c, m, id, a) {
fail('Unknown circle.');
set('circle', a.circle);
}
// Another server: every device gets an address in its tunnel (so each
// needs its configuration again); circles and home networks are the old
// server's and go.
if (a.server != null && a.server != '' && a.server != p.server) {
if (!m.servers[a.server])
fail('Unknown server.');
set('server', a.server);
p.server = a.server;
for (let did in p.devices) {
let addr = alloc_address(m, m.servers[a.server]);
if (!addr)
fail(`No free address left on ${m.servers[a.server].name}.`);
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.delete(CONFIG, id, 'circle');
c.delete(CONFIG, id, 'home_net');
}
if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
if (length(nets))
@@ -750,6 +775,113 @@ export function server_errors(m, srv, others_subnets) {
return errs;
};
/**
* What is wrong inside a model as a whole, beyond each server: devices with
* an address outside their server's subnet, the server's own address, a
* prefix on it or one shared with another device (the access sets are keyed
* by address, and one bad peer line makes `awg syncconf` refuse the whole
* server), malformed keys, people and devices pointing at servers, people,
* circles or services that do not exist, and two people with one link. [] when
* it is consistent. Import, restore and Health check it; the runtime sync
* skips what it would reject (dawnline.awg, dawnline.nft).
*/
export function model_errors(m) {
let errs = [];
let codes = {}, addrs = {};
for (let id, p in m.people) {
let who = `Person ${p.name}`;
if (p.server != '' && !m.servers[p.server])
push(errs, `${who}: server ${p.server} does not exist.`);
if (p.circle != '' && !m.circles[p.circle])
push(errs, `${who}: circle ${p.circle} does not exist.`);
for (let sid in p.services)
if (!m.services[sid])
push(errs, `${who}: home service ${sid} does not exist.`);
if (p.code != '') {
if (codes[p.code])
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`);
codes[p.code] = p.name;
}
}
for (let id, d in m.devices) {
let p = m.people[d.person];
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
if (!p) {
push(errs, `${who}: person ${d.person} does not exist.`);
continue;
}
if (!valid_key(d.public_key))
push(errs, `${who}: the public key is not a key.`);
if (d.private_key != '' && !valid_key(d.private_key))
push(errs, `${who}: the private key is not a key.`);
if (d.preshared_key != '' && !valid_key(d.preshared_key))
push(errs, `${who}: the preshared key is not a key.`);
let n = ip2int(d.address);
if (n == null) {
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`);
continue;
}
let srv = m.servers[p.server];
let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last))
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`);
else if (t && n == t.first)
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`);
let key = `${p.server} ${d.address}`;
if (addrs[key])
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`);
addrs[key] = who;
}
for (let id, ci in m.circles)
if (!m.servers[ci.server])
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`);
return errs;
};
/**
* Give every device on a server an address in `subnet` (the server's new
* tunnel network), lowest first: used by server_update when the network
* changes. Each device then needs its configuration again (the address is
* in it). Fails when the subnet cannot hold them.
*/
export function renumber_server(c, m, srv, subnet) {
srv.subnet = subnet;
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices)
m.devices[did].address = '';
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices) {
let addr = alloc_address(m, srv);
if (!addr)
fail(`${subnet} has no room for every device on ${srv.name}.`);
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.set(CONFIG, srv.id, 'subnet', subnet);
};
/**
* The DNS labels of a person's devices, { device id: label }, unique within
* the person: two devices whose names give one label ("iPhone" and
* "iPhone!", or two Cyrillic names) get -2, -3 by age. Hostnames in
* /tmp/hosts (dawnline.apply) and the ones the UI shows (dawnline.view) both
* come from here, so what is shown resolves.
*/
export function device_labels(m, p) {
let out = {}, used = {};
let devs = sort(map(p.devices, (id) => m.devices[id]), (a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
for (let d in devs) {
let base = host_label(d.name), l = base;
for (let n = 2; used[l]; n++)
l = `${substr(base, 0, 37)}-${n}`;
used[l] = true;
out[d.id] = l;
}
return out;
};
/**
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
* A forwarded port never reaches the router itself, so nothing here can listen on it.
@@ -813,7 +945,9 @@ export function portal_link(m, p, host) {
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
}
let pp = portal_public_port(m);
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
// An IPv6 address needs its brackets in a URL.
let h = index(host, ':') >= 0 && !match(host, /^\[/) ? `[${host}]` : host;
return `https://${h}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
};
/** The main link (QR, invite card, Copy link). */
@@ -42,11 +42,11 @@ export function add(person, name, kind, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
apply.sync();
let s = apply.sync();
let m = core.load();
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
awg.mark_issued(m, id);
return { id, config: awg.client_config(m, m.devices[id]) };
return { id, config: awg.client_config(m, m.devices[id]), warning: s.warning };
};
/**
@@ -89,15 +89,19 @@ export function rotate(id, opts) {
});
// The device a portal page came through would lose its tunnel before the
// answer gets out: load the new key a moment after answering.
let s = null;
if (opts.defer)
sh_bg('sleep 3; /usr/bin/dawnline sync');
else
apply.sync();
s = apply.sync();
let m = core.load();
let d = m.devices[id];
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
awg.mark_issued(m, id);
return awg.client_config(m, d);
let cfg = awg.client_config(m, d);
if (s?.warning)
cfg.warning = s.warning;
return cfg;
};
/** Remove a device. Returns the runtime sync. */
@@ -5,11 +5,12 @@
// named dawnline_* are ever changed.
import { readfile, unlink } from 'fs';
import { q, sh, sh_out, uniq, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
import { q, sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
import { cursor } from 'uci';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as nft from 'dawnline.nft';
import * as loop from 'dawnline.loop';
const LOOP_ZONE = 'dl_loop';
/*
@@ -42,12 +43,33 @@ export function sync(m, dry) {
let snap = net.snapshot(true);
let portal_zone = null, want_loop = false;
// Where tunnel DNS is sent (dawnline.nft): into the netns for home names
// while any server runs "like a home device", and to the LAN's DNS for
// everyone else. A server that does not forward to those zones on its own
// gets a rule for port 53 alone.
let any_loop = length(filter(values(m.servers), (s) => s.lan_like && length(core.tunnels(s)))) > 0;
let lan_dns = loop.lan_dns();
let lan_dns_zone = null;
if (lan_dns)
for (let dev, d in snap.devices)
if (d.zone && in_nets(lan_dns, d.nets ?? []))
lan_dns_zone ??= d.zone;
for (let id, srv in m.servers) {
if (!length(core.tunnels(srv)))
continue;
let z = `dawnline_${id}`;
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
if (!srv.lan_like && any_loop)
sec(`${z}_loopdns`, 'rule', {
name: `Dawnline-${srv.ifname}-names`, src: srv.ifname, dest: LOOP_ZONE,
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
});
if (lan_dns_zone && lan_dns_zone != srv.ifname && index(sn.zones, lan_dns_zone) < 0)
sec(`${z}_landns`, 'rule', {
name: `Dawnline-${srv.ifname}-dns`, src: srv.ifname, dest: lan_dns_zone, dest_ip: lan_dns,
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
});
sec(`${z}_zone`, 'zone', {
// Forward within the zone (device to device) is decided by the inet dawnline table.
name: srv.ifname, network: [ srv.ifname ],
@@ -1,14 +1,20 @@
// 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.
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
// counters. Only the agent performs lookups, on its minute tick and within a
// time budget, never on the 1-second watcher; the UI reads the cache.
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util';
import { stat } from 'fs';
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
const CACHE = `${DATA_DIR}/geo.json`;
const CACHE = `${RUN_DIR}/geo.json`;
const SAVED = `${DATA_DIR}/geo.json`;
const TTL = 30 * 86400;
const RETRY = 86400;
// Entries kept at least; addresses still shown are never pushed out (resolve).
const CAP = 500;
// [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 ],
@@ -30,16 +36,30 @@ export function is_public(ip) {
};
export function load() {
return read_json(CACHE, null) ?? { ips: {}, home: null };
return read_json(CACHE, null) ?? read_json(SAVED, null) ?? { ips: {}, home: null };
};
/** The live copy (tmpfs); flush() puts it on flash. */
export function save(cache) {
ensure_dir(DATA_DIR, 0o700);
ensure_dir(RUN_DIR);
write_json(CACHE, cache, 0o600);
};
/** Copy the live cache to flash when it is newer (the agent, about hourly and on a clean stop). */
export function flush() {
let live = stat(CACHE);
if (!live || live.mtime <= (stat(SAVED)?.mtime ?? 0))
return false;
let c = read_json(CACHE, null);
if (!c)
return false;
ensure_dir(DATA_DIR, 0o700);
write_json(SAVED, c, 0o600);
return true;
};
function fetch_json(url) {
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`);
let out = sh_out(`uclient-fetch -q -T 5 -O - ${q(url)}`);
if (!out)
return null;
try {
@@ -79,13 +99,17 @@ export function lookup(provider, ip) {
};
/**
* Resolve up to `max` addresses that are missing or stale. Returns true when
* the cache changed (the caller saves it).
* Resolve up to `max` of `ips` that are missing or stale, within `budget`
* seconds (each lookup may wait on the network). Returns true when the cache
* changed (the caller saves it). `ips` is also what is still shown: the cache
* is kept bounded by dropping other entries only, oldest first, so a lookup
* is never repeated for an address that is still on the map.
*/
export function resolve(settings, cache, ips, max) {
export function resolve(settings, cache, ips, max, budget) {
let now = time(), changed = false, done = 0;
let started = now;
for (let ip in ips) {
if (done >= max)
if (done >= max || (budget != null && time() - started >= budget))
break;
if (!is_public(ip))
continue;
@@ -103,12 +127,17 @@ export function resolve(settings, cache, ips, max) {
else
cache.ips[ip] = { fail: now };
}
// Keep the cache bounded: drop the oldest entries beyond 500.
let shown = {};
for (let ip in ips)
shown[ip] = true;
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]];
if (length(all) > CAP) {
let other = sort(filter(all, (ip) => !shown[ip]),
(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) - CAP && i < length(other); i++) {
delete cache.ips[other[i]];
changed = true;
}
}
return changed;
};
@@ -132,4 +161,6 @@ export function place(cache, ip) {
export function clear() {
save({ ips: {}, home: null });
ensure_dir(DATA_DIR, 0o700);
write_json(SAVED, { ips: {}, home: null }, 0o600);
};
@@ -11,6 +11,7 @@ import * as fw from 'dawnline.fw';
import * as loop from 'dawnline.loop';
import * as net from 'dawnline.net';
import * as awg from 'dawnline.awg';
import * as builds from 'dawnline.awg_builds';
import * as lookup from 'dawnline.lookup';
import * as pc from 'dawnline.portalcert';
@@ -232,34 +233,102 @@ function reply_check(id, title, proto, port, r) {
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** What kind of IPv4 the WAN has: public, cgnat (100.64/10), private (behind another router), or none. */
export function wan_kind(wan) {
let wc = wan ? ip2int(wan) : null;
if (wc == null)
return 'none';
if (in_cidr(wc, PRIVATE[0]))
return 'cgnat';
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
};
/**
* What a public address points at, for Health and the "as you type" check on
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
* here (an IPv4 of it is this router's WAN), v6_only }.
*/
export function endpoint_facts(srv, host) {
let ips = host ? lookup.resolve(host) : [];
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
return {
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
here: wan != null && index(ips4, wan) >= 0,
v6_only: !length(ips4) && length(ips6) > 0,
};
};
/** The facts in words: { status: ok|warn|error, text }. `proto_note` names what must get through ("UDP 4500"). */
export function endpoint_words(f, proto_note) {
if (!f.host)
return { status: 'error', text: 'No public address: devices will not know where to connect.' };
if (!length(f.ips))
return { status: 'error', text: `${f.host} does not resolve.` };
if (f.cloudflare)
return { status: 'error', text: `${f.host} → ${join(', ', f.ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.` };
if (f.v6_only)
return { status: f.kind == 'public' ? 'warn' : 'ok', text: `${f.host} → ${join(', ', f.ips6)}: IPv6 only, so only devices with IPv6 connect${f.kind == 'public' ? ` (the router's IPv4 ${f.wan} has no name)` : ''}.` };
if (f.kind == 'cgnat' || f.kind == 'private')
return { status: 'warn', text: f.kind == 'cgnat'
? `The WAN address ${f.wan} is CGNAT (shared by the ISP): ${proto_note} cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.`
: `The WAN address ${f.wan} is private: this router is behind another one. Forward ${proto_note} on it, or devices cannot connect.` };
if (f.wan && !f.here)
return { status: 'warn', text: `${f.host} points at ${join(', ', f.ips4)}, not this router (WAN ${f.wan}). Check your DNS / DDNS.` };
return { status: 'ok', text: f.here ? `${f.host} points at this router (${f.wan}).` : `${f.host} → ${join(', ', f.ips)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
function endpoint_check(id, title, srv, host, proto_note) {
if (!host)
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
let ips = lookup.resolve(host);
let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
let wc = wan ? ip2int(wan) : null;
let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0;
if (!length(ips))
return check(id, title, 'error', `${host} does not resolve.`);
if (cgnat)
return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`);
if (length(filter(ips, (a) => cloudflare_ip(a))))
return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`);
if (wan && index(ips, wan) < 0)
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`);
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`);
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
return check(id, title, w.status, w.text);
}
/**
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
* Dawnline's (pref < 5205) whose table has a default route of its own sends
* marked tunnel traffic straight out, past "like a home device". Reported,
* since those marks belong to that package. [] when none.
*/
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
if (!mm || +mm[1] >= 5205)
continue;
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
let def = match(routes, /(^|\n)default [^\n]*/)?.[0] ?? '';
if (def == '' || match(def, /local default/) || index(def, `dev ${net.INTERNAL.transit}`) >= 0)
continue;
push(out, `pref ${mm[1]} fwmark 0x${mm[2]} → table ${mm[4]}`);
}
return out;
}
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
let out = sh('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
let m = match(out ?? '', /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
return m ? +m[1] : null;
}
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.load();
let title = 'AmneziaWG installed';
if (length(st.missing ?? []))
if (length(st.missing ?? [])) {
// The module was built for the kernel of the firmware it was installed on.
let kc = builds.kernel_changed();
if (kc && index(st.missing, 'kmod-amneziawg') >= 0)
return check('awg', title, 'error',
`The firmware changed (kernel ${kc.was} → ${kc.now}): the AmneziaWG build installed for it is gone. Install the build for this firmware.`,
'install:awg', 'AmneziaWG needs a build for the new firmware');
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
}
if (!st.loaded) {
// load() tried it: the second modprobe only repeats why.
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
@@ -286,19 +355,30 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
if (up) {
let expected = 0;
// By key, not by count: a stale peer standing in for a missing one would
// make the numbers match.
let states = apply.states_for(m, core.load_usage());
let wanted = {}, expected = 0;
for (let did, d in m.devices) {
let p = m.people[d.person];
if (p?.server == id && !d.disabled && states[d.person] == 'active')
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
wanted[d.public_key] = true;
expected++;
}
let actual = 0;
}
let loaded = {}, actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname)
if (p.ifname == srv.ifname) {
loaded[k] = true;
actual++;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn',
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
}
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
let same = !missing && !extra;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, same ? 'ok' : 'warn',
same ? `${actual} device${actual == 1 ? ' is' : 's are'} loaded in the tunnel.` :
`${missing} of ${expected} device${expected == 1 ? '' : 's'} missing${extra ? `, ${extra} loaded that should not be` : ''}.`,
same ? null : 'sync'));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
@@ -396,6 +476,15 @@ export function health(m) {
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart'));
// A full overlay fails every config write on the router, Dawnline's and
// OpenWrt's own; backups and history are what Dawnline adds to it.
let free = overlay_free_kb();
if (free != null)
push(out, check('flash', 'Free space on the router', free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
free < 2048 ? `${int(free / 1024 * 10) / 10} MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.`
: `${int(free / 1024)} MB free on the overlay.`,
null, 'The router is running out of flash'));
if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
return out;
@@ -403,9 +492,24 @@ export function health(m) {
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 ? 'Table inet dawnline enforces who may reach LAN and the internet.'
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.',
nft_ok ? null : 'apply'));
if (length(filter(values(m.servers), (s) => s.lan_like && s.enabled))) {
let pr = policy_routing();
push(out, check('policy', 'Internet like a home device not bypassed', length(pr) ? 'warn' : 'ok',
length(pr) ? `Policy routing on the router (${join('; ', pr)}) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters.`
: 'No other policy routing ahead of the tunnel rules.',
null, 'Other policy routing bypasses the home-device path'));
}
// A device the sync has to leave out (a merged import, a hand-edited config).
let data = core.model_errors(m);
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok',
length(data) ? `${join(' ', slice(data, 0, 4))}${length(data) > 4 ? ` (${length(data) - 4} more)` : ''} Such devices are left out of the tunnels: fix or remove them.`
: 'Every device has a key and an address of its own inside its server.'));
let fwc = cursor();
fwc.load('firewall');
@@ -465,6 +569,10 @@ export function fix(id) {
}
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
if (m) {
// Only Dawnline's own tunnels: never another interface of the router.
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
if (!length(mine))
die(`${m[1]} is not one of Dawnline's tunnels.`);
system(`ifup ${q(m[1])}`);
return { ok: true };
}
@@ -11,14 +11,14 @@ import {
iface_status as util_iface_status, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as schema from 'dawnline.schema';
// Online while the WireGuard session lives: it is dropped 180 s after its
// handshake, and a device that is there renews it every 2 min (a little slack
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
export const ONLINE_WINDOW = 190;
const KEEP_DAYS = 62;
const KEEP_MONTHS = 24;
const KEEP_EVENTS = 2000;
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
/* ---------- retention policy ---------- */
@@ -29,7 +29,7 @@ export const CATEGORY = {
device_added: 'people', device_removed: 'people', devices_removed: 'people',
device_changed: 'people', device_keys: 'people', link_changed: 'people',
person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people',
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
};
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
@@ -38,9 +38,6 @@ 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
@@ -62,13 +59,14 @@ export function policy(s) {
else if (type(cats) != 'array')
cats = split(cats, /[ ,]+/);
cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
// Defaults and ranges come from dawnline.schema, like every other setting.
return {
keep_days: int_or(s.log_keep_days, 30),
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
keep_days: schema.get(s, 'log_keep_days'),
max: schema.get(s, 'log_max'),
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),
persist: schema.get(s, 'log_persist'),
usage_days: schema.get(s, 'usage_keep_days'),
usage_months: schema.get(s, 'usage_keep_months'),
};
};
@@ -110,7 +108,10 @@ export function presence() {
* handshake, rx, tx } }, presence }. See dawnline.awg.
*/
export function dump(m) {
let d = awg.dump();
// Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on
// the router that cannot be read is not our trouble.
let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null;
let d = awg.dump(mine);
d.presence = presence();
return d;
};
@@ -134,8 +135,13 @@ function empty_usage() {
return { devices: {}, people: {}, updated: 0, flushed: 0 };
}
export function load_usage() {
let u = read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
/**
* The usage counters: the live copy in RUN_DIR, else what flash holds. With
* `from_flash` only flash counts (a restore put new counters there, and the
* watcher may have written the old live ones again since).
*/
export function load_usage(from_flash) {
let u = (from_flash ? null : read_json(`${RUN_DIR}/usage.json`, null)) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
// Per-app counters of earlier test builds are not kept.
delete u.clients;
return u;
@@ -397,6 +403,10 @@ export function persist_events(pol) {
unlink(`${DATA_DIR}/events.json`);
return;
}
// Only when something was logged since the last copy: flash is written rarely.
let live_st = stat(`${RUN_DIR}/events.json`);
if (!live_st || live_st.mtime <= (stat(`${DATA_DIR}/events.json`)?.mtime ?? 0))
return;
let ev = read_json(`${RUN_DIR}/events.json`, null);
if (ev != null) {
ensure_dir(DATA_DIR, 0o700);
@@ -4,7 +4,7 @@
// time, so a slow DNS server must not hold up the whole admin UI.
import { readfile } from 'fs';
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util';
import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
import * as live from 'dawnline.live';
import * as net from 'dawnline.net';
@@ -23,9 +23,10 @@ function valid_name(h) {
}
/**
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not
* resolve). IP addresses map to themselves. Every uncached name is asked of
* every server at once; the first server (in SERVERS order) that answers wins.
* Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
* does not resolve). IP addresses map to themselves. Every uncached name is
* asked of every server at once, A and AAAA; the first server (in SERVERS
* order) that answers wins.
*/
export function resolve_all(hosts) {
let out = {}, now = time(), todo = [];
@@ -33,7 +34,7 @@ export function resolve_all(hosts) {
for (let h in hosts) {
if (h == null || out[h] != null)
continue;
if (ip2int(h) != null) {
if (ip2int(h) != null || is_ip6(h)) {
out[h] = [ h ];
continue;
}
@@ -55,14 +56,16 @@ export function resolve_all(hosts) {
let cmds = [];
for (let i = 0; i < length(todo); i++)
for (let j = 0; j < length(SERVERS); j++)
for (let t in [ 'a', 'aaaa' ])
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
push(cmds, `( nslookup -type=a -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
for (let i = 0; i < length(todo); i++) {
let ips = [];
for (let j = 0; j < length(SERVERS) && !length(ips); j++) {
let r = readfile(`${dir}/${i}.${j}`) ?? '';
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null);
for (let j = 0; j < length(SERVERS) && !length(ips); j++)
for (let t in [ 'a', 'aaaa' ]) {
let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
}
out[todo[i]] = ips;
cache[todo[i]] = { ts: now, ips };
@@ -57,23 +57,42 @@ export function uhttpd() {
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
};
/** 1380 was every server's stored MTU before it became automatic (by device type and disguise). */
/*
* Steps that cannot tell from the config whether they ran are recorded in
* `settings.migrated` (a list), so they run exactly once.
*/
function migrated(c, name) {
let done = c.get('dawnline', 'settings', 'migrated') ?? [];
return index(type(done) == 'array' ? done : [ done ], name) >= 0;
}
function mark_migrated(w, name) {
let done = w.get('dawnline', 'settings', 'migrated') ?? [];
w.set('dawnline', 'settings', 'migrated', [ ...(type(done) == 'array' ? done : [ done ]), name ]);
}
/*
* 1380 was every server's stored MTU before it became automatic (by device
* type and disguise). Once only: an admin may choose 1380 again on purpose.
*/
function auto_mtu() {
let c = cursor();
c.load('dawnline');
if (migrated(c, 'auto_mtu'))
return;
let any = false;
c.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
any = true;
});
if (!any)
return;
store.transact((w, m) => {
w.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
w.delete('dawnline', s['.name'], 'mtu');
});
mark_migrated(w, 'auto_mtu');
});
if (any)
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers');
}
@@ -9,8 +9,8 @@
// 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.
// chosen interfaces form the server's nft `home_<id>` 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';
@@ -68,6 +68,15 @@ export function sync(m) {
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue;
}
// A disguise this build cannot run (a 3.1 preset after a rollback to
// 2.0): the kernel would drop those options silently and run a tunnel
// no device can reach. Down, and said so, until the build or the
// disguise is changed.
let why = tools ? awg.obf_unsupported(srv.obf) : null;
if (why) {
block(srv, `is kept down: ${why}`, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
continue;
}
delete srv.blocked;
want[ifn] = true;
if (!tools)
@@ -5,7 +5,7 @@
// changes often (update, one atomic transaction).
import { unlink } from 'fs';
import { sh, ensure_dir, write_file, rand_hex, ip2int, RUN_DIR } from 'dawnline.util';
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
@@ -74,17 +74,33 @@ export function access_sets(m, usage, states) {
return sets;
};
// Duplicate members (two devices with one address) would make the whole load fail.
function set_elems(arr) {
arr = uniq(arr);
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
/** The portal's TCP ports people may reach through the tunnel (never SSH, DNS or LuCI, whatever is stored). */
function portal_ports(m) {
if (!m.settings.portal_enabled)
return [];
let ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
let ports = filter([ m.settings.portal_port ], ok);
if (core.portal_http(m) && ok(core.portal_http_port(m)))
push(ports, core.portal_http_port(m));
return ports;
}
function table(m, sets) {
let ifs = [], lan = [], tun = [];
let ifs = [], tun = [];
let dns_addr = loop.client_dns();
if (!ip4(dns_addr))
dns_addr = null;
let rt = loop.resolver_target();
let snap = net.snapshot();
// Each server's home networks are its own: with several servers, "all
// home" on one never reaches the other's networks (set lan_<id>).
let homes = {};
for (let id, srv in m.servers) {
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
let tns = core.tunnels(srv);
@@ -93,13 +109,13 @@ function table(m, sets) {
push(tun, t.subnet);
}
if (length(tns))
push(lan, ...net.server_net(srv, snap).nets);
homes[id] = net.collapse(net.server_net(srv, snap).nets);
}
lan = net.collapse(lan);
tun = net.collapse(tun);
let t = [];
push(t, 'table inet dawnline {');
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
for (let id, nets in homes)
push(t, ` set home_${id} { type ipv4_addr; flags interval; auto-merge; ${set_elems(nets)} }`);
// Tunnel subnets are never "home", even inside a wider route to the LAN.
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
@@ -118,15 +134,30 @@ function table(m, sets) {
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');
// Every packet is judged by the rules below, not only the first of a
// connection: a change of access cuts open connections too, instead of
// letting a session or a long UDP flow run on for days. Only what has no
// rule of its own passes on its connection: errors and the like, answers
// to the admin's port forwards, and the router's own pings.
push(t, ' ct state related accept');
push(t, ' ct status dnat accept');
push(t, ' icmp type { echo-request, echo-reply } 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');
let pp = portal_ports(m);
if (length(pp))
// Their own portal, also with the VPN on (the address may be this router's).
push(t, ` fib daddr type local tcp dport { ${join(', ', pp)} } accept`);
// The router itself is part of home: for everyone with all of it, and for
// people limited to some networks only on the addresses in those.
push(t, ' fib daddr type local ip saddr @lan_all accept');
push(t, ' fib daddr type local ip saddr . ip daddr @lan_part accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
push(t, ' ip daddr @lan_nets ip daddr != @tun_nets ip saddr @lan_all accept');
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` iifname "${tn.ifname}" ip daddr @home_${id} ip daddr != @tun_nets ip saddr @lan_all accept`);
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
@@ -155,7 +186,9 @@ function table(m, sets) {
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
push(t, ' ip saddr @lan_nets ip saddr != @tun_nets ip daddr @lan_all accept');
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` oifname "${tn.ifname}" ip saddr @home_${id} ip saddr != @tun_nets ip daddr @lan_all accept`);
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
push(t, ' counter reject with icmpx admin-prohibited');
push(t, ' }');
@@ -195,6 +228,11 @@ export function load(script) {
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
};
/** The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. */
export function render(m, sets) {
return table(m, sets);
};
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
export function rebuild(m, sets) {
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
@@ -208,9 +246,10 @@ export function rebuild(m, sets) {
export function update(sets) {
let s = '';
for (let name in SETS) {
let members = uniq(sets[name]);
s += `flush set inet dawnline ${name}\n`;
if (length(sets[name]))
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
if (length(members))
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
}
return load(s);
};
@@ -2,7 +2,7 @@
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
// callback, which gets their output line by line.
import { access, popen } from 'fs';
import { access, popen, stat } from 'fs';
import { q } from 'dawnline.util';
function run(cmd) {
@@ -79,20 +79,56 @@ export function refresh(log) {
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
};
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
let out = run('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
let m = match(out, /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
return m ? +m[1] : null;
}
/**
* Room for `files` (or `need_kb` from the feeds): the package manager
* unpacks before it removes, so a full flash leaves half an install behind.
* Dies with the numbers.
*/
function preflight(files, need_kb, log) {
let free = overlay_free_kb();
if (free == null)
return;
let need = need_kb ?? 512;
for (let f in files ?? [])
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
if (free < need)
die(`Not enough free space on the router: ${int(free / 1024)} MB free, about ${int(need / 1024) + 1} MB needed. Remove old backups or packages first`);
log?.(` ${int(free / 1024)} MB free on the overlay`);
}
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
export function install_files(files, force, log) {
preflight(files, 0, log);
let args = join(' ', map(files, q));
return logged(is_apk()
? `apk add --allow-untrusted ${args}`
: `opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
if (!is_apk())
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
// apk leaves an installed version alone, whatever the file: a reinstall
// that changed nothing is a failure, not a silent "done".
let marker = '/usr/share/ucode/dawnline/util.uc';
let before = force ? stat(marker)?.mtime : null;
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
if (ok && force && before != null && stat(marker)?.mtime == before) {
log?.(' apk did not reinstall the version that is already installed');
die("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router");
}
return ok;
};
/** Packages by name from the feeds. */
export function add(names, log) {
preflight(null, 2048, log);
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
};
export function upgrade(names, log) {
preflight(null, 2048, log);
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
};
@@ -105,7 +141,9 @@ export function upgradable() {
let up = {};
if (is_apk()) {
for (let line in split(run('apk version -l "<"').out, '\n')) {
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
// "name-version-rN < newer": the version is what follows the last dash
// before the release suffix (a name may hold digits, a version no dash).
let m = match(line, /^(\S+)-([^- ]+-r[0-9]+)\s+<\s+(\S+)/);
if (m)
up[m[1]] = m[3];
}
@@ -19,8 +19,14 @@
// other sites' logs. The portal can only manage the person's own devices
// within their limits, and not those the admin turned off (dawnline.devices).
//
// Changes through a link are limited too (a link is not a terminal: a few
// dozen every quarter hour), and the configurations themselves (keys, the
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
// shows the page, but gets them from its HTTPS twin.
//
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
// CGI script (www/cgi-bin/portal) is its wrapper.
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
// that answers anything not shaped like a link (its not_found() twin).
import { stat, readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
@@ -41,6 +47,8 @@ const SHARED_LIMIT = FAIL_LIMIT * 25;
const SHARED_KEY = 'cloudflare';
// Clients remembered at most (the oldest go first).
const RATE_MAX = 2000;
// Changes one link may make within FAIL_WINDOW (each one writes flash and syncs the tunnels).
const ACTION_LIMIT = 40;
const BODY_MAX = 8192;
// The early end of a request (a response was written).
const DONE = '__dawnline_done__';
@@ -216,6 +224,21 @@ function rate_fail(r) {
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
}
/** One more change through this link; refused beyond ACTION_LIMIT per window. */
function rate_action(r) {
let key = `act:${r.person.id}`;
let l = lock('portal-rate');
let st = rate_state();
let v = st[key] ?? { first: time(), count: 0 };
v.count++;
st[key] = v;
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
if (v.count > ACTION_LIMIT)
fail(r, '429 Too Many Requests', 'Too many changes in a short time. Try again in a few minutes.');
}
/* ---------- pages ---------- */
/** The app shell; it reads the code from its own URL and sends it along. */
@@ -295,6 +318,26 @@ function need_open(r) {
fail(r, '403 Forbidden', why);
}
/** The same link over HTTPS (for a plain-HTTP visitor), or null when this is it. */
function https_url(r) {
if (r.https)
return null;
let host = r.host;
let h = match(host, /^\[/) ? match(host, /^(\[[^\]]*\])/)?.[1] : split(host, ':')[0];
let port = r.m.settings.portal_port;
return `https://${h}${port == 443 ? '' : `:${port}`}${r.base}`;
}
/**
* Keys and the disguise never travel in the clear: over plain HTTP a
* configuration is refused, and the answer names the HTTPS link to use.
*/
function need_https(r) {
let u = https_url(r);
if (u)
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u });
}
/** Everything the page shows. */
function state(r) {
let m = r.m, person = r.person;
@@ -315,12 +358,18 @@ function state(r) {
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
},
can_add: length(person.devices) < person.device_limit,
locked: LOCKED[v.state] != null,
// Over plain HTTP: where the configurations are (keys only travel encrypted).
https_url: https_url(r),
kinds: core.KINDS,
// The router's day: access ends and usage days follow its clock, not the browser's.
today: today(),
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
now: time(),
version: VERSION,
};
}
@@ -339,9 +388,11 @@ function api_state(r) {
function api_add(r) {
need_open(r);
need_https(r);
let b = body(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
@@ -350,6 +401,7 @@ function api_add(r) {
function api_config(r, id) {
let d = own_device(r, id);
need_open(r);
need_https(r);
awg.mark_issued(r.m, d.id);
send_json(r, '200 OK', awg.client_config(r.m, d));
}
@@ -361,6 +413,7 @@ const ACTIONS = {
return {};
},
rotate: (r, d, b) => {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
@@ -379,6 +432,7 @@ function api_device(r, id) {
let act = ACTIONS[b.action];
if (!act)
fail(r, '400 Bad Request', 'Unknown action.');
rate_action(r);
let res = act(r, d, b);
reload(r);
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
@@ -425,7 +479,7 @@ export function handle(io) {
let host = header('host') ?? '';
let m = core.load();
let r = {
io, env, m, path, https,
io, env, m, path, https, host,
method: env.REQUEST_METHOD ?? 'GET',
peer: env.REMOTE_ADDR ?? '',
buckets: buckets(env),
@@ -452,11 +506,12 @@ export function handle(io) {
if (p.code == code)
r.person = p;
// A wrong code or a blocked client: indistinguishable from a path that does
// not exist. Only well-formed guesses count towards the limit.
if (rate_blocked(r))
not_found(r);
// A wrong code is indistinguishable from a path that does not exist. Only
// well-formed guesses count towards the limit, and a client over it is just
// no longer counted: a valid link always opens, so guesses from a shared
// address (every Cloudflare visitor) cannot lock its owner out.
if (r.person == null) {
if (!rate_blocked(r))
rate_fail(r);
not_found(r);
}
@@ -34,16 +34,27 @@ export function clamp_days(v) {
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
};
export const METHODS = [ 'off', 'standard', 'strong', 'max' ];
export const METHODS = [ 'off', 'balanced', 'max' ];
/** The disguise a new server gets: the strongest this router can run. */
export function default_method() {
let c = awg.caps();
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
};
/** A disguise method the installed AmneziaWG can run. */
export function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
if (name == 'max' && !awg.caps().v3)
let c = awg.caps();
if (name == 'max' && !c.v3)
die(awg.installed()
? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.');
if (name == 'balanced' && !c.v2)
die(awg.installed()
? 'Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.');
return name;
};
@@ -4,7 +4,7 @@
import { readfile } from 'fs';
import { cursor } from 'uci';
import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util';
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength, NAME_RULE } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
@@ -27,8 +27,8 @@ function new_id(m, make) {
function service_set(a) {
let name = str(a.name);
if (name == '' || length(name) > 48)
die('Enter a service name.');
if (!valid_name(name))
die(`Service: ${NAME_RULE}`);
let address = str(a.address);
if (!schema.ipv4(address))
die('Address must be an IPv4 address.');
@@ -54,8 +54,8 @@ function service_set(a) {
c.delete(core.CONFIG, id, 'port');
return id;
});
apply.sync();
return { id };
let s = apply.sync();
return { id, warning: s.warning };
}
function service_delete(a) {
@@ -72,8 +72,8 @@ function service_delete(a) {
c.delete(core.CONFIG, pid, 'service');
}
});
apply.sync();
return { ok: true };
let s = apply.sync();
return { ok: true, warning: s.warning };
}
/* ---------- circles ---------- */
@@ -81,8 +81,8 @@ function service_delete(a) {
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
function circle_set(a) {
let name = str(a.name);
if (name == '' || length(name) > 32)
die('Enter a circle name (up to 32 characters).');
if (!valid_name(name) || ulength(name) > 32)
die('Enter a circle name: up to 32 characters, without < > " or \\.');
let res = store.transact((c, m) => {
let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci)
@@ -112,9 +112,9 @@ function circle_set(a) {
}
return { id, edit: !!ci, server: m.servers[server].name };
});
apply.sync();
let s = apply.sync();
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
return { id: res.id, circles: values(core.load().circles) };
return { id: res.id, circles: values(core.load().circles), warning: s.warning };
}
function circle_delete(a) {
@@ -128,9 +128,9 @@ function circle_delete(a) {
c.delete(core.CONFIG, pid, 'circle');
return { name: ci.name, server: m.servers[ci.server]?.name };
});
apply.sync();
let s = apply.sync();
admin_log('awg', 'removed', 'circle', res.name, res.server);
return { circles: values(core.load().circles) };
return { circles: values(core.load().circles), warning: s.warning };
}
/* ---------- devices at home ---------- */
@@ -11,7 +11,7 @@ import * as devices from 'dawnline.devices';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
'bonus_gb', 'hours', 'note', 'dns_mode' ];
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
/* ---------- people ---------- */
@@ -39,19 +39,23 @@ function person_update(a) {
fields.circle = a.circle;
if (type(a.home_nets) == 'array')
fields.home_nets = a.home_nets;
let m0 = null;
let before = store.transact((c, m) => {
let p = m.people[a.id];
m0 = m;
core.update_person(c, m, a.id, fields);
return p;
});
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
// "moved to Test" says more than "server".
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
// Access changes affect the nft sets and client AllowedIPs.
apply.sync();
let s = apply.sync();
let m = core.load();
let u = core.load_usage();
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access };
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
}
function person_pause(a) {
@@ -67,16 +71,34 @@ function person_pause(a) {
return apply.sync();
}
/** A new personal link: the old one stops working at once (every portal request carries the code). */
/**
* A new personal link: the old one stops working at once (every portal
* request carries the code). What the old link already handed out stays
* unless asked: `remove` lists the person's devices to take away with it.
*/
function person_regen(a) {
store.transact((c, m) => {
let gone = store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
c.set(core.CONFIG, a.id, 'code', core.new_code());
c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
let gone = [];
for (let id in (type(a.remove) == 'array' ? a.remove : []))
if (m.devices[id]?.person == a.id) {
push(gone, m.devices[id]);
core.delete_device(c, m, id);
}
return gone;
});
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
let s = null;
if (length(gone)) {
for (let d in gone)
live.add_event({ type: 'device_removed', person: a.id, device: d.id, detail: d.name, dname: d.name, dkind: d.kind, by: 'admin' });
s = apply.sync();
}
let m = core.load();
return { link: core.portal_url(m, m.people[a.id]) };
return { link: core.portal_url(m, m.people[a.id]), removed: length(gone), warning: s?.warning };
}
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
@@ -138,11 +160,11 @@ export const methods = {
},
person_update: {
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
call: wrap(person_update),
},
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
person_regen: { args: { id: '' }, call: wrap(person_regen) },
person_regen: { args: { id: '', remove: [] }, call: wrap(person_regen) },
person_links: { args: { id: '' }, call: wrap(person_links) },
person_delete: { args: { id: '' }, call: wrap(person_delete) },
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
@@ -2,7 +2,7 @@
// Interfaces settings, its disguise, and removing it.
import { cursor } from 'uci';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, NAME_RULE, rand_int, uniq, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
@@ -14,7 +14,7 @@ import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices';
import { wrap, str, check_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
/** Server ids that would shadow a portal path. */
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
@@ -77,8 +77,9 @@ function free_port(taken) {
}
function free_subnet(taken) {
for (let i = 0; i < 200; i++) {
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)));
for (let i = 0; i < 300; i++) {
// 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
let bad = false;
for (let t in taken) {
let tc = parse_cidr(t);
@@ -164,21 +165,33 @@ function setup_defaults(a) {
let fc = cursor();
fc.load('firewall');
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
let host = m.settings.portal_host;
let snap = net.snapshot(true);
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
let kind = health.wan_kind(wan_ip || null);
let host = m.settings.portal_host, from = host ? 'portal' : '';
if (!host) {
// Prefer a DDNS name, then an ACME certificate's, then the WAN address.
// Prefer a DDNS name, then an ACME certificate's, then the WAN address —
// but never a private or CGNAT one: nobody on the internet reaches it.
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (s) => {
if (!host && s.lookup_host && s.enabled == '1')
if (!host && s.lookup_host && s.enabled == '1') {
host = s.lookup_host;
});
if (!host)
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
if (!host)
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
from = 'ddns';
}
let wan_zone = index(zones, 'wan') >= 0 ? 'wan' : zones[1];
});
if (!host) {
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
from = host ? 'cert' : '';
}
if (!host && kind == 'public') {
host = wan_ip;
from = 'wan';
}
}
// The zones the WAN and LAN devices are in, whatever they are called.
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
let udp = udp_taken(m, null, wan_zone);
let tcp = tcp_taken(m);
let port = free_port(udp);
@@ -189,10 +202,14 @@ function setup_defaults(a) {
port,
subnet: free_subnet(map(networks, (n) => n.cidr)),
endpoint: host,
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
endpoint_from: from,
wan_kind: kind,
wan_ip: wan_ip || null,
// Automatic.
mtu: 0,
zones,
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
lan_zone,
wan_zone,
// A portal already on keeps its port; a new one takes the server's number when it can.
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
@@ -204,6 +221,22 @@ function setup_defaults(a) {
};
}
/**
* Where a public address points, as the admin types it (debounced in the
* UI): the same facts Health uses, in words. `id` names the server whose WAN
* to compare with (a new one: the default WAN).
*/
function endpoint_probe(a) {
let host = str(a.host);
if (host != '' && !valid_host(host))
die('Public address must be a hostname or IP address.');
let m = core.load();
let srv = m.servers[str(a.id)] ?? null;
let f = health.endpoint_facts(srv, host);
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
return { ...f, status: w.status, text: w.text };
}
/** AmneziaWG can run a server: installed, and its kernel module loads. */
function need_awg_loaded() {
devices.need_awg();
@@ -244,7 +277,7 @@ function server_create(a) {
}
check_udp_port(port, udp);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
let preset = str(a.preset) || 'standard';
let preset = str(a.preset) || default_method();
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
let pc = parse_cidr(srv.subnet);
if (pc)
@@ -264,6 +297,8 @@ function server_create(a) {
let set = (k, v) => c.set(core.CONFIG, id, k, v);
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server');
if (!valid_name(str(a.name) || 'Home'))
die(`Server: ${NAME_RULE}`);
set('name', str(a.name) || 'Home');
set('ifname', ifname);
set('port', `${port}`);
@@ -312,7 +347,7 @@ function server_create(a) {
// after that (by hand, or by an older installer) needs a network restart.
let network_restart = !awg.state().handler;
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
return { id, applied: r, network_restart };
return { id, applied: r, network_restart, warning: r.warning };
}
/* ---------- interfaces ---------- */
@@ -465,12 +500,13 @@ function server_update(a) {
die('Unknown server.');
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
if (v.name != null) {
if (str(v.name) == '')
die('Name cannot be empty.');
if (!valid_name(str(v.name)))
die(`Server: ${NAME_RULE}`);
set('name', str(v.name));
}
// Empty = the portal's address (core.endpoint_host), as at creation.
if (v.endpoint != null) {
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint)))
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
die('Public address must be a hostname or IP address.');
set('endpoint', str(v.endpoint));
}
@@ -504,10 +540,23 @@ function server_update(a) {
else
c.delete(core.CONFIG, srv.id, 'dns');
}
// A new tunnel network: private, free, and every device renumbered into it.
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
let pc = parse_cidr(str(v.subnet));
if (!pc)
die('Subnet must look like 10.77.0.0/24.');
if (!core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
for (let t in taken)
if (cidr_overlaps(pc, parse_cidr(t)))
die(`Subnet overlaps ${t}.`);
core.renumber_server(c, m, srv, cidr_str(pc));
}
return srv;
});
// For the log: what changed, in words. Turning on or off is its own line.
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
let what = [];
for (let k, label in labels) {
if (v[k] == null)
@@ -529,8 +578,19 @@ function server_update(a) {
return r;
}
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
function server_ports(a) {
let m = core.load();
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
}
function server_obfuscation(a) {
let preset = str(a.preset) || 'standard';
let preset = str(a.preset) || default_method();
let o = awg.obf_preset(check_method(preset));
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
@@ -581,6 +641,8 @@ export const methods = {
lan_like: true, portal_enabled: false, portal_port: 0 },
call: wrap(server_create),
},
server_ports: { args: { id: '' }, call: wrap(server_ports) },
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
@@ -115,10 +115,11 @@ function settings_update(a) {
check_portal(core.load(c), m);
return { restart, was: m.settings };
});
let s = null;
if (res.restart)
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
else
apply.sync();
s = apply.sync();
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
let now = core.load().settings, was = res.was;
if (now.portal_enabled != was.portal_enabled)
@@ -140,7 +141,10 @@ function settings_update(a) {
}
if (now.watchdog != was.watchdog)
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
return settings_get({});
let out = settings_get({});
if (s?.warning)
out.warning = s.warning;
return out;
}
export const methods = {
@@ -11,7 +11,28 @@ import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as lookup from 'dawnline.lookup';
import { wrap, clamp_days } from 'dawnline.rpc.common';
import * as health from 'dawnline.health';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
/** The router's public IPv4 (null when none or private). */
function wan_public(m) {
let w = lookup.router_wan(m);
return w && health.wan_kind(w) == 'public' ? w : null;
}
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
function own_addresses(m) {
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
return own;
}
/** Router location plus one point per (device, recent client address). */
function geo_view(m, usage, dmp) {
@@ -84,8 +105,17 @@ function server_view(m, srv, usage, dmp, rates, days) {
online++;
}
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
// The newest handshake from a public address that is not the router's own:
// proof that the port is reachable from the internet.
let own = own_addresses(m);
let reached = 0;
for (let id, d in m.devices)
if (m.people[d.person]?.server == srv.id)
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
if (geo.is_public(ip) && !own[ip] && ts > reached)
reached = ts;
return {
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
// What devices get now, by kind (mtu 0 = automatic).
@@ -169,12 +199,18 @@ function status(a) {
like_home: loop.status(),
awg: awg.caps(),
awg_state: awg.state(),
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
wan: wan_public(m),
};
}
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
function events_list(a) {
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up');
let person = str(a.person), since = +a.since || 0;
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up' &&
(!person || e.person == person) && (!since || (e.ts ?? 0) > since));
let n = +a.limit || 300;
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
}
@@ -239,14 +275,15 @@ function usage_clear(a) {
}
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
/** The live revision, and the version answering (a page notices an update under it). */
function rev() {
return { rev: +(live.presence()?.rev ?? 0) };
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
}
export const methods = {
rev: { call: wrap(rev) },
status: { args: { days: 30 }, call: wrap(status) },
events: { args: { limit: 300 }, call: wrap(events_list) },
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
@@ -6,7 +6,7 @@
// config_get_bool does, so the service and the code never disagree.
import { stat } from 'fs';
import { ip2int, valid_host } from 'dawnline.util';
import { ip2int, valid_host, ulength } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates';
/* ---------- addresses ---------- */
@@ -114,7 +114,7 @@ export function to_int(v, dflt, lo, hi) {
export const SETTINGS = {
portal_enabled: { type: 'bool', dflt: false, restart: true },
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
portal_alt: { type: 'hosts', dflt: [], restart: true },
portal_alt: { type: 'hosts', dflt: [], restart: true, msg: 'Other addresses must be hostnames or IP addresses.' },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
@@ -124,7 +124,8 @@ export const SETTINGS = {
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' },
hostnames: { type: 'bool', dflt: true },
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
geo_enabled: { type: 'bool', dflt: true },
// Off until the admin turns it on: lookups send people's addresses to a third party.
geo_enabled: { type: 'bool', dflt: false },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
log_connections: { type: 'bool', dflt: true },
watchdog: { type: 'bool', dflt: true },
@@ -164,9 +165,13 @@ export function validate(key, val) {
let t = spec.type;
if (t == 'hosts') {
let lst = [];
for (let x in (type(val) == 'array' ? val : []))
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0)
for (let x in (type(val) == 'array' ? val : [])) {
// A typo must not vanish on Save: refused, like the main address.
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
bad(spec, key);
if (trim(x) != '' && index(lst, trim(x)) < 0)
push(lst, trim(x));
}
return length(lst) ? lst : null;
}
if (t == 'targets') {
@@ -222,7 +227,7 @@ export function validate(key, val) {
bad(spec, key);
}
else if (t == 'text') {
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
if (ulength(val) > spec.max || match(val, /[[:cntrl:]]/))
bad(spec, key);
}
return val;
@@ -9,9 +9,14 @@ import * as core from 'dawnline.core';
/** Section names that are never ids of people, devices, servers, services or circles. */
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
/** Commit the dawnline config and keep it readable by root only. */
/**
* Commit the dawnline config and keep it readable by root only. A commit
* that did not reach flash (full or read-only overlay) is an error: the
* caller's change never happened, and nothing downstream may act on it.
*/
export function commit(c) {
c.commit(core.CONFIG);
if (!c.commit(core.CONFIG))
die(`Couldn't save /etc/config/dawnline: ${c.error() ?? 'the write failed'}. Is the flash full?`);
system('chmod 600 /etc/config/dawnline');
};
@@ -115,8 +115,11 @@ export function install(ctx, arg) {
out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps no package files).
if (ctx.pol.keep && out.to != VERSION && upd.kept('app')?.version != VERSION) {
// The version being replaced, for Roll back (downloaded again: opkg keeps
// no package files). Always for an automatic run: nobody is there to
// recover a router whose new version does not come up (postupdate rolls
// back to it on its own).
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
try {
system(`mkdir -p '${ctx.work}/keep'`);
@@ -52,6 +52,9 @@ export function check(ctx) {
if (!fw)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'Cannot detect the firmware target' };
if (fw.snapshot)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only' };
let dir = `${ctx.work}/check`;
system(`mkdir -p '${dir}'`);
let sources = {};
@@ -114,8 +117,14 @@ function reload_module(ctx, before, after) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`);
}
sh('rmmod amneziawg');
// Both steps must really happen: the new tools against the old module (or
// no module at all) leave every tunnel down while the job says "done".
ctx.run('rmmod amneziawg');
if (stat('/sys/module/amneziawg'))
die('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update');
ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg'))
die("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)");
for (let i in ifaces)
sh(`ifup '${i}'`);
}
@@ -227,5 +236,6 @@ export function install(ctx, arg) {
pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed();
settle(ctx, before, out.after);
builds.record(id, fw.tag, out.after);
return out;
};
@@ -4,7 +4,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.5.1';
export const VERSION = '0.8.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -455,38 +455,139 @@ export function in_cidr(ip, c) {
return n != null && n >= c.net && n < c.net + c.size;
};
/* ---------- text ---------- */
/** Characters in a UTF-8 string (length() counts bytes: "Мама" is 8 of them). */
export function ulength(s) {
let n = 0;
for (let i = 0; i < length(s); i++)
if ((ord(s, i) & 0xc0) != 0x80)
n++;
return n;
};
/** The first `n` characters of a UTF-8 string, never cut inside one. */
export function ucut(s, n) {
let i = 0, c = 0;
while (i < length(s)) {
if ((ord(s, i) & 0xc0) != 0x80) {
if (c == n)
break;
c++;
}
i++;
}
return substr(s, 0, i);
};
// Cyrillic (Russian, Ukrainian) to Latin: а-я by code point from U+0430, then
// ё, і, ї, є, ґ; the rest of a string passes as it is.
const CYR_A = 0x430;
const CYRILLIC = [ 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
'f', 'kh', 'ts', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya' ];
const CYRILLIC_MORE = { '1105': 'yo', '1110': 'i', '1111': 'yi', '1108': 'ye', '1169': 'g' };
/**
* Cyrillic letters written in Latin ("Мама" → "mama", "Юля" → "yulya"):
* ids, hostnames and file names are ASCII, and a person should recognise
* their own in them. Other characters are left alone.
*/
export function translit(s) {
let out = '', i = 0, n = length(s);
while (i < n) {
let b = ord(s, i);
if (b < 0x80) {
out += substr(s, i, 1);
i++;
continue;
}
let cp = 0, len = 1;
if ((b & 0xe0) == 0xc0 && i + 1 < n) {
cp = ((b & 0x1f) << 6) | (ord(s, i + 1) & 0x3f);
len = 2;
}
else if ((b & 0xf0) == 0xe0 && i + 2 < n) {
cp = ((b & 0x0f) << 12) | ((ord(s, i + 1) & 0x3f) << 6) | (ord(s, i + 2) & 0x3f);
len = 3;
}
else if ((b & 0xf8) == 0xf0 && i + 3 < n)
len = 4;
// Upper case to lower: А-Я, Ё, І, Ї, Є, Ґ.
if (cp >= 0x410 && cp <= 0x42f)
cp += 0x20;
else if (cp == 0x401)
cp = 0x451;
else if (cp == 0x406)
cp = 0x456;
else if (cp == 0x407)
cp = 0x457;
else if (cp == 0x404)
cp = 0x454;
else if (cp == 0x490)
cp = 0x491;
let t = cp >= CYR_A && cp < CYR_A + length(CYRILLIC) ? CYRILLIC[cp - CYR_A] : CYRILLIC_MORE[`${cp}`];
out += t != null ? t : substr(s, i, len);
i += len;
}
return out;
};
/* ---------- 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;
};
/** A name people see: 1-48 characters (not bytes), none of < > " \ or control characters. */
export function valid_name(s) {
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
};
/** What valid_name wants, for the admin. */
export const NAME_RULE = 'Enter a name: up to 48 characters, without < > " or \\.';
export function valid_key(s) {
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
};
/** An IPv6 address in its usual spelling (no zone, no brackets). */
export function is_ip6(s) {
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == 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);
ip2int(s) != null || is_ip6(s));
};
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
export function valid_date(s) {
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null;
let m = type(s) == 'string' ? match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) : null;
if (!m)
return false;
let l = localtime(timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 12, min: 0, sec: 0 }));
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
};
/** Turn a display name into a portal slug candidate. */
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
export function slugify(s) {
let out = lc(trim(`${s ?? ''}`));
let out = lc(translit(trim(`${s ?? ''}`)));
out = replace(out, /[^a-z0-9]+/g, '-');
out = replace(out, /^-+|-+$/g, '');
return substr(out, 0, 32) || 'user';
};
/**
* A device's name as a DNS label ("Galaxy S24" → "galaxy-s24", "Телефон" →
* "telefon"): at most 40 characters, "device" when nothing is left.
*/
export function host_label(s) {
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
return l || 'device';
};
/* ---------- time ---------- */
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
@@ -29,6 +29,13 @@ export function device_view(m, d, usage, dmp) {
let ts = time();
let hs = peer?.handshake || u?.handshake || 0;
let p = m.people[d.person];
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
let label = '';
if (m.settings.hostnames && p) {
m._labels ??= {};
m._labels[p.id] ??= core.device_labels(m, p);
label = m._labels[p.id][d.id] ?? 'device';
}
let v = {
id: d.id,
name: d.name,
@@ -44,7 +51,7 @@ export function device_view(m, d, usage, dmp) {
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}` : '',
hostname: label ? `${label}.${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),
@@ -96,6 +103,7 @@ export function person_view(m, p, usage, dmp, states, opts) {
v.home_nets = p.home_nets;
v.circle = p.circle;
v.created = p.created;
v.code_set = p.code_set;
}
return v;
};
@@ -12,12 +12,16 @@ import * as health from 'dawnline.health';
import * as awg from 'dawnline.awg';
import * as nft from 'dawnline.nft';
import * as netifd from 'dawnline.netifd';
import * as upd from 'dawnline.updates';
export const STATE = `${RUN_DIR}/watchdog.json`;
/** The agent writes the time here on every tick. */
export const BEAT = `${RUN_DIR}/agent.beat`;
// Seconds before the next repair, by the number of repairs so far.
const WAIT = [ 0, 120, 600, 1800, 3600 ];
// Good minutes in a row before a repaired target's count of repairs is
// forgotten: one good minute between two failures is still flapping.
const SETTLED = 10;
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
export function iface_errors(ifname) {
@@ -77,8 +81,10 @@ function probes(m) {
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
// A reload keeps LuCI logins; a restart (second try) signs everyone out.
repair: { what: 'reloading rpcd', run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
// A reload keeps LuCI logins; a restart (second try) signs everyone out —
// and after three it stops: restarting rpcd every hour for good would
// sign every admin out for good.
repair: { what: 'reloading rpcd', max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
});
return out;
}
@@ -87,6 +93,9 @@ function probes(m) {
export function run(m) {
let now = time();
let fix = m.settings.watchdog;
// An update is replacing packages or restarting tunnels: what looks broken
// meanwhile is being worked on; repairs would only get in its way.
let busy = upd.busy();
let st = read_json(STATE, {});
let t = type(st.targets) == 'object' ? st.targets : {};
let repairs = filter(st.repairs ?? [], (r) => now - r.ts < 86400);
@@ -100,16 +109,30 @@ export function run(m) {
if (x.reported)
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
x.bad = 0;
x.tries = 0;
x.next = 0;
x.reported = false;
x.stuck = false;
// The repairs so far are forgotten only once it has stayed up a while:
// a target that fails every other minute keeps its back-off.
x.good = (x.good ?? 0) + 1;
if (x.good >= SETTLED) {
x.tries = 0;
x.good = 0;
}
continue;
}
x.good = 0;
// One bad minute can be a restart in progress.
if (++x.bad < 2)
continue;
if (!fix || !p.repair) {
if (busy)
continue;
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
slog(p.src, 'error', `${p.problem} — not repaired again (${p.repair.max} repairs didn't help)`, p.detail?.(), p.who);
x.reported = true;
continue;
}
if (!fix || !p.repair || (p.repair.max && x.tries >= p.repair.max)) {
if (!x.reported)
slog(p.src, 'error', p.problem, p.detail?.(), p.who);
x.reported = true;
+2 -1
View File
@@ -27,4 +27,5 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
## Checks
- `scripts/lint-ucode.py` and `scripts/check-ucode.sh` (compiles on the router) pass before any deploy; new directories and entry points are added to both, and executables to the mode check in `.github/workflows/ci.yml`.
- `scripts/lint-ucode.py` and `scripts/ucode-container.sh` (compiles and runs `tests/ucode` in the OpenWrt rootfs containers; `scripts/check-ucode.sh` compiles on the router instead) pass before any deploy; new directories and entry points are added to `lint-ucode.py` and `scripts/compile-ucode.sh`, and executables to the mode check in `.github/workflows/ci.yml`.
- Pure functions get a case in `tests/ucode/<module>.test.uc`; what reads the clock takes an optional `ts` so a test can pass one.
+2 -2
View File
@@ -19,9 +19,9 @@ grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/pack
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" \
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \
"$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"
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc"
find "$STAGE" -name '.DS_Store' -delete
TAR="$OUT/luci-app-dawnline-$VERSION.tar.gz"
+342
View File
@@ -0,0 +1,342 @@
#!/usr/bin/env node
// Capture the raw README screenshots from a live router into
// docs/screenshots/raw/<name>.png (2x PNG); scripts/frame-screenshots.py then
// puts them into a browser window for the README.
//
// Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome
// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with
// the password from LUCI_PASSWORD or asked on the terminal; the session lives
// only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed.
//
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
// [--mask real=shown ...] [--name real=shown ...]
// [--only overview,people]
//
// --mask replaces text on every page before the capture (a domain, a name);
// --name does the same for a person's name in any case, and for their initials.
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
const SCALE = 2;
const args = { router: 'https://outline.lan', person: '', mask: [], names: [], only: [] };
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
const v = () => process.argv[++i] ?? die(`${a} needs a value`);
if (a === '--router') args.router = v().replace(/\/+$/, '');
else if (a === '--person') args.person = v();
else if (a === '--mask') args.mask.push(v().split('=', 2));
else if (a === '--name') args.names.push(v().split('=', 2));
else if (a === '--only') args.only = v().split(',');
else die(`unknown argument ${a}`);
}
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
/** As shared/format initials(): first letters of the first and last word, or the first two of one word. */
const initials = (name) => {
const p = name.trim().split(/\s+/);
return (p[0][0] + (p.length > 1 ? p[p.length - 1][0] : (p[0][1] ?? ''))).toUpperCase();
};
for (const [real, shown] of args.names)
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
function die(msg) {
console.error(msg);
process.exit(1);
}
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
const USER = process.env.LUCI_USER || 'root';
/*
* Each shot: the page, what must be on it before the capture, what to do
* first (in the page), and the area to keep (in the page, CSS pixels).
* Admin pages keep the theme's header and the content column, 48px either side.
*/
const column = `(() => {
const r = document.querySelector('.dl-root').getBoundingClientRect();
return { x: r.left - 48, w: r.width + 96 };
})()`;
// From the top down to an element; whatever follows it is hidden, not cut through.
const below = (sel) => `(() => {
const c = ${column}, el = document.querySelector(${JSON.stringify(sel)});
for (let e = el; e && !e.classList.contains('dl-root'); e = e.parentElement)
for (let n = e.nextElementSibling; n; n = n.nextElementSibling) n.style.visibility = 'hidden';
return { x: c.x, y: 0, width: c.w, height: el.getBoundingClientRect().bottom + 40 };
})()`;
const SHOTS = [
{
name: 'overview',
url: () => `${LUCI}/server`,
width: 1400,
ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas',
// The map shows the last 30 days, not only who is online now.
prep: `(() => {
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days');
b?.click();
})()`,
settle: 6000,
clip: below('.dl-srvov .dl-panel.flush'),
},
{
name: 'people',
url: () => `${LUCI}/server?section=people`,
width: 1400,
ready: '.dl-srvbody a[href*="dawnline/person"]',
clip: below('.dl-srvbody'),
},
{
name: 'person',
url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`,
width: 1400,
ready: '.dl-grid-person .dl-row',
// Down to the end of Access & limits; activity rows that would be cut are hidden.
clip: `(() => {
const c = ${column}, cut = document.querySelector('.dl-grid-person > .dl-col:last-child').getBoundingClientRect().bottom + 40;
document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => {
if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden';
});
return { x: c.x, y: 0, width: c.w, height: cut };
})()`,
},
{
name: 'access',
url: () => `${LUCI}/server?section=access`,
width: 1400,
ready: 'section.dl-ifcard details',
// The home network card alone, its folded lists closed.
prep: `(() => {
const card = [...document.querySelectorAll('section.dl-ifcard')].find((s) => s.querySelector('details'));
card.querySelectorAll('details[open]').forEach((d) => (d.open = false));
card.setAttribute('data-shot', '');
})()`,
clip: `(() => {
const r = document.querySelector('[data-shot]').getBoundingClientRect();
return { x: r.left - 12, y: r.top - 12, width: r.width + 24, height: r.height + 24 };
})()`,
},
{
name: 'portal',
url: (s) => s.portal,
width: 1320,
ready: 'body',
settle: 3000,
// The content: everything but full-width or full-height wrappers, 36px around it.
clip: `(() => {
let l = innerWidth, r = 0, b = 0;
for (const e of document.body.querySelectorAll('*')) {
const x = e.getBoundingClientRect();
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
l = Math.min(l, x.left);
r = Math.max(r, x.right);
b = Math.max(b, x.bottom);
}
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
})()`,
},
];
const MASK = `((pairs, inits) => {
const doc = new Map();
const isPrivate = (a) => a[0] === 10 || a[0] === 127 || (a[0] === 172 && a[1] >= 16 && a[1] < 32) ||
(a[0] === 192 && a[1] === 168) || (a[0] === 100 && a[1] >= 64 && a[1] < 128) || a[0] === 0 || a[0] >= 224;
const ip = (m) => {
const a = m.split('.').map(Number);
if (a.some((x) => x > 255) || isPrivate(a)) return m;
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
return doc.get(m);
};
const swap = (s) => pairs.reduce((t, [a, b]) => t.split(a).join(b), s).replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip);
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
for (let n; (n = w.nextNode()); ) {
const ini = inits.find(([a]) => n.nodeValue.trim() === a);
const v = ini ? n.nodeValue.replace(ini[0], ini[1]) : swap(n.nodeValue);
if (v !== n.nodeValue) n.nodeValue = v;
}
document.querySelectorAll('input').forEach((i) => { const v = swap(i.value); if (v !== i.value) i.value = v; });
})(${JSON.stringify(args.mask)}, ${JSON.stringify(INITIALS)})`;
async function password() {
if (process.env.LUCI_PASSWORD) return process.env.LUCI_PASSWORD;
if (!process.stdin.isTTY) die('Set LUCI_PASSWORD or run on a terminal');
process.stdout.write(`LuCI password for ${USER}: `);
execFileSync('stty', ['-echo'], { stdio: 'inherit' });
try {
const rl = createInterface({ input: process.stdin });
const line = await new Promise((ok) => rl.once('line', ok));
rl.close();
return line.replace(/\r$/, '');
} finally {
execFileSync('stty', ['echo'], { stdio: 'inherit' });
process.stdout.write('\n');
}
}
function findBrowser() {
const c = [
process.env.BROWSER,
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/chromium',
'/usr/bin/google-chrome',
];
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
}
/** A page over the DevTools protocol: send(method, params) and waitFor(event). */
async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = fail;
});
let id = 0;
const pending = new Map();
const waiters = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) {
const { ok, fail } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) {
for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params);
}
}
};
const send = (method, params = {}) =>
new Promise((ok, fail) => {
pending.set(++id, { ok, fail });
ws.send(JSON.stringify({ id, method, params }));
});
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
return { send, waitFor, close: () => ws.close() };
}
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
async function main() {
const pass = await password();
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
const chrome = spawn(
findBrowser(),
[
'--headless=new',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
// The router's certificate is usually for its public name, not router.lan.
'--ignore-certificate-errors',
'--hide-scrollbars',
'--no-first-run',
'--no-default-browser-check',
// MapLibre needs WebGL; headless gets it from SwiftShader.
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'about:blank',
],
{ stdio: 'ignore' },
);
try {
const portFile = join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
const port = readFileSync(portFile, 'utf8').split('\n')[0];
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable');
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
const evaluate = async (expression) => {
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
const go = async (url) => {
const loaded = page.waitFor('Page.loadEventFired');
await page.send('Page.navigate', { url });
await loaded;
};
const waitSel = async (sel, ms = 20000) => {
for (let t = 0; t < ms; t += 250) {
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
await sleep(250);
}
throw new Error(`timed out waiting for ${sel}`);
};
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
const viewport = (width, height = 2600) =>
page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: SCALE, mobile: false });
await viewport(1400);
await go(`${args.router}/cgi-bin/luci/`);
if (await evaluate(`!!document.querySelector('input[name=luci_password]')`)) {
await evaluate(`(() => {
document.querySelector('input[name=luci_username]').value = ${JSON.stringify(USER)};
document.querySelector('input[name=luci_password]').value = ${JSON.stringify(pass)};
})()`);
const loaded = page.waitFor('Page.loadEventFired');
await evaluate(`document.querySelector('form.login-form, form').submit()`);
await loaded;
if (await evaluate(`!!document.querySelector('input[name=luci_password]')`))
die(
(await evaluate(`!!document.querySelector('.login-error')`))
? `LuCI login failed: wrong password for ${USER} (LUCI_USER sets the user)`
: `LuCI login failed: still on the login page (${await evaluate('location.href')})`,
);
}
// The person to show (the first one on People unless --person) and their personal link.
const s = { person: args.person, portal: '' };
await go(`${LUCI}/server?section=people`);
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
if (!s.person)
s.person = await evaluate(
`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`,
);
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
.then((r) => r.link ?? r.links?.[0] ?? '')`);
for (const shot of SHOTS) {
if (args.only.length && !args.only.includes(shot.name)) continue;
const url = shot.url(s);
if (!url) {
console.log(`skip ${shot.name}: no URL (the portal is off?)`);
continue;
}
await viewport(shot.width);
await go(url);
await waitSel(shot.ready);
await sleep(2000);
if (shot.prep) await evaluate(shot.prep);
await sleep(shot.settle ?? 1500);
await evaluate(MASK);
const clip = await evaluate(shot.clip);
const { data } = await page.send('Page.captureScreenshot', {
format: 'png',
clip: { ...clip, scale: 1 },
captureBeyondViewport: true,
});
writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64'));
console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
}
page.close();
} finally {
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });
}
}
main().catch((e) => die(e.message));
+5 -19
View File
@@ -1,6 +1,7 @@
#!/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.
# the tree is unpacked under /tmp/dlc and scripts/compile-ucode.sh runs there
# (the same check CI runs in an OpenWrt rootfs container, scripts/ucode-container.sh).
# scripts/check-ucode.sh [root@host]
set -euo pipefail
HOST="${1:-root@outline.lan}"
@@ -12,21 +13,6 @@ TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
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
# Modules by their import name: dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc dawnline.rpc.x.
for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do
[ -f "$f" ] || continue
n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g')
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
[ -f "$f" ] || continue
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
ssh "$HOST" 'rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz'
# The script goes over stdin (`sh -s`), nothing of it stays on the router.
ssh "$HOST" 'sh -s /tmp/dlc; rc=$?; rm -rf /tmp/dlc; exit $rc' < "$(dirname "$0")/compile-ucode.sh"
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Compile-check every ucode file of a Dawnline tree without installing it:
# modules are imported by name (dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc
# dawnline.rpc.x) and entry points compiled with `ucode -c`. Needs ucode with
# its fs, uci, ubus and uloop modules, which is any OpenWrt box or an
# openwrt/rootfs container (scripts/ucode-container.sh); check-ucode.sh pipes
# this script to a router.
# scripts/compile-ucode.sh [ROOT] ROOT holds usr/ and etc/ (default: .)
#
# ucode resolves names at compile time and imports are static, so this catches
# a syntax error, a missing module and a named import that nothing exports.
set -eu
ROOT="$(cd "${1:-.}" && pwd)"
cd "$ROOT"
LIB="$ROOT/usr/share/ucode/*.uc"
rc=0
for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do
[ -f "$f" ] || continue
n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g')
out=$(ucode -L "$LIB" -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
# Entry points (ucode scripts outside the module tree); the shell ones live in
# the ShellCheck list of .github/workflows/ci.yml instead.
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline \
usr/share/dawnline/portal/cgi.uc; do
[ -f "$f" ] || { echo "FAIL $f: missing"; rc=1; continue; }
out=$(ucode -L "$LIB" -c -o /dev/null "$f" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
[ $rc = 0 ] && echo "all ucode files compile"
exit $rc
+8 -6
View File
@@ -1,9 +1,11 @@
#!/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).
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
are written to docs/screenshots/<name>.png at the same scale. 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
@@ -23,10 +25,10 @@ SHOTS = {
'people': 'router.lan · Dawnline · People',
'person': 'router.lan · Dawnline · Myata',
'portal': 'vpn.example.com/kamiro-telosu-bavine',
'map': 'router.lan · Dawnline · Overview',
'access': 'router.lan · Dawnline · Home · Access',
}
PAD_X, PAD_Y, BAR = 120, 96, 40
SCALE = 2
CANDIDATES = [
os.environ.get('BROWSER', ''),
@@ -75,7 +77,7 @@ def main():
if not os.path.exists(src):
print(f'skip {name}: no raw capture')
continue
iw, ih = png_size(src)
iw, ih = (v // SCALE for v in 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:
@@ -83,7 +85,7 @@ def main():
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}'],
f'--force-device-scale-factor={SCALE}', 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)
+43 -5
View File
@@ -3,8 +3,10 @@
ucode resolves names where they are used: calling a function that is declared
further down the same file fails at runtime ("access to undeclared variable").
Also: calls and named imports must match what a Dawnline module exports, and
the rpcd methods (dawnline.rpc.*) must match the plugin and its ACL.
Also: calls and named imports must match what a Dawnline module exports, the
rpcd methods (dawnline.rpc.*) must match the plugin and its ACL, and regexes
stay POSIX (rules/backend.md). Imports against the module layering are
reported as notes, not failures.
Run: scripts/lint-ucode.py [package root]
"""
import glob
@@ -22,9 +24,8 @@ files = modules + [
PLUGIN,
f"{root}/usr/libexec/dawnline/agent",
f"{root}/usr/libexec/dawnline/updater",
f"{root}/usr/libexec/dawnline/resolver",
f"{root}/usr/bin/dawnline",
f"{root}/usr/share/dawnline/portal/www/cgi-bin/portal",
f"{root}/usr/share/dawnline/portal/cgi.uc",
]
files = [f for f in files if os.path.exists(f)]
bad = 0
@@ -40,6 +41,16 @@ def strip_comments(text):
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
def blank_comments(text):
"""Comments replaced by their newlines: line numbers stay, their text goes."""
return re.sub(r'//[^\n]*|/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S)
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
# a delimiter (so a division keeps out). Good enough for how Dawnline writes them.
REGEX_LITERAL = re.compile(r'(?<![\w)\]])/((?:\\.|[^/\\\n])+)/[gis]*(?=[,);\s])')
def modname(path):
"""dawnline/rpc/people.uc → 'rpc.people' (as in import … from 'dawnline.rpc.people')."""
rel = os.path.relpath(path, MODDIR)[:-3]
@@ -55,7 +66,7 @@ for f in files:
problem(f"{f}:{line}: {name}() is used before its definition")
# In a module an exported function is an expression statement: its closing
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
lines = open(f, encoding='utf-8').read().split('\n')
lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
inside = None
for n, text in enumerate(lines, 1):
if inside is None and re.match(r'^export function \w+\(', text):
@@ -68,6 +79,14 @@ for f in files:
# not preceded by valid expression"), and let [a, b] = … does not compile.
if re.search(r'/[^/\n]*\(\?[:=!][^/\n]*/', text):
problem(f"{f}:{n}: ucode regexes are POSIX: no (?: (?= (?! groups")
# Lazy quantifiers (*? +? }?) and the [\s\S] class are PCRE: the C
# library's regcomp does something else with them or rejects them.
for m in REGEX_LITERAL.finditer(text):
body = m.group(1)
if re.search(r'(?<!\\)[*+}]\?', body):
problem(f"{f}:{n}: ucode regexes are POSIX: no lazy quantifiers (*? +? }}?) in /{body}/")
if re.search(r'\[\\[sS]\\[sS]\]', body):
problem(f"{f}:{n}: ucode regexes are POSIX: no [\\s\\S] class in /{body}/ (use (.|\\n) or a negated class)")
if re.match(r'\s*(let|const)\s*[\[{]', text):
problem(f"{f}:{n}: ucode has no destructuring")
@@ -124,5 +143,24 @@ if methods and os.path.exists(ACL):
if 'uci' in acl.get(kind, {}) and 'dawnline' in acl[kind]['uci']:
problem(f"{ACL}: {kind} grants uci 'dawnline' (private keys, no validation): use the rpc methods")
# Layering (rules/backend.md): util, schema → core → store → domain modules →
# apply → entry points. A module importing one from a layer above it is
# reported, not failed, until the existing edges are untangled.
LAYER = {'util': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'}
notes = 0
for f in modules:
mod = modname(f)
if mod.startswith('rpc.'):
continue # an entry point: may import anything
mine = LAYER.get(mod, 4)
for dep in re.findall(r"from 'dawnline\.([\w.]+)'", strip_comments(open(f, encoding='utf-8').read())):
theirs = LAYER.get(dep, 4)
if theirs > mine or (theirs == mine and mine < 4 and dep != mod):
print(f"note: {f}: {mod} ({LAYER_NAME[mine]}) imports dawnline.{dep} ({LAYER_NAME[theirs]}), a layer above it")
notes += 1
if notes:
print(f"lint-ucode: {notes} layering notes (not failures)")
print(f"lint-ucode: {len(files)} files checked" + (", problems found" if bad else ", ok"))
sys.exit(bad)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Run the ucode checks the way CI does: in an OpenWrt rootfs container with the
# release's own ucode and libuci — compile every file (compile-ucode.sh), then
# the unit tests (tests/ucode/run.sh). Needs docker; the repository is mounted
# read-only at /src, the container is thrown away.
# scripts/ucode-container.sh [24.10|25.12|all] [test name filter]
#
# Images are the x86-64 rootfs of the OpenWrt releases the packages are built
# for (build/Dockerfile, scripts/build-packages.sh), pinned by digest so a
# retagged image cannot change what CI runs. To move to a new release change
# the tag and the digest together (docker buildx imagetools inspect <image>).
set -euo pipefail
REPO="$(cd "$(dirname "$0")/.." && pwd)"
image_for() {
case "$1" in
24.10) echo 'openwrt/rootfs:x86-64-24.10.6@sha256:fd76f3afb9c390ef2915618b6e3d7187698c03ecc6c23d3a13f12b62d9c6209e' ;;
25.12) echo 'openwrt/rootfs:x86-64-25.12.3@sha256:af882e0583954fc2ceac6b081a9d214fc739cfea36a29b48795a5f15563aa3b5' ;;
*) echo "unknown release $1 (24.10 or 25.12)" >&2; exit 2 ;;
esac
}
releases="${1:-all}"
[ "$releases" = all ] && releases='24.10 25.12'
rc=0
for rel in $releases; do
image="$(image_for "$rel")"
echo "== OpenWrt $rel ($image)"
# The checks run from this stdin script (`sh -s`): ucode-mod-uloop is not in
# the 24.10 rootfs, so what is missing is installed from the release's feeds.
docker run --rm -i --platform linux/amd64 -v "$REPO:/src:ro" -e "FILTER=${2:-}" "$image" sh -s <<-'INNER' || rc=1
set -eu
missing=''
command -v ucode >/dev/null || missing='ucode'
for m in fs uci ubus uloop; do
[ -e "/usr/lib/ucode/$m.so" ] || missing="$missing ucode-mod-$m"
done
if [ -n "$missing" ]; then
echo "installing:$missing"
if command -v apk >/dev/null; then
# shellcheck disable=SC2086
apk add --quiet $missing
else
mkdir -p /var/lock
# shellcheck disable=SC2086
opkg update >/dev/null && opkg install $missing >/dev/null
fi
fi
sh /src/scripts/compile-ucode.sh /src/package/luci-app-dawnline/root
sh /src/tests/ucode/run.sh /src "$FILTER"
INNER
done
exit $rc
+96
View File
@@ -0,0 +1,96 @@
// dawnline.awg: disguise presets against their own validation, and the parser
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP).
import { readfile, writefile, unlink } from 'fs';
import * as awg from 'dawnline.awg';
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
let fixtures = sourcepath(0, true) + '/fixtures';
test('obf_preset off', () => {
let o = awg.obf_preset('off');
eq(o, { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }, 'plain WireGuard headers');
eq(awg.obf_errors(o), [], 'valid');
});
test('obf_preset balanced', () => {
for (let i = 0; i < 25; i++) {
let o = awg.obf_preset('balanced');
eq(awg.obf_errors(o), [], 'balanced is valid');
ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`);
let jmin = +o.jmin, jmax = +o.jmax;
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `junk sizes ${o.jmin}-${o.jmax}`);
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
ok(+o[k] >= 5, `${k} above the reserved values`);
ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`);
ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets');
eq(o.header_protection_key, null, 'no 3.1 values');
}
});
test('obf_preset max', () => {
let o = awg.obf_preset('max');
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey');
ok(+o.jc >= 4 && +o.jc <= 6, 'jc');
ok(substr(o.i1, 0, 3) == '<r ', 'DNS-like first packet');
eq([ o.random_trailers, o.disable_cookies, o.content_padding_addition ], [ 'on', 'on', '10-100' ], '3.1 options');
ok(substr(o.i2, 0, 3) == '<r ', 'DNS-answer second packet');
// The template varies by name length and top-level domain (the letters
// themselves are random at run time): over many servers, more than one shape.
let shapes = {};
for (let i = 0; i < 20; i++)
shapes[awg.obf_preset('max').i1] = true;
ok(length(keys(shapes)) > 1, 'signature packets differ between servers');
// The preset passes the server's own validation (jmin/jmax may be small: 0.5.2).
eq(awg.obf_errors(o), [], 'max is valid');
});
test('obf_errors', () => {
eq(awg.obf_errors({}), [], 'nothing set');
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range');
eq(awg.obf_errors({ jmin: '0', jmax: '0' }), [], 'zero junk sizes are allowed');
eq(awg.obf_errors({ jmin: '2000' }), [ 'jmin=2000 (0-1024)' ], 'jmin range');
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'jmin > jmax' ], 'order');
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 's1 + 56 = s2' ], 'the handshake size clash');
eq(awg.obf_errors({ s4: '33' }), [ 's4=33 (0-32)' ], 's4 range');
eq(awg.obf_errors({ jc: 'x' }), [ 'jc=x (0-10)' ], 'not a number');
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'h1-h4 must be distinct' ], 'duplicate headers');
eq(awg.obf_errors({ h1: '7-9', h2: 'abc' }), [ 'h2 must be a number or range' ], 'header ranges');
eq(awg.obf_neutral({ jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }), true, 'off is neutral');
eq(awg.obf_neutral({ jc: '4', jmin: '64', jmax: '128' }), false, 'junk is not neutral');
});
function dump_of(name) {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
return awg.dump();
}
test('dump: AmneziaWG 1.0 (14 interface fields)', () => {
let d = dump_of('1.0');
eq(d.ok, true, 'ok');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(d.peers['HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw='],
{ ifname: 'awgmain', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, 'peer with a session');
eq(d.peers['TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='],
{ ifname: 'awgmain', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
});
test('dump: AmneziaWG 2.0 (33 interface fields)', () => {
let d = dump_of('2.0');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(keys(d.peers), [ 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=' ], 'one peer');
});
test('dump: AmneziaWG 3.1 (33 interface fields, protection on)', () => {
let d = dump_of('3.1');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(length(d.peers), 2, 'two peers');
});
test('dump: the tool fails', () => {
unlink(AWG_DUMP);
let d = awg.dump();
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
});
+166
View File
@@ -0,0 +1,166 @@
// dawnline.core: the model read from the fixture config (real libuci), access
// hours, quotas and the derived person state at an explicit time, address
// allocation and the automatic MTU.
import * as core from 'dawnline.core';
// A local time that no time zone turns into another day.
function at(y, mo, d, h, mi) {
return timelocal({ year: y, mon: mo, mday: d, hour: h, min: mi, sec: 0 });
}
let m = core.load();
test('load reads the fixture', () => {
eq(keys(m.servers), [ 'main' ], 'servers');
eq(sort(keys(m.people)), [ 'alice', 'bob' ], 'people');
eq(m.servers.main.subnet, '10.9.0.0/29', 'subnet');
eq(m.servers.main.mtu, 1380, 'stored MTU');
eq(m.servers.main.obf, { jc: '4', jmin: '64', jmax: '128', s4: '12' }, 'disguise values as strings');
eq(m.servers.main.mesh, 'all', 'mesh default');
eq(m.people.alice.devices, [ 'alice_phone' ], 'devices attached to their person');
eq(m.people.alice.access, 'both', 'access');
eq(m.people.bob.access, 'internet', 'access default');
eq(m.people.bob.quota_gb, 2, 'quota as a number');
eq(m.people.bob.device_limit, 3, 'device limit from the settings default');
eq(m.devices.alice_phone.kind, 'phone', 'kind');
eq(m.settings.portal_enabled, true, 'bool setting');
eq(m.settings.updates.interval, '7d', 'update policy from the same section');
eq(m.settings.updates.targets, [ 'app' ], 'update targets list');
eq(m.settings.retention.log_connections, '0', 'raw retention values');
});
test('parse_hours', () => {
eq(core.parse_hours('07:00-23:00'), [ 420, 1380 ], 'day window');
eq(core.parse_hours('23:00-07:00'), [ 1380, 420 ], 'overnight window');
eq(core.parse_hours('7:00-23:00'), [ 420, 1380 ], 'one-digit hour');
eq(core.parse_hours('00:00-24:00'), [ 0, 1440 ], 'whole day');
eq(core.parse_hours('24:00-01:00'), null, 'start at 24:00');
eq(core.parse_hours('10:00-10:00'), null, 'empty window');
eq(core.parse_hours('always'), null, 'words');
eq(core.parse_hours(''), null, 'empty');
eq(core.parse_hours(null), null, 'null');
});
test('person_quota', () => {
let march = at(2026, 3, 10, 12, 0);
eq(core.person_quota({ quota_gb: 0 }, march), 0, 'unlimited');
eq(core.person_quota({ quota_gb: 2 }, march), 2147483648, '2 GiB');
eq(core.person_quota({ quota_gb: 2, bonus_gb: 1, bonus_month: '2026-03' }, march), 3221225472, 'bonus this month');
eq(core.person_quota({ quota_gb: 2, bonus_gb: 1, bonus_month: '2026-02' }, march), 2147483648, 'bonus of another month');
eq(core.person_quota({ quota_gb: -1 }, march), 0, 'negative is unlimited');
});
test('person_usage', () => {
let march = at(2026, 3, 10, 12, 0);
let usage = { people: { bob: { total: [ 100, 50 ], months: { '2026-03': [ 10, 5 ], '2026-02': [ 1000, 1000 ] } } } };
eq(core.person_usage({ id: 'bob', quota_period: 'month' }, usage, march), 15, 'this month');
eq(core.person_usage({ id: 'bob', quota_period: 'month' }, usage, at(2026, 4, 1, 0, 0)), 0, 'a month without traffic');
eq(core.person_usage({ id: 'bob', quota_period: 'total' }, usage, march), 150, 'total');
eq(core.person_usage({ id: 'nobody', quota_period: 'month' }, usage, march), 0, 'unknown person');
eq(core.person_usage({ id: 'bob' }, null, march), 0, 'no usage data');
});
test('own_state', () => {
let base = { id: 'p', paused: false, expires: '', expire_action: 'pause', quota_gb: 0, hours: '' };
let noon = at(2026, 3, 10, 12, 0);
eq(core.own_state(m, base, null, noon), 'active', 'nothing set');
eq(core.own_state(m, { ...base, paused: true }, null, noon), 'paused', 'paused');
eq(core.own_state(m, { ...base, expires: '2026-03-09' }, null, noon), 'expired', 'expired yesterday');
eq(core.own_state(m, { ...base, expires: '2026-03-10' }, null, noon), 'active', 'expires at the end of today');
eq(core.own_state(m, { ...base, expires: '2026-03-09', expire_action: 'notify' }, null, noon), 'active', 'notify keeps access');
let usage = { people: { p: { months: { '2026-03': [ 600000000, 600000000 ] } } } };
eq(core.own_state(m, { ...base, quota_gb: 1 }, usage, noon), 'quota', 'over quota');
eq(core.own_state(m, { ...base, quota_gb: 1, bonus_gb: 1, bonus_month: '2026-03' }, usage, noon), 'active', 'bonus lifts the quota');
eq(core.own_state(m, { ...base, quota_gb: 1 }, usage, at(2026, 4, 1, 0, 0)), 'active', 'a new month resets the usage');
eq(core.own_state(m, { ...base, hours: '09:00-17:00' }, null, noon), 'active', 'inside the hours');
eq(core.own_state(m, { ...base, hours: '09:00-17:00' }, null, at(2026, 3, 10, 20, 0)), 'hours', 'outside the hours');
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, at(2026, 3, 10, 23, 0)), 'active', 'overnight, before midnight');
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, at(2026, 3, 10, 5, 59)), 'active', 'overnight, after midnight');
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, noon), 'hours', 'overnight, daytime');
eq(core.own_state(m, { ...base, paused: true, expires: '2000-01-01' }, null, noon), 'paused', 'paused wins over expired');
eq(core.own_state(m, { ...base, expires: '2000-01-01', quota_gb: 1 }, usage, noon), 'expired', 'expired wins over quota');
});
test('person_state', () => {
let noon = at(2026, 3, 10, 12, 0);
let p = { id: 'p', server: 'main', paused: false, expires: '', expire_action: 'pause', quota_gb: 0, hours: '' };
eq(core.person_state(m, p, null, noon), 'active', 'server on');
eq(core.person_state(m, { ...p, server: 'gone' }, null, noon), 'no_server', 'no server');
let off = { servers: { main: { ...m.servers.main, enabled: false } } };
eq(core.person_state(off, p, null, noon), 'server_off', 'server off');
eq(core.person_state(off, { ...p, paused: true }, null, noon), 'server_off', 'server off is about the server');
ok(core.person_expired({ expires: '2000-01-01' }, noon), 'person_expired');
ok(!core.person_expired({ expires: '' }, noon), 'no end date');
ok(!core.person_expired({ expires: 'garbage' }, noon), 'bad date is not expired');
});
test('alloc_address', () => {
let srv = { id: 'main', subnet: '10.9.0.0/29' };
let other = { id: 'other', subnet: '10.9.1.0/29' };
let model = (addrs) => {
let mm = { servers: { main: srv, other }, people: { a: { server: 'main' }, o: { server: 'other' } }, devices: {} };
for (let i, a in addrs)
mm.devices[`d${i}`] = { person: 'a', address: a };
return mm;
};
eq(core.alloc_address(model([]), srv), '10.9.0.2', 'router has the first host');
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.3' ]), srv), '10.9.0.4', 'next free');
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.4' ]), srv), '10.9.0.3', 'lowest gap');
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.3', '10.9.0.4', '10.9.0.5', '10.9.0.6' ]), srv), null, 'exhausted (.7 is broadcast)');
eq(core.alloc_address(model([ '10.9.0.2', 'garbage' ]), srv), '10.9.0.3', 'a broken address is ignored');
let mm = model([]);
mm.devices.x = { person: 'o', address: '10.9.0.2' };
eq(core.alloc_address(mm, srv), '10.9.0.2', 'another server\'s devices do not count');
eq(core.alloc_address(model([]), { id: 'main', subnet: 'nonsense' }), null, 'no subnet');
eq(core.server_address(srv), '10.9.0.1', 'server_address');
eq(core.tunnels({ ...srv, ifname: 'awgmain', private_key: 'k' }), [ { ifname: 'awgmain', subnet: '10.9.0.0/29', address: '10.9.0.1' } ], 'tunnels');
eq(core.tunnels({ ...srv, ifname: 'awgmain' }), [], 'no key, no tunnel');
eq(core.tunnels({ ...srv, ifname: 'awgmain', private_key: 'k', blocked: 'taken' }), [], 'blocked interface');
eq(core.tunnels({ ...srv, ifname: 'awg-main', private_key: 'k' }), [], 'bad interface name');
});
test('tunnel_mtu / device_mtu', () => {
eq(core.tunnel_mtu({ mtu: 1420 }), 1420, 'set by hand');
eq(core.tunnel_mtu({ mtu: 0, obf: {} }), 1380, 'automatic');
eq(core.tunnel_mtu({ mtu: 0 }), 1380, 'automatic without disguise');
eq(core.tunnel_mtu({ mtu: 0, obf: { s4: '12' } }), 1368, 'S4 taken off');
eq(core.tunnel_mtu({ mtu: 0, obf: { s4: '100' } }), 1280, 'never below 1280');
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone' }), 1280, 'phone');
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer' }), 1380, 'computer');
eq(core.device_mtu({ mtu: 1200 }, { kind: 'tablet' }), 1200, 'a smaller tunnel MTU stays');
});
test('names and codes', () => {
ok(core.valid_ifname('awgmain') && core.valid_ifname('a') && core.valid_ifname('awg_1'), 'interface names');
ok(!core.valid_ifname('Awg') && !core.valid_ifname('1awg') && !core.valid_ifname('awg-main') && !core.valid_ifname('awgmain123456'), 'bad interface names');
for (let i = 0; i < 20; i++)
ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code');
});
test('renumber_server', () => {
let srv = { id: 'main', name: 'Main', subnet: '10.9.0.0/29' };
let mm = {
servers: { main: srv, other: { id: 'other', subnet: '10.9.1.0/29' } },
people: { a: { server: 'main', devices: [ 'a1', 'a2' ] }, o: { server: 'other', devices: [ 'o1' ] } },
devices: { a1: { person: 'a', address: '10.9.0.5' }, a2: { person: 'a', address: '10.9.0.3' }, o1: { person: 'o', address: '10.9.1.2' } },
};
let set = {};
let c = { set: (cfg, s, k, v) => { set[`${s}.${k}`] = v; }, delete: () => {} };
core.renumber_server(c, mm, srv, '10.77.0.0/24');
eq(srv.subnet, '10.77.0.0/24', 'the server moves');
eq([ mm.devices.a1.address, mm.devices.a2.address ], [ '10.77.0.2', '10.77.0.3' ], 'devices renumbered lowest first');
eq(mm.devices.o1.address, '10.9.1.2', 'another server untouched');
eq(set, { 'a1.address': '10.77.0.2', 'a2.address': '10.77.0.3', 'main.subnet': '10.77.0.0/24' }, 'written to uci');
let err = null;
try { core.renumber_server(c, mm, srv, '10.9.2.0/30'); } catch (e) { err = e; }
ok(err != null, 'refuses a subnet too small for the devices');
});
test('device_labels', () => {
let mm = { devices: {
a: { id: 'a', name: 'iPhone', created: 1 }, b: { id: 'b', name: 'iPhone!', created: 2 },
c: { id: 'c', name: 'Телефон', created: 3 }, d: { id: 'd', name: 'телефон', created: 4 },
} };
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
});
+3
View File
@@ -0,0 +1,3 @@
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 1234567 2345678 3456789 4567890
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
awgmain TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= (none) (none) 10.9.0.3/32 0 0 0 off
+2
View File
@@ -0,0 +1,2 @@
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 12 12 1234567 2345678 3456789 4567890 <b 0xdead>
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
+3
View File
@@ -0,0 +1,3 @@
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 12 12 1234567 2345678 3456789 4567890 <r 2><b 0x858000010001> yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= 10-100 on on
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
awgmain TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= (none) (none) 10.9.0.3/32 0 0 0 off
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Stand-in for amneziawg-tools in the ucode tests (no kernel module in a
# container): `genkey` prints one fixed key, `show all dump` prints the fixture
# a test has put at /tmp/dawnline-tests/awg-dump (or fails, as the tool does
# when no interface is up). Anything else fails.
case "$1 ${2:-} ${3:-}" in
'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;;
'show all dump') cat /tmp/dawnline-tests/awg-dump ;;
*) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;;
esac
+43
View File
@@ -0,0 +1,43 @@
# Test fixture: a small installation (one server, two people, one device).
# migrate.test.uc expects bob's random code, the server's stored MTU 1380 and
# uhttpd's error_page: the one-time steps remove them.
config settings 'settings'
option portal_enabled '1'
option portal_port '8443'
option portal_host 'vpn.example.com'
option log_connections '0'
option update_interval '7d'
list update_targets 'app'
config server 'main'
option name 'Main'
option ifname 'awgmain'
option port '51820'
option subnet '10.9.0.0/29'
option private_key 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
option mtu '1380'
option jc '4'
option jmin '64'
option jmax '128'
option s4 '12'
config person 'alice'
option server 'main'
option name 'Alice'
option code 'abcdef-ghijkl-mnopqr'
option access 'both'
config person 'bob'
option server 'main'
option name 'Bob'
option code 'XyZ12345'
option quota_gb '2'
config device 'alice_phone'
option person 'alice'
option name 'Phone'
option kind 'phone'
option address '10.9.0.2'
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
+8
View File
@@ -0,0 +1,8 @@
# Test fixture: LuCI's web server as versions before 0.4 left it, with the
# portal as its error page (migrate.uhttpd removes that).
config uhttpd 'main'
list listen_http '0.0.0.0:80'
list listen_https '0.0.0.0:443'
option home '/www'
option error_page '/cgi-bin/dawnline-portal'
+50
View File
@@ -0,0 +1,50 @@
// dawnline.live: event categories and the retention policy, from a settings
// object and from the fixture config (real libuci).
import * as live from 'dawnline.live';
test('category_of', () => {
eq(live.category_of('connect'), 'connections', 'connect');
eq(live.category_of('roam'), 'connections', 'roam');
eq(live.category_of('device_added'), 'people', 'device events are people events');
eq(live.category_of('person_changed'), 'people', 'person');
eq(live.category_of('server_down'), 'problems', 'server');
eq(live.category_of('something_new'), 'problems', 'unknown types are problems');
});
test('policy defaults', () => {
eq(live.policy({}), { keep_days: 30, max: 2000, categories: [ 'connections', 'people', 'problems' ],
persist: 'hourly', usage_days: 62, usage_months: 24 }, 'empty settings');
});
test('policy categories', () => {
eq(live.policy({ log_connections: '0' }).categories, [ 'people', 'problems' ], 'old switch');
eq(live.policy({ log_category: 'devices, problems' }).categories, [ 'people', 'problems' ], 'string list, devices renamed');
eq(live.policy({ log_category: [ 'connections', 'bogus', 'connections' ] }).categories, [ 'connections' ], 'list, unknown and repeats dropped');
eq(live.policy({ log_category: [], log_connections: '0' }).categories, [], 'explicit empty list wins');
});
// Ranges come from dawnline.schema: a stored value outside them (an older
// version, a hand edit) reads as the default, as settings_update would have refused it.
test('policy ranges', () => {
eq(live.policy({ log_max: '50' }).max, 2000, 'max below the floor: default');
eq(live.policy({ log_max: '99999' }).max, 2000, 'max above the ceiling: default');
eq(live.policy({ log_max: '150' }).max, 150, 'max in range');
eq(live.policy({ log_max: 'abc' }).max, 2000, 'bad max');
eq(live.policy({ log_keep_days: '0' }).keep_days, 0, 'keep forever');
eq(live.policy({ log_keep_days: '-3' }).keep_days, 30, 'negative days');
eq(live.policy({ log_persist: '10min' }).persist, '10min', 'persist');
eq(live.policy({ log_persist: 'daily' }).persist, 'hourly', 'bad persist');
eq(live.policy({ usage_keep_days: '1' }).usage_days, 62, 'usage days below the floor: default');
eq(live.policy({ usage_keep_months: '500' }).usage_months, 24, 'usage months above the ceiling: default');
});
test('policy from the config', () => {
eq(live.policy(null).categories, [ 'people', 'problems' ], 'fixture turns connections off');
eq(live.policy(null).max, 2000, 'default where the fixture says nothing');
});
test('endpoint_ip', () => {
eq(live.endpoint_ip('203.0.113.7:41821'), '203.0.113.7', 'v4');
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
eq(live.endpoint_ip(''), '', 'none');
});
+44
View File
@@ -0,0 +1,44 @@
// dawnline.migrate: the one-time steps on the fixture config (real libuci):
// each changes what it must the first time and nothing the second time.
// This test rewrites /etc/config/dawnline and /etc/config/uhttpd.
import { cursor } from 'uci';
import { stat } from 'fs';
import * as core from 'dawnline.core';
import * as migrate from 'dawnline.migrate';
function conf(name) {
let c = cursor();
c.load(name);
return c;
}
test('before: the fixture holds the old state', () => {
let c = conf('dawnline');
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
});
test('run: the steps change what they must', () => {
migrate.run();
let c = conf('dawnline');
ok(match(c.get('dawnline', 'bob', 'code'), core.WORD_CODE), 'bob has a word code');
eq(c.get('dawnline', 'alice', 'code'), 'abcdef-ghijkl-mnopqr', 'alice keeps hers');
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
user_read: true, user_write: true, user_exec: false,
group_read: false, group_write: false, group_exec: false,
other_read: false, other_write: false, other_exec: false }, 'config stays private');
});
test('run again: a step runs once', () => {
let before = conf('dawnline').get('dawnline', 'bob', 'code');
let mtime = stat('/etc/config/dawnline').mtime;
migrate.run();
eq(conf('dawnline').get('dawnline', 'bob', 'code'), before, 'the code is not drawn again');
eq(stat('/etc/config/dawnline').mtime, mtime, 'nothing written');
});
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
# Run the ucode unit tests against the real libuci: the fixture configs are
# copied into /etc/config (replacing what is there), the stand-in `awg` goes on
# PATH and tests/ucode/run.uc runs every *.test.uc. For a throw-away OpenWrt
# rootfs container (scripts/ucode-container.sh); on anything else it refuses
# unless DAWNLINE_TEST_FORCE=1, because it overwrites /etc/config/dawnline.
# tests/ucode/run.sh [REPO] [test name filter]
set -eu
REPO="$(cd "${1:-$(dirname "$0")/../..}" && pwd)"
T="$REPO/tests/ucode"
if [ ! -e /.dockerenv ] && [ "${DAWNLINE_TEST_FORCE:-}" != 1 ]; then
echo "run.sh replaces /etc/config/dawnline and /etc/config/uhttpd: run it in a container (scripts/ucode-container.sh)" >&2
exit 2
fi
cp "$T"/fixtures/config/* /etc/config/
mkdir -p /tmp/dawnline-tests /var/run/dawnline
PATH="$T/fixtures/bin:$PATH" ucode -L "$REPO/package/luci-app-dawnline/root/usr/share/ucode/*.uc" "$T/run.uc" "${2:-}"
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/ucode
'use strict';
// Dawnline ucode unit tests. Runs every *.test.uc beside this file (in name
// order; migrate.test.uc changes /etc/config/dawnline, so it sorts after the
// tests that read the fixture as it is) with four helpers in scope:
// test(name, fn) one case; a thrown error or die() fails it
// eq(got, want, note) deep equality (JSON form), note names the case
// ok(cond, note) a true value
// throws(fn, re, note) fn must throw; the message must match re when given
// tests/ucode/run.sh prepares the fixtures and starts this with the modules
// on -L; an optional argument runs only the files whose name contains it.
import { lsdir } from 'fs';
let dir = sourcepath(0, true);
let passed = 0, failed = 0, file = null;
function eq(got, want, note) {
let g = sprintf('%J', got), w = sprintf('%J', want);
if (g != w)
die(`${note ? note + ': ' : ''}got ${g}, want ${w}`);
}
function ok(cond, note) {
if (!cond)
die(note ?? 'expected a true value');
}
function throws(fn, re, note) {
let msg = null;
try {
fn();
}
catch (e) {
msg = e.message ?? `${e}`;
}
if (msg == null)
die(`${note ?? 'call'} did not throw`);
if (re && !match(msg, re))
die(`${note ?? 'call'} threw "${msg}", not ${re}`);
return msg;
}
function test(name, fn) {
try {
fn();
passed++;
}
catch (e) {
failed++;
// The first frame in the test file itself (not eq()/ok() in here).
let at = filter(e.stacktrace ?? [], (f) => f.filename && index(f.filename, '/run.uc') < 0)[0];
printf('FAIL %s: %s\n %s%s\n', file, name, e.message ?? `${e}`, at ? ` (${at.filename}:${at.line})` : '');
}
}
for (file in sort(lsdir(dir) ?? [])) {
if (!match(file, /\.test\.uc$/) || (ARGV[0] && index(file, ARGV[0]) < 0))
continue;
try {
include(`${dir}/${file}`, { test, eq, ok, throws });
}
catch (e) {
failed++;
printf('FAIL %s: could not run\n %s\n', file, e.message ?? `${e}`);
}
}
printf('%d passed, %d failed\n', passed, failed);
exit(failed ? 1 : 0);
+146
View File
@@ -0,0 +1,146 @@
// dawnline.schema: what the admin may save (validate) and how stored values
// are read (get), one case per settings type.
import * as schema from 'dawnline.schema';
test('validate: bool', () => {
eq(schema.validate('portal_enabled', true), '1', 'true');
eq(schema.validate('portal_enabled', false), '0', 'false');
eq(schema.validate('portal_enabled', '1'), '1', 'string 1');
eq(schema.validate('portal_enabled', ''), null, 'empty removes the option');
throws(() => schema.validate('portal_enabled', 'yes'), /0 or 1/, 'yes');
});
test('validate: int', () => {
eq(schema.validate('portal_port', '8443'), '8443', 'in range');
eq(schema.validate('portal_port', ' 443 '), '443', 'trimmed');
eq(schema.validate('portal_port', '08443'), '8443', 'leading zero dropped');
eq(schema.validate('portal_port', 9000), '9000', 'number');
throws(() => schema.validate('portal_port', '0'), /free port/, 'below min');
throws(() => schema.validate('portal_port', '70000'), /free port/, 'above max');
throws(() => schema.validate('portal_port', 'abc'), /free port/, 'letters');
throws(() => schema.validate('portal_port', '-1'), /free port/, 'negative');
throws(() => schema.validate('default_device_limit', '33'), /1-32/, 'device limit');
eq(schema.validate('log_keep_days', '0'), '0', 'zero allowed where min is 0');
});
test('validate: enum', () => {
eq(schema.validate('geo_provider', 'ipapi.co'), 'ipapi.co', 'known');
throws(() => schema.validate('geo_provider', 'maxmind'), /Unknown location service/, 'unknown');
eq(schema.validate('update_interval', '7d'), '7d', 'interval from dawnline.updates');
throws(() => schema.validate('update_interval', '2d'), /6h, 12h, 1d or 7d/, 'unknown interval');
});
test('validate: host and hosts', () => {
eq(schema.validate('portal_host', 'vpn.example.com'), 'vpn.example.com', 'name');
eq(schema.validate('portal_host', '203.0.113.7'), '203.0.113.7', 'address');
throws(() => schema.validate('portal_host', 'bad host!'), /hostname or IP/, 'bad');
eq(schema.validate('portal_alt', [ 'a.example.com', ' a.example.com ', '', 'b.example.com' ]),
[ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, empty ones dropped');
throws(() => schema.validate('portal_alt', [ 'a.example.com', 'bad host' ]), /hostnames or IP/, 'a typo is refused, not dropped');
eq(schema.validate('portal_alt', []), null, 'empty list removes the option');
eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list');
});
test('validate: url', () => {
eq(schema.validate('portal_redirect', 'https://example.com/x?y=1'), 'https://example.com/x?y=1', 'https with path');
eq(schema.validate('portal_redirect', 'http://example.com:8080'), 'http://example.com:8080', 'http with port');
throws(() => schema.validate('portal_redirect', 'ftp://example.com'), /full http/, 'scheme');
throws(() => schema.validate('portal_redirect', 'https://example.com/<x>'), /full http/, 'angle brackets');
throws(() => schema.validate('portal_redirect', 'https://example.com/' + replace(sprintf('%300s', ''), ' ', 'a')), /full http/, 'over 300 characters');
});
test('validate: file', () => {
eq(schema.validate('portal_cert', '/etc/passwd'), '/etc/passwd', 'existing file');
throws(() => schema.validate('portal_cert', '/nonexistent/cert.pem'), /does not exist/, 'missing');
throws(() => schema.validate('portal_cert', 'cert.pem'), /does not exist/, 'relative');
});
test('validate: domain', () => {
eq(schema.validate('domain', 'lan'), 'lan', 'single');
eq(schema.validate('domain', 'home.arpa'), 'home.arpa', 'dotted');
throws(() => schema.validate('domain', 'Lan'), /lowercase/, 'upper case');
throws(() => schema.validate('domain', replace(sprintf('%33s', ''), ' ', 'a')), /lowercase/, '33-char label');
});
test('validate: ipv4', () => {
eq(schema.validate('home_dns_fallback', '9.9.9.9'), '9.9.9.9', 'address');
eq(schema.validate('home_dns_fallback', ''), 'none', 'empty means no fallback');
throws(() => schema.validate('home_dns_fallback', '999.1.1.1'), /IPv4/, 'bad octet');
throws(() => schema.validate('home_dns_fallback', 'dns.example'), /IPv4/, 'name');
});
test('validate: time', () => {
eq(schema.validate('update_time', '04:00'), '04:00', 'padded');
eq(schema.validate('update_time', '4:00'), '4:00', 'unpadded');
eq(schema.validate('update_time', '23:59'), '23:59', 'last minute');
throws(() => schema.validate('update_time', '24:00'), /HH:MM/, 'hour 24');
throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60');
});
test('validate: text', () => {
eq(schema.validate('portal_title', 'My VPN'), 'My VPN', 'plain');
eq(schema.validate('portal_title', replace(sprintf('%64s', ''), ' ', 'a')), replace(sprintf('%64s', ''), ' ', 'a'), '64 characters');
throws(() => schema.validate('portal_title', replace(sprintf('%65s', ''), ' ', 'a')), /64 characters/, '65 characters');
throws(() => schema.validate('portal_title', 'a\nb'), /64 characters/, 'control character');
});
test('validate: targets', () => {
eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once');
eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice');
eq(schema.validate('update_targets', 'app'), [ 'none' ], 'not a list');
});
test('validate: unknown key', () => {
throws(() => schema.validate('nonsense', '1'), /Unknown setting/);
});
test('get', () => {
eq(schema.get({ portal_enabled: 'on' }, 'portal_enabled'), true, 'bool synonyms');
eq(schema.get({ portal_enabled: 'maybe' }, 'portal_enabled'), false, 'bad bool is the default');
eq(schema.get({}, 'portal_enabled'), false, 'missing bool');
eq(schema.get({ portal_port: '443' }, 'portal_port'), 443, 'int');
eq(schema.get({ portal_port: '99999' }, 'portal_port'), 8443, 'int out of range is the default');
eq(schema.get({ portal_port: 'x' }, 'portal_port'), 8443, 'bad int');
eq(schema.get({}, 'portal_alt'), [], 'missing list');
eq(schema.get({ portal_alt: 'a.example.com' }, 'portal_alt'), [ 'a.example.com' ], 'single value as list');
eq(schema.get({ portal_alt: [ 'a', '' ] }, 'portal_alt'), [ 'a' ], 'empty entries dropped');
eq(schema.get({}, 'update_targets'), [ 'app', 'packages' ], 'default targets');
eq(schema.get({ geo_provider: 'ipapi.co' }, 'geo_provider'), 'ipapi.co', 'enum');
eq(schema.get({ geo_provider: 'x' }, 'geo_provider'), 'ipwho.is', 'bad enum is the default');
eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty');
eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4');
eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4');
eq(schema.get({}, 'portal_title'), 'Dawnline', 'missing text');
eq(schema.get({ portal_title: '' }, 'portal_title'), 'Dawnline', 'empty text');
eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through');
eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value');
eq(schema.get(null, 'portal_port'), 8443, 'no section');
});
test('parsing helpers', () => {
eq(schema.bool('TRUE', false), true, 'case-insensitive');
eq(schema.bool(' 0 ', true), false, 'trimmed');
eq(schema.bool(null, true), true, 'default');
eq(schema.to_int('-5', 0, 0, 10), 0, 'below min');
eq(schema.to_int('7', 0, 0, 10), 7, 'in range');
eq(schema.to_int('7.5', 0), 0, 'not whole');
ok(schema.valid_port('65535'), 'max port');
ok(!schema.valid_port('0'), 'port 0');
ok(!schema.valid_port('65536'), 'port 65536');
ok(!schema.valid_port('12a'), 'letters');
ok(!schema.valid_port(null), 'null');
});
test('addresses', () => {
ok(schema.ipv4('10.0.0.1') && !schema.ipv4('10.0.0.256') && !schema.ipv4(null), 'ipv4');
eq(schema.ipv6_groups('::1'), [ 0, 0, 0, 0, 0, 0, 0, 1 ], 'loopback');
eq(schema.ipv6_groups('2001:db8::1'), [ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1 ], 'compressed');
eq(schema.ipv6_groups('::ffff:192.0.2.1'), [ 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x0201 ], 'embedded IPv4');
eq(schema.ipv6_groups('1:2:3:4:5:6:7:8'), [ 1, 2, 3, 4, 5, 6, 7, 8 ], 'full');
eq(schema.ipv6_groups('1:2:3:4:5:6:7:8:9'), null, 'nine groups');
eq(schema.ipv6_groups('1:2:3:4:5:6:7'), null, 'seven groups, no gap');
eq(schema.ipv6_groups('1::2::3'), null, 'two gaps');
eq(schema.ipv6_groups('fe80::1%eth0'), null, 'zone id');
eq(schema.ipv6_groups('12345::'), null, 'group too long');
ok(schema.ip('10.0.0.1') && schema.ip('fe80::1') && !schema.ip('nope'), 'ip');
});
+54
View File
@@ -0,0 +1,54 @@
// dawnline.updates: the update policy from raw settings, what is due at a
// given time, and release version ordering.
import * as updates from 'dawnline.updates';
function at(y, mo, d, h, mi) {
return timelocal({ year: y, mon: mo, mday: d, hour: h, min: mi, sec: 0 });
}
test('policy defaults', () => {
eq(updates.policy(null), { check: true, interval: '1d', auto: true, mode: 'scheduled', time: '04:00',
targets: [ 'app', 'packages' ], keep: false, mirrors: true }, 'no settings');
eq(updates.policy({}), updates.policy(null), 'empty settings');
});
test('policy values', () => {
let p = updates.policy({ update_check: '0', update_interval: '7d', update_auto: 'no', update_mode: 'immediate',
update_time: '23:59', update_targets: 'amneziawg', update_keep: '1', update_mirrors: 'off' });
eq(p, { check: false, interval: '7d', auto: false, mode: 'immediate', time: '23:59', targets: [ 'amneziawg' ], keep: true, mirrors: false }, 'all set');
eq(updates.policy({ update_interval: '2d' }).interval, '1d', 'unknown interval');
eq(updates.policy({ update_time: '24:00' }).time, '04:00', 'bad time');
eq(updates.policy({ update_time: '4:30' }).time, '4:30', 'unpadded time');
eq(updates.policy({ update_mode: 'later' }).mode, 'scheduled', 'unknown mode');
eq(updates.policy({ update_targets: [ 'packages', 'bogus', 'app' ] }).targets, [ 'packages', 'app' ], 'unknown targets dropped');
eq(updates.policy({ update_targets: [ 'none' ] }).targets, [], '"none" is no target');
eq(updates.policy({ update_targets: [] }).targets, [], 'empty list');
});
test('due', () => {
let pol = updates.policy({ update_time: '04:00' });
let t = at(2026, 3, 10, 4, 30);
eq(updates.due(pol, {}, t), 'install', 'in the window, never run');
eq(updates.due(pol, { install_day: '2026-03-10' }, t), 'check', 'window spent, check is due');
eq(updates.due(pol, { install_day: '2026-03-10', check: t - 3600 }, t), null, 'checked an hour ago');
eq(updates.due(pol, { check: t - 90000 }, at(2026, 3, 10, 12, 0)), 'check', 'outside the window, a day has passed');
eq(updates.due(pol, {}, at(2026, 3, 10, 5, 30)), 'check', 'window over (an hour)');
eq(updates.due(updates.policy({ update_auto: '0', update_check: '0' }), {}, t), null, 'everything off');
eq(updates.due(updates.policy({ update_mode: 'immediate' }), {}, t), 'check', 'immediate mode has no window');
eq(updates.due(updates.policy({ update_targets: [] }), {}, t), 'check', 'nothing to install');
let late = updates.policy({ update_time: '23:30' });
eq(updates.due(late, {}, at(2026, 3, 11, 0, 15)), 'install', 'window across midnight');
eq(updates.mark_day(late, {}, at(2026, 3, 11, 0, 15)).install_day, '2026-03-10', 'mark_day records the slot\'s day');
});
test('version_cmp', () => {
eq(updates.version_cmp('0.5.1', '0.5.1'), 0, 'equal');
eq(updates.version_cmp('v0.5.1', '0.5.1'), 0, 'v prefix');
eq(updates.version_cmp('0.5.1', '0.5.2'), -1, 'patch');
eq(updates.version_cmp('0.10.0', '0.9.9'), 1, 'numbers, not strings');
eq(updates.version_cmp('0.6', '0.6.0'), 0, 'missing part is zero');
eq(updates.version_cmp('0.6.0-rc1', '0.6.0'), -1, 'pre-release before the release');
eq(updates.version_cmp('0.6.0-rc2', '0.6.0-rc10'), -1, 'rc numbers as numbers');
eq(updates.version_cmp('0.6.0-beta', '0.6.0-rc1'), -1, 'beta before rc');
eq(updates.version_cmp('garbage', '0.1'), -1, 'unparsable is lowest');
});
+132
View File
@@ -0,0 +1,132 @@
// dawnline.util: validation, addresses, slugs and dates (pure functions).
import * as util from 'dawnline.util';
test('valid_name', () => {
ok(util.valid_name('Alice'), 'plain');
ok(util.valid_name('Мама'), 'non-ASCII letters');
ok(!util.valid_name(''), 'empty');
ok(!util.valid_name(' '), 'blank');
ok(!util.valid_name(null), 'null');
ok(!util.valid_name(42), 'number');
ok(util.valid_name('a' + replace(sprintf('%47s', ''), ' ', 'b')), '48 characters');
ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 characters');
ok(util.valid_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧ'), '25 Cyrillic letters (50 bytes) are 25 characters');
ok(!util.valid_name('Bob "B"'), 'quotes');
ok(!util.valid_name('a<b'), 'angle bracket');
ok(!util.valid_name('a"b'), 'quote');
ok(!util.valid_name('a\\b'), 'backslash');
ok(!util.valid_name('a\tb'), 'control character');
});
test('valid_host', () => {
ok(util.valid_host('vpn.example.com'), 'name');
ok(util.valid_host('router'), 'single label');
ok(util.valid_host('203.0.113.7'), 'IPv4');
ok(util.valid_host('2001:db8::1'), 'IPv6');
ok(!util.valid_host('-a.example.com'), 'leading dash');
ok(!util.valid_host('a..example.com'), 'empty label');
ok(!util.valid_host('bad host'), 'space');
ok(!util.valid_host(''), 'empty');
ok(!util.valid_host(null), 'null');
let label = replace(sprintf('%63s', ''), ' ', 'a');
ok(util.valid_host(`${label}.example`), '63-char label');
ok(!util.valid_host(`${label}a.example`), '64-char label');
ok(!util.valid_host(join('.', [ label, label, label, label, 'x' ])), 'over 253 characters');
});
test('valid_date', () => {
ok(util.valid_date('2026-01-31'), 'ISO day');
ok(!util.valid_date('2026-1-31'), 'no padding');
ok(!util.valid_date('20260131'), 'no dashes');
ok(!util.valid_date('2026-01-31T00:00'), 'trailing time');
ok(!util.valid_date(20260131), 'not a string');
});
test('valid_slug and valid_key', () => {
ok(util.valid_slug('alice'), 'word');
ok(util.valid_slug('a'), 'one character');
ok(util.valid_slug('alice-2'), 'dash inside');
ok(!util.valid_slug('-alice'), 'leading dash');
ok(!util.valid_slug('Alice'), 'upper case');
ok(!util.valid_slug(replace(sprintf('%33s', ''), ' ', 'a')), '33 characters');
ok(util.valid_key('yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='), 'WireGuard key');
ok(!util.valid_key('yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk'), 'no padding');
ok(!util.valid_key('yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmb='), 'impossible last sextet');
ok(!util.valid_key(''), 'empty');
});
test('ip2int / int2ip / cidr_any', () => {
eq(util.ip2int('10.9.0.1'), 168361985, 'ip2int');
eq(util.int2ip(168361985), '10.9.0.1', 'int2ip');
eq(util.ip2int('256.0.0.1'), null, 'octet over 255');
eq(util.ip2int('1.2.3'), null, 'three octets');
eq(util.cidr_any('10.0.0.5'), { net: util.ip2int('10.0.0.5'), prefix: 32, size: 1, ip: util.ip2int('10.0.0.5') }, 'bare address is a /32');
eq(util.cidr_any('10.0.0.5/8'), { net: util.ip2int('10.0.0.0'), prefix: 8, size: 16777216, ip: util.ip2int('10.0.0.5') }, 'masked base');
eq(util.cidr_any('10.0.0.0/33'), null, 'prefix over 32');
eq(util.cidr_any(null), null, 'null');
eq(util.in_nets('10.9.0.7', [ '192.168.0.0/16', '10.9.0.0/29' ]), '10.9.0.0/29', 'first match');
eq(util.in_nets('10.9.0.8', [ '10.9.0.0/29' ]), null, 'just outside');
eq(util.in_nets('nonsense', [ '10.9.0.0/29' ]), null, 'not an address');
});
test('parse_cidr', () => {
let c = util.parse_cidr('10.9.0.0/24');
eq([ util.int2ip(c.net), c.prefix, c.size, util.int2ip(c.first), util.int2ip(c.last) ], [ '10.9.0.0', 24, 256, '10.9.0.1', '10.9.0.254' ], '/24');
eq(util.int2ip(util.parse_cidr('10.9.0.77/24').net), '10.9.0.0', 'host bits masked off');
eq(util.cidr_str(util.parse_cidr('10.9.0.77/24')), '10.9.0.0/24', 'cidr_str');
eq(util.parse_cidr('10.9.0.0/7'), null, 'too wide');
eq(util.parse_cidr('10.9.0.0/31'), null, 'too narrow');
eq(util.parse_cidr('10.9.0.0'), null, 'no prefix');
eq(util.parse_cidr('300.0.0.0/24'), null, 'bad octet');
eq(util.parse_cidr(null), null, 'null');
ok(util.cidr_overlaps(util.parse_cidr('10.9.0.0/24'), util.parse_cidr('10.9.0.128/25')), 'overlap');
ok(!util.cidr_overlaps(util.parse_cidr('10.9.0.0/24'), util.parse_cidr('10.9.1.0/24')), 'adjacent');
ok(util.in_cidr('10.9.0.200', util.parse_cidr('10.9.0.0/24')), 'in_cidr');
ok(!util.in_cidr('10.9.1.1', util.parse_cidr('10.9.0.0/24')), 'not in_cidr');
});
test('cloudflare_ip', () => {
ok(util.cloudflare_ip('104.16.1.1'), 'v4 range');
ok(util.cloudflare_ip('2606:4700::1'), 'v6 range');
ok(!util.cloudflare_ip('8.8.8.8'), 'other v4');
ok(!util.cloudflare_ip('2001:db8::1'), 'other v6');
ok(!util.cloudflare_ip(null), 'null');
});
test('slugify', () => {
eq(util.slugify('Alice Smith'), 'alice-smith', 'spaces to dashes');
eq(util.slugify(' --Bob!! '), 'bob', 'trimmed dashes');
eq(util.slugify(''), 'user', 'empty');
eq(util.slugify(null), 'user', 'null');
eq(util.slugify('Мама'), 'mama', 'Cyrillic written in Latin');
eq(util.slugify('Юля Щукина'), 'yulya-shchukina', 'Cyrillic words');
eq(util.slugify('日本'), 'user', 'nothing left');
eq(length(util.slugify(replace(sprintf('%40s', ''), ' ', 'x'))), 32, 'cut at 32');
});
test('dates', () => {
let end = util.date_end('2026-02-28');
let t = localtime(end);
eq([ t.year, t.mon, t.mday, t.hour, t.min, t.sec ], [ 2026, 2, 28, 23, 59, 59 ], 'end of the local day');
eq(util.date_end('2026-2-28'), null, 'bad date');
let noon = timelocal({ year: 2026, mon: 3, mday: 1, hour: 12, min: 0, sec: 0 });
eq(util.day_key(noon), '2026-03-01', 'day_key');
eq(util.month_key(noon), '2026-03', 'month_key');
eq(util.day_key_ago(1, noon), '2026-02-28', 'day_key_ago crosses the month');
eq(util.day_key_ago(0, noon), '2026-03-01', 'zero days');
eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq');
});
test('text: ulength, ucut, translit, host_label', () => {
eq(util.ulength('Мама'), 4, 'characters, not bytes');
eq(util.ulength('abc'), 3, 'ascii');
eq(util.ucut('Привет', 3), 'При', 'cut by characters');
eq(util.ucut('ab', 5), 'ab', 'shorter than the cut');
eq(util.translit('Мама Таня'), 'mama tanya', 'Russian');
eq(util.translit('Їжак Ґава ёж'), 'yizhak gava yozh', 'Ukrainian letters and ё');
eq(util.translit('Mixed Текст 1'), 'Mixed tekst 1', 'Latin and digits pass');
eq(util.host_label('Galaxy S24'), 'galaxy-s24', 'label');
eq(util.host_label('Телефон Ёжика'), 'telefon-yozhika', 'Cyrillic label');
eq(util.host_label('!!!'), 'device', 'nothing left');
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
});
+4
View File
@@ -452,6 +452,10 @@ do_backup() {
do_teardown() {
step "Running Dawnline's own removal"
if ubus list luci.dawnline >/dev/null 2>&1; then
# The removal takes the update lock itself: hand it over (the service is
# stopped first, so no automatic update can slip in between).
[ "$DRY_RUN" -eq 1 ] || /etc/init.d/dawnline stop >/dev/null 2>&1
exec 8>&- 2>/dev/null
# The same call as Settings → Remove Dawnline from this router.
if act "call luci.dawnline uninstall (Settings → Remove Dawnline)" rpc \
ubus -t 120 call luci.dawnline uninstall '{"confirm":"remove"}'; then
+20 -2
View File
@@ -1,17 +1,18 @@
{
"name": "dawnline-web",
"version": "0.5.1",
"version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.5.1",
"version": "0.8.0",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
},
"devDependencies": {
"@types/node": "22.20.5",
"prettier": "3.6.2",
"tsup": "8.5.0",
"typescript": "5.9.3",
@@ -933,6 +934,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@vitest/expect": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz",
@@ -1973,6 +1984,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/vite": {
"version": "7.3.7",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz",
+3 -2
View File
@@ -1,13 +1,13 @@
{
"name": "dawnline-web",
"version": "0.5.1",
"version": "0.8.0",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"build": "tsc --noEmit && tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
"test": "vitest run",
"format": "prettier --write .",
"format:check": "prettier --check .",
@@ -17,6 +17,7 @@
"qrcode-generator": "1.4.4"
},
"devDependencies": {
"@types/node": "22.20.5",
"prettier": "3.6.2",
"tsup": "8.5.0",
"typescript": "5.9.3",
+20 -5
View File
@@ -6,8 +6,10 @@ import { E } from './e';
import { api, type HomeHost } from './api';
import { button } from './ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
import { attempt } from './ui/toast';
import { attempt, notify } from './ui/toast';
import { chipToggle, input } from './ui/controls';
import { firstBad, liveField } from './ui/layout';
import { circleNameHelp, ipv4Help, nameHelp, portsHelp } from './netcheck';
import { icon } from '../shared/icons';
type Service = Status['services'][number];
@@ -30,17 +32,23 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
placeholder: 'All ports, or e.g. 445, 5000',
class: 'cbi-input-text dl-mono',
});
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown to people who may reach it.'));
const addrRow = liveField('Address', addr, () => ipv4Help(addr.value));
const portsRow = liveField('Ports', ports, () => portsHelp(ports.value));
modal(
sv ? `Edit ${sv.name}` : 'Add service',
[field('Name', name), field('Address', addr), field('Ports', ports)],
[nameRow, addrRow, portsRow],
[
cancelButton(),
' ',
button(
'Save',
async () => {
const bad = firstBad([nameRow, addrRow, portsRow]);
if (bad) {
notify(bad, 'warning');
return;
}
const list = ports.value.split(/[ ,]+/).filter(Boolean);
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
closeModal();
@@ -316,11 +324,13 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
);
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
const others = st.circles.filter((c) => c.server === serverId && c.id !== ci?.id).map((c) => c.name);
const nameRow = liveField('Name', name, () => circleNameHelp(name.value, others));
modal(
ci ? `Edit ${ci.name}` : 'New circle',
[
field('Name', name),
nameRow,
field('Colour', swatches),
field('People', chips),
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
@@ -344,6 +354,11 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
button(
'Save',
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
closeModal();
onDone();
+46 -14
View File
@@ -1,15 +1,23 @@
// luci.dawnline RPC bindings. The backend reports failures as { error }.
// luci.dawnline RPC bindings. The backend reports failures as { error }, and
// a change the router saved but could not fully put into effect (access rules
// that did not load, a server that refused its devices) as { warning }.
import type { Network, PortHold } from './netcheck';
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
import { notify } from './ui/toast';
/** Throw a backend failure; show a warning the answer carries. */
function settle<T>(r: any): T {
if (r && typeof r === 'object') {
if (typeof r.error === 'string') throw new Error(r.error);
if (typeof r.warning === 'string' && r.warning) notify(r.warning, 'warning', 12000);
}
return r as T;
}
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;
};
return async (...args: unknown[]): Promise<T> => settle<T>(await fn(...args));
}
export interface SetupDefaults {
@@ -31,6 +39,24 @@ export interface SetupDefaults {
tcp_taken: PortHold[];
awg: AwgCaps;
awg_state?: AwgState;
/** Where the suggested address came from: ddns, cert, wan, portal ('' = nothing found). */
endpoint_from?: string;
/** What the WAN's IPv4 is: public, private (behind another router), cgnat, none. */
wan_kind?: 'public' | 'private' | 'cgnat' | 'none';
wan_ip?: string | null;
}
/** Where a public address points (rpc endpoint_probe): the facts and their verdict in words. */
export interface EndpointProbe {
host: string;
ips: string[];
wan: string | null;
kind: 'public' | 'private' | 'cgnat' | 'none';
cloudflare: boolean;
here: boolean;
v6_only: boolean;
status: 'ok' | 'warn' | 'error';
text: string;
}
export interface Backup {
@@ -315,7 +341,8 @@ export type PersonPatch = Partial<
| 'bonus_gb'
| 'hours'
| 'note'
| 'dns_mode',
| 'dns_mode'
| 'server',
string
>
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
@@ -341,6 +368,7 @@ const personUpdateRaw = rpc.declare<any>({
'services',
'circle',
'home_nets',
'server',
],
});
@@ -359,10 +387,8 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
'note',
'dns_mode',
] as const;
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets];
const r = await personUpdateRaw(...args);
if (r && typeof r.error === 'string') throw new Error(r.error);
return r;
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets, patch.server];
return settle(await personUpdateRaw(...args));
}
const status = call<Status>('status', ['days']);
@@ -399,7 +425,7 @@ export interface ServiceLog {
export type Health = { checks: HealthCheck[] } & ServiceLog;
export const api = {
rev: call<{ rev: number }>('rev'),
rev: call<{ rev: number; version?: string }>('rev'),
personUpdate,
settingsGet: call<SettingsData>('settings_get'),
portalInfo: call<PortalInfo>('portal_info'),
@@ -407,7 +433,8 @@ export const api = {
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']),
/** The newest `limit` events; a person's only, or only those after `since` (a ts), when given. */
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit', 'person', 'since']),
logsClear,
interfaces: call<InterfacesData>('interfaces', ['id']),
serverInterfaces: call<InterfacesData>('server_interfaces', [
@@ -445,6 +472,10 @@ export const api = {
]),
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
serverUpdate: call<unknown>('server_update', ['id', 'values']),
/** What an existing server's ports and a new tunnel network must avoid (checked as you type). */
serverPorts: call<{ udp_taken: PortHold[]; tcp_taken: PortHold[]; networks?: Network[] }>('server_ports', ['id']),
/** Where a public address points, for the live help under the field (debounced by the caller). */
endpointProbe: call<EndpointProbe>('endpoint_probe', ['host', 'id', 'port']),
serverDelete: call<unknown>('server_delete', ['id']),
/** The personal link, its code and every address it works on (main first); not part of the status. */
personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']),
@@ -459,7 +490,8 @@ export const api = {
'quota_period',
]),
personPause: call<unknown>('person_pause', ['id', 'paused']),
personRegen: call<{ link: string | null }>('person_regen', ['id']),
/** A new link; `remove` lists devices (ids) to take away with the old one. */
personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']),
personDelete: call<unknown>('person_delete', ['id']),
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
+68 -17
View File
@@ -10,11 +10,12 @@ import { confirmDialog } from '../ui/modal';
import { copyText, downloadFile } from '../ui/files';
import { attempt, notify } from '../ui/toast';
import { input } from '../ui/controls';
import { callout, card, group, row, svg } from '../ui/layout';
import { callout, card, firstBad, group, liveRow, row, svg } from '../ui/layout';
import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck';
import { qrSvg } from '../../shared/qr';
import { vpnKey } from '../../shared/vpnkey';
import { icon } from '../../shared/icons';
import { methodInfo, methodPicker, type Method } from '../disguise';
import { methodInfo, methodPicker, type Method, defaultMethod, legacyTitle } from '../disguise';
import { coreHead, type Core, type CoreCtx } from './common';
/** `.conf` names of the disguise parameters, in file order. */
@@ -198,6 +199,13 @@ function fileCard(cfg: AwgConfig): HTMLElement {
]);
}
/** The configuration carries no disguise values: plain WireGuard, any WireGuard app takes it. */
export function plainWg(cfg: AwgConfig): boolean {
const o = (cfg.amnezia.obfuscation ?? {}) as Record<string, string | undefined>;
const neutral: Record<string, string> = { h1: '1', h2: '2', h3: '3', h4: '4' };
return Object.entries(o).every(([k, v]) => v == null || v === '' || v === (neutral[k] ?? '0'));
}
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
@@ -211,7 +219,11 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
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.'),
E(
'span',
{ class: 'dl-sub' },
plainWg(cfg) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
@@ -243,7 +255,7 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
const devices = people.reduce((n, p) => n + p.devices.length, 0);
const ok = await confirmDialog(
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
`${devices} AmneziaWG device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : ''}`,
`${devices} AmneziaWG device${devices === 1 ? ' stops' : 's stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : m === 'balanced' ? ' They need an app with AmneziaWG 2.0 or newer.' : ''}${ctx.st.servers.length === 1 && devices ? ' To keep the old disguise for some people, add a second server and move them there.' : ''}`,
same ? 'Generate and apply' : 'Switch and apply',
true,
);
@@ -263,30 +275,54 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
inputmode: 'numeric',
class: 'cbi-input-text dl-w-port dl-mono',
});
const now = `${srv.mtus.computer} for computers and routers, ${srv.mtus.phone} for phones and tablets`;
const mtuHint = srv.mtu
? `Now ${now}. Empty = automatic.`
: `Automatic by device type and disguise: now ${now}. Lower it if some sites hang.`;
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
let selected: Method = current ?? 'standard';
let selected: Method = current ?? defaultMethod(st.awg);
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
const label = () =>
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
label();
const tools = st.awg_state?.tools !== false;
// Who holds which port arrives once the card is built (netstat on the
// router); until then the port is only checked for its range.
let holds: PortHold[] = [];
const portRow = liveRow('UDP port', port, () =>
portHelp(
Number(port.value),
holds,
`Opened on the WAN firewall automatically.${Number(port.value) === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
),
);
api
.serverPorts(srv.id)
.then((r) => {
holds = r.udp_taken ?? [];
portRow.refresh();
})
.catch(() => {});
const mtuRow = liveRow('MTU', mtu, () => mtuHelp(mtu.value, srv.mtus));
const kaRow = liveRow('Keep-alive', ka, () => keepaliveHelp(ka.value));
return card(
'',
[
coreHead('AmneziaWG', srv.ifname),
group('globe', 'Listening', 'Where devices reach this core from the internet', [
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
]),
group('globe', 'Listening', 'Where devices reach this core from the internet', [portRow]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
row('MTU', mtu, mtuHint),
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
mtuRow,
kaRow,
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
// A server from before 0.8 on the old junk-only disguise: it runs, but is no longer offered.
legacyTitle(srv.preset)
? callout('warn', [
E('b', {}, legacyTitle(srv.preset)!),
' is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ',
E('b', {}, 'Balanced'),
' or ',
E('b', {}, 'Maximum'),
': devices import their configuration again.',
])
: '',
methodPicker(
st.awg,
selected,
@@ -331,7 +367,19 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
],
[
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
button('Save', () => ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved'), 'positive'),
button(
'Save',
() => {
// The help lines already say what is wrong: do not send it anyway.
const bad = firstBad([portRow, mtuRow, kaRow]);
if (bad) {
notify(bad, 'warning');
return;
}
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved');
},
'positive',
),
],
);
}
@@ -351,7 +399,7 @@ function overviewTile(srv: Server): HTMLElement {
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.i1) chips.push(/0x(8580|0100)0001/.test(o.i1) ? 'DNS-like first packets' : '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' }, [
@@ -361,7 +409,10 @@ function overviewTile(srv: Server): HTMLElement {
]),
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')]),
E('span', { class: 'dl-stack' }, [
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')),
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
]),
]),
m
? E('div', { class: 'dl-disg-meters' }, [
+46 -14
View File
@@ -11,7 +11,8 @@ import { copyText, downloadFile } from './ui/files';
import { dropdown, type MenuItem } from './ui/menu';
import { drawer } from './ui/drawer';
import { attempt, notify } from './ui/toast';
import { svg } from './ui/layout';
import { liveField, svg } from './ui/layout';
import { nameHelp } from './netcheck';
import { deviceStatus } from './ui/badges';
import { qrSvg } from '../shared/qr';
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
@@ -20,6 +21,7 @@ import { eventBy } from './events/model';
import { spark } from './widgets/spark';
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores';
import { plainWg } from './cores/awg';
import { onLiveChange } from './state/live';
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map';
import { personUrl } from './urls';
@@ -123,7 +125,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
let geo = o.geo;
let now = o.now;
let today = o.today ?? isoDay(new Date());
const connect = await core.connectBlock(cfg);
// Phones and tablets are set up by scanning; computers and routers by a file.
const connect = await core.connectBlock(cfg, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
@@ -137,7 +140,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const loadLog = async (force = false) => {
const own = o.events?.();
if (own && !force) return showLog(own);
const ev = await api.events(5000).catch(() => null);
const ev = await api.events(2000, person.id).catch(() => null);
if (ev) showLog(ev.events);
};
@@ -183,7 +186,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
E('div', { class: 'dl-dstats' }, [
E('div', { class: 'dl-dstats-cell wide' }, [
E('span', { class: 'dl-metric-label' }, 'Status'),
deviceStatus(d, now, 'Waiting for the first connection'),
deviceStatus(d, now, 'Waiting for the first connection', p),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'This month'),
@@ -221,10 +224,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
]),
),
row('Added', `${when(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)}…` : '—'),
),
// The whole key, copyable: it is what another WireGuard server needs to add this device by hand.
cfg.amnezia.client_pub_key ? copyRow('Public key', cfg.amnezia.client_pub_key) : row('Public key', '—'),
]),
);
dom.content(foot, [
@@ -300,15 +301,22 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const rename = () => {
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
const nameRow = liveField('Name', input, () => nameHelp(input.value, taken, 'Shown in the portal and in the app.'));
modal(
`Rename ${d.name}`,
[E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])],
[nameRow],
[
cancelButton(),
' ',
button(
'Save',
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
closeModal();
await changed();
@@ -426,7 +434,11 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
`${d.name} · QR code`,
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(core.qrText(c)), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
E(
'span',
{ class: 'dl-sub' },
plainWg(c) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
),
]),
cancelButton('Close'),
);
@@ -500,8 +512,22 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
export function addDevice(person: Person, o: DeviceOpts) {
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: KIND_LABEL.phone, maxlength: 48 }) as HTMLInputElement;
const taken = person.devices.map((x) => x.name);
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
const suggest = (k: Kind) => {
const base = KIND_LABEL[k];
let n = 1;
let name = base;
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
return name;
};
let kind: Kind = 'phone';
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
const nameRow = liveField('Name', nameInput, () =>
nameInput.value.trim()
? nameHelp(nameInput.value, taken, 'Shown in the portal and in the app.')
: { text: `Named after its type: ${suggest(kind)}.`, bad: false },
);
const kinds = E(
'div',
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
@@ -521,7 +547,8 @@ export function addDevice(person: Person, o: DeviceOpts) {
c.classList.toggle('on', on);
c.setAttribute('aria-checked', on ? 'true' : 'false');
});
nameInput.placeholder = KIND_LABEL[k];
nameInput.placeholder = suggest(k);
nameRow.refresh();
},
},
[icon(k), E('span', {}, KIND_LABEL[k])],
@@ -540,7 +567,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
)
: '',
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]),
nameRow,
],
[
cancelButton(),
@@ -548,7 +575,12 @@ export function addDevice(person: Person, o: DeviceOpts) {
button(
'Add device',
async () => {
const name = nameInput.value.trim() || nameInput.placeholder.replace(/^e\.g\. /, '');
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
const name = nameInput.value.trim() || suggest(kind);
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
if (!r) return;
closeModal();
+28 -22
View File
@@ -4,7 +4,9 @@ import type { AwgCaps } from '../shared/types';
import { E } from './e';
import { icon } from '../shared/icons';
export type Method = 'standard' | 'strong' | 'max' | 'off';
export type Method = 'balanced' | 'max' | 'off';
/** The router features a method may need (the boolean ones of AwgCaps). */
export type AwgNeed = 'v2' | 'v3';
export interface MethodInfo {
id: Method;
@@ -19,7 +21,7 @@ export interface MethodInfo {
/** The same, short (server header). */
short: string;
/** Router capability it needs. */
needs?: keyof AwgCaps;
needs?: AwgNeed;
}
export const METHODS: MethodInfo[] = [
@@ -34,24 +36,15 @@ export const METHODS: MethodInfo[] = [
short: 'Any WireGuard app',
},
{
id: 'standard',
title: 'Standard',
id: 'balanced',
title: 'Balanced',
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',
speed: 4,
needs: 'v2',
text: 'AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.',
apps: 'AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps',
short: 'AmneziaWG 2.0+ apps',
},
{
id: 'max',
@@ -68,13 +61,24 @@ export const METHODS: MethodInfo[] = [
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.',
/** The disguise a new server gets: the strongest this router can run. */
export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.v2 ? 'balanced' : 'off');
/**
* Servers made before 0.8 may carry the old Standard or Strong disguise
* (1.0-style junk only, which networks learned to spot). They keep running;
* the picker offers Balanced or Maximum instead. The title for such a server, or null.
*/
export const legacyTitle = (preset: string): string | null =>
preset === 'standard' ? 'Standard (old)' : preset === 'strong' ? 'Strong (old)' : null;
const NEEDS: Record<AwgNeed, string> = {
v2: 'Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).',
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
};
/** The same while no AmneziaWG is installed at all ("newer" would be misleading). */
const NEEDS_NONE: Record<keyof AwgCaps, string> = {
const NEEDS_NONE: Record<AwgNeed, string> = {
v2: 'Needs AmneziaWG on the router.',
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
};
@@ -135,7 +139,9 @@ export function methodPicker(
E(
'div',
{ class: 'dl-method-foot' },
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
ok
? [icon(m.id === 'off' ? 'wireguard' : 'amneziawg'), E('span', {}, m.apps)]
: [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
),
],
);
+2
View File
@@ -20,6 +20,8 @@ const CATEGORY: Record<string, LogCategory> = {
person_changed: 'people',
paused: 'people',
resumed: 'people',
expiring: 'people',
expired_kept: 'people',
portal_blocked: 'problems',
};
+8
View File
@@ -21,6 +21,8 @@ const EVENT_TONE: Record<string, string> = {
person_removed: '',
paused: 'warn',
resumed: 'ok',
expiring: 'warn',
expired_kept: '',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
@@ -35,6 +37,8 @@ const EVENT_ICON: Record<string, string> = {
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
expiring: 'calendar',
expired_kept: 'calendar',
};
function eventIcon(st: Names, e: LogEvent): string {
@@ -135,6 +139,10 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
case 'person_changed':
// The detail lists changed fields by their option names (device_limit, expire_action).
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
case 'expiring':
return [kind('Person'), b(who), m(`’s access ends in ${e.detail ?? 'a few days'}`)];
case 'expired_kept':
return [kind('Person'), b(who), m(`’s end date passed (${e.detail ?? ''}) · access kept`)];
case 'paused':
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
+13 -7
View File
@@ -107,21 +107,27 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
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] });
// Three tiers: the card as a file, the link through the share sheet (older
// Android, Firefox on phones), else a download of the card.
const canShareFile = !!nav.canShare?.({ files: [file] });
const canShareLink = !canShareFile && typeof nav.share === 'function' && (nav.canShare?.({ url: href }) ?? true);
const close = () => {
URL.revokeObjectURL(url);
closeModal();
};
const share = canShare
? button(
[icon('link'), ' Share card'],
async () => {
const shareIt = async (data: ShareData) => {
try {
await nav.share({ files: [file], title: `Invite ${p.name}` });
await nav.share(data);
} catch {
/* cancelled */
}
},
};
const share = canShareFile
? button([icon('link'), ' Share card'], () => shareIt({ files: [file], title: `Invite ${p.name}` }), 'positive')
: canShareLink
? button(
[icon('link'), ' Share link'],
() => shareIt({ url: href, title: `Invite ${p.name}`, text: `Your personal VPN link` }),
'positive',
)
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
+29 -4
View File
@@ -13,6 +13,15 @@ import { onNavigate } from './ui/nav';
// mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it.
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist';
// What those files must be (sha384): code from a CDN runs inside the LuCI
// page, where it could use the admin's session. A modulepreload with an
// integrity carries the check into the import(); the stylesheet has its own.
// The worker (loaded by the library) runs in its own context without the page
// or the session, so it goes unchecked.
const MAPLIBRE_SRI = {
module: 'sha384-q26X6R1yFeg0QR9SHHn6U3Nb0ddRRTtwxsahubv5R89/v5nijKpk9KviUp9ZLySk',
css: 'sha384-1TZtfVz7qtwR5vD7cMwjGT+9uiK4lqE3pbUOPwYO6OCpb+TYP0S9vLIhG02JCU04',
};
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';
@@ -29,17 +38,33 @@ let loading: Promise<any> | null = null;
* leaves it alone), with the worker URL set as mapcn does.
*/
function loadMapLibre(host: HTMLElement): Promise<any> {
host.appendChild(E('link', { rel: 'stylesheet', href: `${MAPLIBRE}/maplibre-gl.css` }));
host.appendChild(
E('link', { rel: 'stylesheet', href: `${MAPLIBRE}/maplibre-gl.css`, integrity: MAPLIBRE_SRI.css, crossorigin: 'anonymous' }),
);
if (loading) return loading;
const url = `${MAPLIBRE}/maplibre-gl.mjs`;
loading = import(/* @vite-ignore */ url).then(
// The preload fetches and checks the module; the module map keeps the
// result, so the import() below gets the checked copy or fails with it.
const preload = new Promise<void>((resolve, reject) => {
const link = E('link', { rel: 'modulepreload', href: url, integrity: MAPLIBRE_SRI.module, crossorigin: 'anonymous' });
link.addEventListener('load', () => resolve());
link.addEventListener('error', () => reject(new Error('integrity')));
document.head.appendChild(link);
});
loading = preload
.then(() => import(/* @vite-ignore */ url))
.then(
(gl) => {
if (!gl.getWorkerUrl()) gl.setWorkerUrl(`${MAPLIBRE}/maplibre-gl-worker.mjs`);
return gl;
},
() => {
(e: Error) => {
loading = null;
throw new Error('Could not load the map library (no internet access from this browser?)');
throw new Error(
e?.message === 'integrity'
? 'The map library from the CDN is not the expected file: not loading it.'
: 'Could not load the map library (no internet access from this browser?)',
);
},
);
return loading;
+230
View File
@@ -91,3 +91,233 @@ export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean
const who = holder(port + 1, taken);
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
}
/* ---------- other fields, mirroring the router's rules (dawnline.util, schema, core) ---------- */
/** Characters, not UTF-16 units or bytes: what the router counts (util.ulength). */
export const chars = (s: string): number => Array.from(s).length;
const NAME_MAX = 48;
const BAD_NAME = /[<>"\\\u0000-\u001f\u007f]/;
/**
* A name people see (util.valid_name): 1–48 characters, none of < > " \.
* `taken` are names already used where it must be unique (case-insensitive).
*/
export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
const t = s.trim();
if (!t) return { text: 'Enter a name.', bad: true };
if (chars(s) > NAME_MAX) return { text: `Up to ${NAME_MAX} characters (${chars(s)} now).`, bad: true };
if (BAD_NAME.test(s)) return { text: 'Names can’t contain < > " or \\.', bad: true };
if (taken.some((x) => x.toLowerCase() === t.toLowerCase())) return { text: `“${t}” already exists — pick another name.`, bad: true };
return { text: good, bad: false };
}
/** A circle's name: like a name, up to 32 characters. */
export function circleNameHelp(s: string, taken: string[] = []): Help {
if (chars(s) > 32) return { text: `Up to 32 characters (${chars(s)} now).`, bad: true };
return nameHelp(s, taken, 'Shown on the person cards.');
}
const HOSTNAME = /^[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])?)*$/;
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
export function isIpv4(s: string): boolean {
const m = IPV4.exec(s);
return !!m && m.slice(1).every((x) => Number(x) <= 255);
}
export function isIpv6(s: string): boolean {
return /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(s) && !/:::/.test(s);
}
/**
* The public address of a server or the portal (util.valid_host): a hostname
* or an IP address, nothing else. `port` names what devices connect to when
* it is fine; `empty` is what an empty field means (null: it is required).
*/
export function hostHelp(s: string, port?: number, empty: string | null = null): Help {
const t = s.trim();
if (!t) return empty != null ? { text: empty, bad: false } : { text: 'Enter a hostname or IP address.', bad: true };
if (/^[a-z]+:\/\//i.test(t)) return { text: 'Leave out https:// — just the name.', bad: true };
if (/\/.*/.test(t)) return { text: 'Just the name, without a path.', bad: true };
if (/^[^:\[]+:\d+$/.test(t)) return { text: 'Just the name, without a port (the port is on AmneziaWG).', bad: true };
if (/\s/.test(t)) return { text: 'A hostname has no spaces.', bad: true };
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: 'Use a hostname or an IP address.', bad: true };
const shown = isIpv6(t) ? `[${t}]` : t;
return { text: port ? `Devices connect to ${shown}:${port}.` : `Links use ${shown}.`, bad: false };
}
/** The DNS list a server hands to devices (rpc/servers.uc dns_list): IPs, comma-separated; empty = this router. */
export function dnsHelp(s: string, routerAddr: string): Help {
const items = s.split(/[ ,]+/).filter(Boolean);
if (!items.length)
return { text: `This router (${routerAddr}): queries go where your home network sends them, and home names work.`, bad: false };
const bad = items.find((x) => !isIpv4(x) && !isIpv6(x));
if (bad) return { text: `“${bad}” is not an IP address. Separate several with commas.`, bad: true };
return { text: `Devices use ${items.join(' and ')} — home names and your LAN’s DNS filters no longer apply to them.`, bad: false };
}
/** MTU (rpc/servers.uc check_mtu): empty = automatic, else 1280–1500. */
export function mtuHelp(s: string, mtus: { computer: number; phone: number }): Help {
const t = s.trim();
if (!t)
return {
text: `Automatic by device type and disguise: ${mtus.computer} for computers and routers, ${mtus.phone} for phones and tablets.`,
bad: false,
};
if (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)
return { text: 'MTU must be 1280–1500, or empty for automatic.', bad: true };
const n = Number(t);
return { text: `Computers and routers get ${n}, phones and tablets ${Math.min(n, 1280)}.`, bad: false };
}
/** Keep-alive (rpc/servers.uc): 0–600 s; empty = 25. */
export function keepaliveHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'Default: a packet every 25 s keeps NAT open and “Connected” accurate.', bad: false };
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: 'Use 0–600 seconds.', bad: true };
if (Number(t) === 0) return { text: 'Off: NAT may close the tunnel when idle, and “Connected” lags.', bad: false };
return { text: `Devices send a packet every ${t} s to keep NAT open (a little battery on phones).`, bad: false };
}
/** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */
export function limitHelp(s: string, have = 0): Help {
const t = s.trim();
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: 'Use 1–32.', bad: true };
const n = Number(t);
if (have > n)
return { text: `Already has ${have} devices: remove ${have - n === 1 ? 'one' : `${have - n}`} first, or allow more.`, bad: true };
return { text: `They can add ${n} device${n === 1 ? '' : 's'} themselves.`, bad: false };
}
/** Monthly data in GB (core.create_person): empty = unlimited, else 0–100000. */
export function quotaHelp(s: string, monthly = true): Help {
const t = s.trim();
if (!t) return { text: 'Optional. No data limit.', bad: false };
const n = Number(t);
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: 'A number of GB, up to 100000.', bad: true };
if (n === 0) return { text: 'Optional. No data limit.', bad: false };
return { text: monthly ? `Paused after ${t} GB this month, resumed on the 1st.` : `Paused after ${t} GB in total.`, bad: false };
}
/** An end date (YYYY-MM-DD) against the router's day; empty = none. */
export function expiresHelp(
s: string,
today: string,
daysLeft: (d: string, t: string) => number | null,
date: (d: string) => string,
): Help {
const t = s.trim();
if (!t) return { text: 'Optional. No end date.', bad: false };
const left = daysLeft(t, today);
if (left == null) return { text: 'Use a date.', bad: true };
if (left < 0) return { text: 'That date has passed: access would end at once.', bad: true };
return { text: left === 1 ? `Access ends today (${date(t)}).` : `Access ends in ${left} days (${date(t)}).`, bad: false };
}
/** A home service's address (rpc/home.uc): IPv4; `homeNets` warn when it is outside every home network. */
export function ipv4Help(s: string, inHome: ((ip: string) => boolean) | null = null): Help {
const t = s.trim();
if (!t) return { text: 'The device’s address at home.', bad: true };
if (!isIpv4(t)) return { text: 'Use an IPv4 address, like 192.168.1.10.', bad: true };
if (inHome && !inHome(t)) return { text: `${t} is not in any home network of this server: nobody would reach it.`, bad: false };
return { text: '', bad: false };
}
/** A service's ports: empty = all, else numbers 1–65535. */
export function portsHelp(s: string): Help {
const items = s.split(/[ ,]+/).filter(Boolean);
if (!items.length) return { text: 'All ports.', bad: false };
const bad = items.find((x) => !/^\d{1,5}$/.test(x) || Number(x) < 1 || Number(x) > 65535);
if (bad) return { text: `“${bad}” is not a port (1–65535).`, bad: true };
return { text: `Port${items.length === 1 ? '' : 's'} ${items.join(', ')}.`, bad: false };
}
/** The portal's redirect for unknown links (schema portal_redirect): a full http(s) URL, or empty. */
export function urlHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'Wrong links get a bare “Not found”.', bad: false };
if (!/^https?:\/\//i.test(t)) return { text: 'Must start with http:// or https://.', bad: true };
if (t.length > 300 || !/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(t))
return { text: 'Not a usable address (no spaces or quotes).', bad: true };
return { text: 'Wrong links are sent there instead of a “Not found”.', bad: false };
}
/** The portal's title: up to 64 characters on one line. */
export function titleHelp(s: string): Help {
if (chars(s) > 64) return { text: `Up to 64 characters (${chars(s)} now).`, bad: true };
if (/[\u0000-\u001f\u007f]/.test(s)) return { text: 'One line, please.', bad: true };
return { text: 'Shown in the browser tab and at the top of the portal.', bad: false };
}
/** The home domain for device hostnames (schema domain): lowercase letters, digits, dashes, dots. */
export function domainHelp(s: string, example = 'phone.myata'): Help {
const t = s.trim();
// Empty keeps the default (the router stores nothing then).
if (!t) return { text: `The default, lan: devices get names like ${example}.lan.`, bad: false };
if (!/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(t))
return { text: /[A-Z]/.test(t) ? 'Lowercase only.' : 'Lowercase letters, digits, dashes and dots.', bad: true };
return { text: `Devices get names like ${example}.${t}.`, bad: false };
}
/** The fallback DNS for home-names devices: an IPv4 address, or empty for none. */
export function fallbackDnsHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'None: without the tunnel those devices have no DNS.', bad: false };
if (!isIpv4(t)) return { text: 'Use an IPv4 address, or leave it empty.', bad: true };
return { text: `${t} takes over when the tunnel is down.`, bad: false };
}
/** The daily update time (schema update_time): HH:MM. */
export function timeHelp(s: string): Help {
const t = s.trim();
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: 'Use HH:MM, 00:00–23:59.', bad: true };
return { text: `Runs within an hour after ${t} (router time).`, bad: false };
}
/**
* A public address checked on the router as it is typed (rpc endpoint_probe:
* where it points, CGNAT, Cloudflare), debounced so a keystroke is not a
* lookup. `help()` is the row's: the syntax first (hostHelp), then the
* router's verdict once it arrives, "Checking…" in between.
*/
export function endpointProbe(
get: () => { host: string; port: number; id?: string },
probe: (host: string, id: string | undefined, port: number) => Promise<{ text: string; status?: string }>,
onResult: () => void,
opts: { empty?: string | null; idle?: () => string } = {},
) {
let timer = 0;
let asked = '';
let result: { host: string; text: string; bad: boolean } | null = null;
const schedule = () => {
const { host } = get();
const h = hostHelp(host, get().port, opts.empty ?? null);
if (h.bad || !host.trim() || host.trim() === result?.host) return;
clearTimeout(timer);
timer = window.setTimeout(async () => {
const want = host.trim();
asked = want;
try {
const { id, port } = get();
const r = await probe(want, id, port);
if (asked !== want) return;
result = { host: want, text: r.text, bad: r.status === 'error' };
} catch {
if (asked !== want) return;
result = { host: want, text: h.text, bad: false };
}
onResult();
}, 700);
};
const help = (): Help => {
const { host, port } = get();
const h = hostHelp(host, port, opts.empty ?? null);
if (h.bad || !host.trim()) return h;
if (result && result.host === host.trim()) return { text: result.text, bad: result.bad };
const idle = opts.idle?.();
return { text: idle ? `${idle} Checking where it points…` : `${h.text} Checking where it points…`, bad: false };
};
return { help, schedule };
}
+52 -5
View File
@@ -8,7 +8,7 @@ import { api } from '../api';
import { svg } from '../ui/layout';
import { attachTip } from '../ui/tooltip';
import { icon } from '../../shared/icons';
import { ago, bits, bytes, daysLeft, initials, todayOf } from '../../shared/format';
import { ago, bits, bytes, date, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
import { ConnectionMap, rangeControl, type Range } from '../map';
import { personUrl } from '../urls';
import { eventRow } from '../events/render';
@@ -17,6 +17,9 @@ import { repaint } from '../state/poller';
import { daysTile, speedTile } from '../widgets/tiles';
import { coreOf } from '../cores';
import { healthNotices, runFix } from '../widgets/health';
import { attempt } from '../ui/toast';
import { isIpv4 } from '../netcheck';
import { onNavigate } from '../ui/nav';
interface Attention {
tone: string;
@@ -46,8 +49,10 @@ function attention(st: Status): Attention[] {
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, today);
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 (endsSoon(p, left)) out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ${endsIn(left as number)}.`] });
// "Keep access" at the end date: nothing changes on its own, so it is said here.
else if (left != null && left < 0 && p.expire_action === 'notify')
out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s end date passed (${date(p.expires)}) · access kept.`] });
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.'] });
}
@@ -64,12 +69,40 @@ function attention(st: Status): Attention[] {
]
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
});
// A server that gives devices an IPv4 that is no longer the router's: one click puts the new one in.
for (const s of st.servers)
if (st.wan && isIpv4(s.endpoint) && s.endpoint !== st.wan)
out.push({
tone: 'warn',
text: [
`Public address changed: ${s.name} still gives devices ${s.endpoint}, the router is ${st.wan} now. `,
E(
'button',
{
type: 'button',
class: 'dl-fix',
click: async (ev: Event) => {
const b = ev.currentTarget as HTMLButtonElement;
b.disabled = true;
await attempt(
() => api.serverUpdate(s.id, { endpoint: st.wan }),
`${s.name} uses ${st.wan} now — devices need their configuration again`,
);
b.disabled = false;
},
},
'Use the new address',
),
' A DDNS name would follow it by itself.',
],
});
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/diagnostics'), 'Details')],
});
if (!st.settings.portal_enabled)
// Only while setting up: an admin who keeps the portal off has decided so.
if (!st.settings.portal_enabled && !st.people.length)
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
return out;
}
@@ -157,6 +190,7 @@ export class ServerOverview {
'.',
]),
]);
this.map?.destroy();
this.map = new ConnectionMap(
{
openPerson: (id) => (location.href = personUrl(id)),
@@ -164,6 +198,13 @@ export class ServerOverview {
},
this.range,
);
// A WebGL map outlives the page's DOM unless it is told: free it when
// Outline navigates away (the page object itself may be reused).
const offNav = onNavigate(() => {
offNav();
this.map?.destroy();
this.map = null;
});
const legend = E('div', { class: 'dl-map-legend' }, [
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
@@ -382,6 +423,12 @@ export class ServerOverview {
/** The last 30 days, today on the right, with the peak. */
monthTile(): HTMLElement {
return daysTile(this.st.series, '');
// Who used the most this month (the People sort has it too, a click away).
const top = [...this.st.people]
.map((p) => [p, p.month[0] + p.month[1]] as const)
.filter(([, n]) => n > 0)
.sort((a, b) => b[1] - a[1])
.slice(0, 2);
return daysTile(this.st.series, top.length ? `Most: ${top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')}` : '');
}
}
+137 -26
View File
@@ -17,7 +17,10 @@ import { copyPersonLink, inviteCard } from '../invite';
import { personUrl } from '../urls';
import { scoped } from '../state/scope';
import { createPoller, focusInside, type Poller } from '../state/poller';
import { onNavigate } from '../ui/nav';
import { accessPicker } from '../widgets/access-picker';
import { firstBad, liveField } from '../ui/layout';
import { expiresHelp, limitHelp, nameHelp, quotaHelp } from '../netcheck';
import { coreFor } from '../cores';
import { icon } from '../../shared/icons';
import {
@@ -30,12 +33,30 @@ import {
date,
dayDiff,
daysLeft,
endsIn,
endsSoon,
initials,
todayOf,
} from '../../shared/format';
type Sid = string;
/** Per-browser conveniences (a tab, a sort): storage may be absent or refuse. */
function remembered(key: string): string | null {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function remember(key: string, value: string) {
try {
localStorage.setItem(key, value);
} catch {
/* no storage */
}
}
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
function slotBar(p: Person): HTMLElement {
const used = p.devices.length;
@@ -66,12 +87,7 @@ const stopReason = (p: Person): Exclude<Person['state'], 'active' | 'server_off'
function needsAttention(p: Person, today: string): boolean {
const left = daysLeft(p.expires, today);
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)
);
return p.state === 'quota' || p.state === 'expired' || endsSoon(p, left) || (!!p.quota_limit && p.quota_used >= p.quota_limit * 0.9);
}
/** A month more, from the end date or from today once it has passed. */
@@ -92,9 +108,14 @@ export class PeoplePage {
/** The cards, one per person, in the current sort order. */
private list: HTMLElement = E('div', { class: 'dl-plist', role: 'list' });
// `?filter=online` (from Overview) preselects a tab.
// The tab and the sort are remembered in this browser; ?filter= (from Overview) wins for the tab.
filter: Filter =
(['all', 'online', 'attention', 'paused'] as Filter[]).find((f) => f === new URLSearchParams(location.search).get('filter')) ?? 'all';
sort: SortBy = 'seen';
(['all', 'online', 'attention', 'paused'] as Filter[]).find(
(f) => f === (new URLSearchParams(location.search).get('filter') ?? remembered('dl.people.filter')),
) ?? 'all';
sort: SortBy = (['seen', 'name', 'usage'] as SortBy[]).find((x) => x === remembered('dl.people.sort')) ?? 'seen';
/** What the admin typed into Find (name, note, device, address). */
query = '';
noFooter = true;
/** Set when shown as a server's People section: only that server's people. */
serverId: string | null = null;
@@ -211,11 +232,37 @@ export class PeoplePage {
'aria-label': 'Sort',
change: (ev: Event) => {
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
remember('dl.people.sort', page.sort);
page.decorate();
},
},
[E('option', { value: 'seen' }, 'Last seen'), E('option', { value: 'name' }, 'Name'), E('option', { value: 'usage' }, 'Usage')],
[
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, 'Last seen'),
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, 'Name'),
E('option', { value: 'usage', selected: page.sort === 'usage' ? 'selected' : null }, 'Usage'),
],
);
// Find, once the list is long enough to need it; "/" focuses it.
const find = E('input', {
type: 'search',
class: 'cbi-input-text dl-people-find',
placeholder: 'Find…',
'aria-label': 'Find a person or device',
hidden: st.people.length > 8 ? null : 'hidden',
input: (ev: Event) => {
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
page.decorate();
},
}) as HTMLInputElement;
const onSlash = (ev: KeyboardEvent) => {
const t = ev.target as HTMLElement;
if (ev.key === '/' && !find.hidden && !['INPUT', 'TEXTAREA', 'SELECT'].includes(t?.tagName) && !t?.isContentEditable) {
ev.preventDefault();
find.focus();
}
};
document.addEventListener('keydown', onSlash);
onNavigate(() => document.removeEventListener('keydown', onSlash));
const wrap = E('div', { class: 'dl-root' }, [
page.serverId
? ''
@@ -237,6 +284,7 @@ export class PeoplePage {
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
// Sort and add stay together on the right, wrapping as one group.
E('div', { class: 'dl-toolbar-end' }, [
find,
sort,
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
]),
@@ -293,6 +341,7 @@ export class PeoplePage {
class: f === this.filter ? 'on' : '',
click: () => {
this.filter = f;
remember('dl.people.filter', f);
this.decorate();
},
},
@@ -301,10 +350,14 @@ export class PeoplePage {
),
);
}
const q = this.query;
const hay = (p: Person) =>
[p.name, p.note ?? '', ...p.devices.flatMap((d) => [d.name, d.address, d.hostname, d.endpoint])].join(' ').toLowerCase();
const match = (p: Person) => {
if (this.filter === 'online' && !p.online) return false;
if (this.filter === 'attention' && !attn(p)) return false;
if (this.filter === 'paused' && !paused(p)) return false;
if (q && !hay(p).includes(q)) return false;
return true;
};
// Whatever the sort: people who can connect, then those held by a limit or an end
@@ -357,12 +410,12 @@ export class PeoplePage {
const pills: Node[] = [];
const why = stopReason(p);
if (p.expires && why !== 'expired') {
const soon = left != null && left >= 0 && left <= Math.max(p.expire_warn, 3);
const soon = endsSoon(p, left);
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)}`,
over ? `ended ${date(p.expires)}` : soon ? endsIn(left as number) : `until ${date(p.expires)}`,
]),
);
}
@@ -408,9 +461,18 @@ export class PeoplePage {
),
);
// Ending soon (the strip below handles an end that has passed).
// Ending soon (the strip below handles an end that has passed); someone new
// without a device yet gets a nudge to send the link.
const fixes: Node[] = [];
if (p.expires && left != null && left <= Math.max(p.expire_warn, 3) && why !== 'expired')
if (!p.devices.length && portal && !stopped(p))
fixes.push(
E(
'button',
{ type: 'button', class: 'dl-fix', click: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home') },
'Send invite',
),
);
if (p.expires && endsSoon(p, left) && why !== 'expired')
fixes.push(
E(
'button',
@@ -615,7 +677,15 @@ export class PeoplePage {
return;
}
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement;
const access = accessPicker('internet');
// The last person's access and data limit come back pre-filled (most are alike).
const last = (() => {
try {
return JSON.parse(remembered('dl.person.last') ?? '{}') as { access?: Person['access']; quota?: string };
} catch {
return {} as { access?: Person['access']; quota?: string };
}
})();
const access = accessPicker(last.access ?? 'internet');
const limit = E('input', {
type: 'number',
class: 'cbi-input-text',
@@ -630,6 +700,7 @@ export class PeoplePage {
min: 0,
step: 'any',
placeholder: 'Unlimited',
value: last.quota ?? '',
}) as HTMLInputElement;
const quick = (label: string, months: number) =>
E(
@@ -639,6 +710,7 @@ export class PeoplePage {
class: 'cbi-button cbi-button-neutral',
click: () => {
expires.value = months ? addMonthsClamped(todayOf(st.series), months) : '';
expires.dispatchEvent(new Event('change'));
},
},
label,
@@ -658,44 +730,62 @@ export class PeoplePage {
E('label', { class: 'cbi-value-title' }, label),
E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']),
]);
// Each field says what its value means, or what is wrong, as it is typed; Create refuses what the router would.
const today = todayOf(st.series);
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown in their portal and apps.'));
const limitRow = liveField('Devices', limit, () => limitHelp(limit.value));
const expRow = liveField(
'End date',
expires,
() => expiresHelp(expires.value, today, daysLeft, date),
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
);
const quotaRow = liveField('Monthly data (GB)', quota, () => quotaHelp(quota.value));
// The quick buttons set the date without an input event.
expires.addEventListener('change', () => expRow.refresh());
const portalOn = st.settings.portal_enabled;
modal(
'Add person',
[
row('Name', name),
nameRow,
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.'),
limitRow,
expRow,
quotaRow,
],
[
cancelButton(),
' ',
button(
'Create and copy link',
// Without the portal there is no link to copy.
portalOn ? 'Create and copy link' : 'Create',
async () => {
const bad = firstBad([nameRow, limitRow, expRow, quotaRow]);
if (bad) {
notify(bad, 'warning');
return;
}
const r = await attempt(() =>
api.personCreate(
name.value.trim(),
'',
server?.value ?? srv.id,
access.get(),
String(Number(limit.value) || st.settings.default_device_limit),
limit.value.trim(),
expires.value,
quota.value.trim(),
'month',
),
);
if (!r) return;
if (r.link) await copyText(r.link, 'Personal link copied');
remember('dl.person.last', JSON.stringify({ access: access.get(), quota: quota.value.trim() }));
// After the await some browsers refuse the clipboard: the card has its own Copy.
if (r.link) await copyText(r.link, 'Personal link copied', true);
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();
},
@@ -714,10 +804,31 @@ export class PeoplePage {
});
return;
}
// No portal, no link: the two ways on from here, as buttons.
const p = this.person(id);
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')],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Done'),
' ',
E(
'a',
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}?section=portal` },
'Open Settings',
),
' ',
p
? button(
'Add device',
() => {
closeModal();
addDevice(p, this.deviceOpts(p));
},
'positive',
)
: '',
],
);
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ export function devicesPart(page: PersonPage): HTMLElement {
E('span', { class: 'dl-dcard-ic' }, icon(d.kind)),
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
E('b', {}, d.name),
deviceStatus(d, now),
deviceStatus(d, now, undefined, p),
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
]),
more(d),
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more