Compare commits

5 Commits
Author SHA1 Message Date
Aemeath 29b1d7dfd7 Dawnline 0.4.2
Build packages / Version (push) Waiting to run
- Connections show up at once: the agent looks at the tunnels every
  second and, the moment a device connects or roams, writes it to the
  activity log, updates traffic and the map, and locates the new address
- A device counts as gone when its WireGuard session expires (1-3 min
  after it leaves), so a phone asleep no longer flaps between
  disconnect and connect
- The admin pages follow along within seconds: Overview, People, the
  person page and the device panel refresh when something happens, with
  a light check every 2 s instead of reloading everything every 10 s
- The personal portal no longer refreshes itself in the background:
  every request costs the router a CGI process, so it loads once and
  after the visitor's own changes
- Agent guidance and code standards (backend, frontend, shell, UI) now
  live in the repository: AGENTS.md and rules/
2026-10-16 03:52:21 +03:00
Aemeath 6444722d14 Dawnline 0.4.1
Build packages / Version (push) Waiting to run
- Fixed: with a transparent proxy on the router (Clash, sing-box and
  others that mark the router's own traffic for tproxy), the portal and
  AmneziaWG answered nobody outside the LAN: their replies were diverted
  into the proxy, so visitors saw timeouts (Cloudflare 522) and devices
  could not connect from outside
- Dawnline's own answers now leave by the main table through a small nft
  table (inet dawnline_reply) that clears only the proxy's mark on them;
  it follows the proxy within a minute when one starts later, and the old
  priority-90 policy rules, which never matched, are removed
- Health's "answers reach" checks read that table, and the uninstaller
  removes it
2026-10-16 03:12:48 +03:00
Aemeath 34293fb8e5 Dawnline 0.4.0
Build packages / Version (push) Waiting to run
- Components tab replaces Updates: Dawnline, the AmneziaWG build for this
  firmware (Slava-Shchipunov 2.0 or 2Grey 3.1, Russian translation) and
  the system packages Dawnline adds, each checked, installed, reinstalled
  or rolled back in place, with What's new, versions and an activity log
- Automatic updates: daily check, install at a set time or right away,
  per component; AmneziaWG is left out by default and an automatic run
  never switches its build or generation
- Downloads verified against GitHub's sha256; mirrors are used only when
  GitHub is unreachable and the hash is known
- New installer: checks firmware, clock, space and DNS, lets you pick a
  release, shows the plan and asks first; --dry-run
- New uninstaller removes everything Dawnline added (cron, nft, firewall,
  routing, interfaces, packages it installed); --dry-run
- Works without AmneziaWG on the router: Overview, the setup wizard,
  Health and Components say what is missing and offer to install it
- Overview shows failed health checks as notices with their fix
- People list no longer reads the config from the browser: private keys
  stay on the router; personal links are fetched on demand
- Config changes are serialized under one lock, the nft table loads
  atomically and fails closed, and Dawnline never touches network
  sections it did not create
- The portal never opens system ports, keeps disabled devices disabled,
  rate-limits per address and counts days by the router's clock
- Settings and Diagnostics load their heavy parts in the background
- Release notes are written from the commits since the previous release
- Backend and admin UI split into small single-purpose modules
2026-10-16 02:14:15 +03:00
Aemeath 70a932b8ea Dawnline 0.3.1
Build packages / Version (push) Waiting to run
- Find home devices (Bonjour) removed: iOS looks for services over the
  tunnel only under a search domain, and Android and Chromecast only over
  multicast, which WireGuard does not carry. Upgrading removes its server
  option and dnsmasq records
- Home services still show the ports devices announce when umdns runs
2026-10-15 19:01:15 +03:00
Aemeath e657742b52 README: new screenshots for 0.3.0, Access added 2026-10-15 18:21:27 +03:00
180 changed files with 17870 additions and 10286 deletions

No files matched your search

+24 -11
View File
@@ -3,14 +3,17 @@ name: Build packages
# A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk
# (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with
# both packages and sha256sums.txt, the files install.sh and the in-app updater
# download. Run it by hand to get the packages as workflow artifacts only.
# download. The release notes list what changed since the previous tag, from the
# commits (scripts/release-notes.sh). Run it by hand to get the packages as
# workflow artifacts only.
on:
push:
tags: ['v*']
workflow_dispatch:
# Read-only by default; only the release job may write (publish the release).
permissions:
contents: write
contents: read
jobs:
version:
@@ -21,6 +24,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Read and check the version
id: version
@@ -49,6 +54,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v5
@@ -82,7 +89,21 @@ jobs:
runs-on: ubuntu-24.04
needs: [version, build]
if: github.ref_type == 'tag'
permissions:
contents: write
steps:
# The whole history and the tags: the notes list the commits since the previous tag.
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
fetch-depth: 0
- name: Release notes
run: |
sh scripts/release-notes.sh "${GITHUB_REF_NAME}" "${GITHUB_REPOSITORY}" > notes.md
cat notes.md
- name: Download packages
uses: actions/download-artifact@v4
with:
@@ -102,12 +123,4 @@ jobs:
name: Dawnline ${{ github.ref_name }}
tag_name: ${{ github.ref_name }}
files: release/*
generate_release_notes: true
body: |
Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk):
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh)"
```
Or upgrade from LuCI → Network → Dawnline → Updates.
body_path: notes.md
+7
View File
@@ -22,6 +22,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v5
@@ -78,12 +80,15 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: ShellCheck
run: |
shellcheck --version
shellcheck -S warning \
install.sh \
uninstall.sh \
package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
@@ -96,6 +101,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Use before definition
run: python3 scripts/lint-ucode.py
+35
View File
@@ -0,0 +1,35 @@
# AGENTS.md — Dawnline
Guidance for coding agents working in this repository (`tickcount/luci-app-dawnline`): an AmneziaWG access server for OpenWrt with a LuCI admin UI and a personal portal. `CLAUDE.md` points here.
## Rules
- `rules/code-standards.md` — how all code is written: decomposition, one locked writer, fail closed, validation at the boundary, comments and commits.
- `rules/backend.md` — ucode on the router: module layers, conventions, what things cost there (CGI portal, rpcd, the agent's watcher).
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
- `rules/shell.md` — install, uninstall, init and CI scripts.
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
## Layout
- `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`.
## 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).
## Releases
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
- No `Co-Authored-By` or other agent attribution in commits.
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` and `sha256sums.txt`.
- Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead.
- On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256).
+74 -20
View File
@@ -20,9 +20,11 @@ limits, live traffic and a LuCI admin that follows a modern design.
|---|---|
| ![People](docs/screenshots/people.png) | ![Person](docs/screenshots/person.png) |
| Personal portal | Where people connect from |
| Personal portal | Home network access |
|---|---|
| ![Personal portal](docs/screenshots/portal.png) | ![Map](docs/screenshots/map.png) |
| ![Personal portal](docs/screenshots/portal.png) | ![Access](docs/screenshots/access.png) |
![Where people connect from](docs/screenshots/map.png)
## Features
@@ -34,9 +36,11 @@ limits, live traffic and a LuCI admin that follows a modern design.
accounts, no sessions, and a new link locks the old one out at once. People
add, rename and remove their devices and get each one as a QR code,
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
access or limits. Links work on 443 with a Let's Encrypt certificate (via
ACME), several addresses at once (a Cloudflare-proxied name, a plain IP), the
same link at home, and wrong links can redirect to your website.
access or limits. Links work on the portal's own port with a Let's Encrypt
certificate (via ACME), several addresses at once (a Cloudflare-proxied name,
a plain IP), the same link at home, and wrong links can redirect to your
website. Behind Cloudflare, pick a port it proxies (2053, 2083, 2087, 2096 or
8443).
- **Access per person**, enforced in an `inet dawnline` nftables table on the
tunnel interface: home network only, internet only, or both, and optionally
only some home networks or home services (picked from the devices the router
@@ -44,9 +48,6 @@ limits, live traffic and a LuCI admin that follows a modern design.
or within circles (family sees family, guests see guests). "Who reaches what"
sums up the rules and "Check access" walks them step by step for a device
and an address.
- **Find home devices** (optional, needs `umdns`): AirPlay, printers and shared
Macs at home show up on iPhone, iPad and Mac over the tunnel, published as
DNS-SD records in dnsmasq.
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
or total data limits, allowed hours, pause one person or everyone. Devices
drop off the tunnel at once (`awg syncconf`, no interface restart).
@@ -89,17 +90,45 @@ On the router:
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
The installer checks the firmware, installs AmneziaWG for it if needed, then
downloads the Dawnline package for your package manager from the latest
release, checks it against `sha256sums.txt` and installs it with its
dependencies. Then open **LuCI → Network → Dawnline** and run the setup wizard.
The installer checks the firmware, the clock, free space and DNS, lets you pick
a release (the latest is the default), shows the plan and asks before it
changes anything. It downloads the Dawnline package for your package manager,
checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware
if it is missing, then installs Dawnline with its dependencies and checks that
LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup
wizard.
Options:
Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
and the service state to `/etc/dawnline/installer-backups/` (the newest three
are kept); if a step fails, it puts them back. Packages are not rolled back: to
return to an older release, run the installer with `--tag`. Everything it does
is logged to `/tmp/dawnline-install.log`.
With options, download it first:
```sh
sh install.sh 0.1.0 # a given release
DAWNLINE_AWG=grey sh install.sh # AmneziaWG from 2Grey (default: Slava-Shchipunov, then 2Grey)
DAWNLINE_AWG=skip sh install.sh # never install AmneziaWG
wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh
sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
```
| Option | |
|---|---|
| `-y`, `--yes` | No questions: the latest release (or `--tag`) and the recommended choices |
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same |
| `--no-awg` | Same as `--awg skip` |
When GitHub is slow or blocked, the installer retries downloads through
`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
through a mirror:
```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases):
@@ -112,8 +141,32 @@ apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # Open
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
keys and history are kept, and a backup is made first.
**Remove**: **Settings → Remove Dawnline from this router** (keeps a backup),
then `opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
**Remove** on the router:
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
```
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
removal (the same as **Settings → Remove Dawnline from this router**), removes
the package and cleans up what is left. AmneziaWG stays installed, since other
tunnels may use it. After installing Dawnline again, restore the backup in
**Settings → Backups**. With options, download it first:
```sh
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
sh /tmp/dawnline-uninstall.sh --dry-run
```
| Option | |
|---|---|
| `-y`, `--yes` | Do not ask for confirmation |
| `-p`, `--purge` | Also delete the configuration, keys, history and every backup (`/etc/config/dawnline`, `/etc/dawnline`); no backup is made |
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
| `-n`, `--dry-run` | Show what would be removed; change nothing |
By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then
`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
## What Dawnline changes on the router
@@ -134,10 +187,11 @@ are kept in `/var/run/dawnline` and flushed to flash at most hourly.
```
package/luci-app-dawnline/
root/usr/share/ucode/dawnline/ ucode library (model, apply, live, ops, view, loop)
root/usr/share/ucode/dawnline/ ucode library: model (core), AmneziaWG (awg), apply, live,
ops, view, loop, portal
root/usr/share/rpcd/ucode/ luci.dawnline RPC object
root/usr/libexec/dawnline/ agent (usage, limits, presence) and updater
root/usr/share/dawnline/portal/ portal CGI and its (minified) assets
root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets
root/usr/bin/dawnline command line (`dawnline help`)
htdocs/ LuCI views and the generated module dawnline/app.js
web/ TypeScript sources of the admin UI and the portal
Binary file not shown.

After

Width:  |  Height:  |  Size: 287 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 418 KiB

After

Width:  |  Height:  |  Size: 427 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 277 KiB

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 301 KiB

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 291 KiB

After

Width:  |  Height:  |  Size: 274 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 KiB

After

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

After

Width:  |  Height:  |  Size: 147 KiB

+1278 -104
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -6,13 +6,13 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.3.0
PKG_VERSION:=0.4.2
PKG_RELEASE:=1
PKG_LICENSE:=MIT
LUCI_TITLE:=Dawnline - AmneziaWG access server
# AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not
# in the OpenWrt feeds: install.sh and the Updates page install a build made for
# in the OpenWrt feeds: install.sh and the Components page install a build made for
# the router's firmware. The portal's HTTPS needs any libustream TLS module and
# openssl-util; Settings offers to install them when the portal is turned on.
# Runtime dependencies only (control file Depends): the package ships scripts
@@ -34,6 +34,10 @@ define Package/luci-app-dawnline/conffiles
/etc/config/dawnline
endef
# /etc/dawnline (keys, backups, usage, history) survives a sysupgrade too:
# root/lib/upgrade/keep.d/dawnline-data (the package's own keep.d file is
# generated from conffiles).
define Package/luci-app-dawnline/prerm
#!/bin/sh
[ -n "$${IPKG_INSTROOT}" ] && exit 0
@@ -41,6 +45,11 @@ define Package/luci-app-dawnline/prerm
[ "$$1" = "upgrade" ] && exit 0
/etc/init.d/dawnline stop 2>/dev/null
/usr/bin/dawnline teardown 2>/dev/null
# The heartbeat check would point at a removed file.
grep -qs /usr/libexec/dawnline/ /etc/crontabs/root && {
sed -i '\#/usr/libexec/dawnline/#d' /etc/crontabs/root
/etc/init.d/cron restart 2>/dev/null
}
exit 0
endef
@@ -2,19 +2,28 @@
'use strict';
'require baseclass';
'require dom';
'require form';
'require poll';
'require rpc';
'require uci';
'require ui';
var An=Object.create;var Qt=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var Nn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var Hn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var In=(i,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nn(t))!Rn.call(i,s)&&s!==n&&Qt(i,s,{get:()=>t[s],enumerable:!(a=Pn(t,s))||a.enumerable});return i};var Bn=(i,t,n)=>(n=i!=null?An(zn(i)):{},In(t||!i||!i.__esModule?Qt(n,"default",{value:i,enumerable:!0}):n,i));var nn=Hn((en,tn)=>{"use strict";var Xt=(function(){var i=function($,N){var C=236,T=17,y=$,A=n[N],m=null,h=0,P=null,f=[],_={},O=function(M,E){h=y*4+17,m=(function(x){for(var D=new Array(x),k=0;k<x;k+=1){D[k]=new Array(x);for(var H=0;H<x;H+=1)D[k][H]=null}return D})(h),G(0,0),G(h-7,0),G(0,h-7),q(),S(),te(M,E),y>=7&&W(M),P==null&&(P=Te(y,A,f)),le(P,E)},G=function(M,E){for(var x=-1;x<=7;x+=1)if(!(M+x<=-1||h<=M+x))for(var D=-1;D<=7;D+=1)E+D<=-1||h<=E+D||(0<=x&&x<=6&&(D==0||D==6)||0<=D&&D<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=D&&D<=4?m[M+x][E+D]=!0:m[M+x][E+D]=!1)},B=function(){for(var M=0,E=0,x=0;x<8;x+=1){O(!0,x);var D=s.getLostPoint(_);(x==0||M>D)&&(M=D,E=x)}return E},S=function(){for(var M=8;M<h-8;M+=1)m[M][6]==null&&(m[M][6]=M%2==0);for(var E=8;E<h-8;E+=1)m[6][E]==null&&(m[6][E]=E%2==0)},q=function(){for(var M=s.getPatternPosition(y),E=0;E<M.length;E+=1)for(var x=0;x<M.length;x+=1){var D=M[E],k=M[x];if(m[D][k]==null)for(var H=-2;H<=2;H+=1)for(var V=-2;V<=2;V+=1)H==-2||H==2||V==-2||V==2||H==0&&V==0?m[D+H][k+V]=!0:m[D+H][k+V]=!1}},W=function(M){for(var E=s.getBCHTypeNumber(y),x=0;x<18;x+=1){var D=!M&&(E>>x&1)==1;m[Math.floor(x/3)][x%3+h-8-3]=D}for(var x=0;x<18;x+=1){var D=!M&&(E>>x&1)==1;m[x%3+h-8-3][Math.floor(x/3)]=D}},te=function(M,E){for(var x=A<<3|E,D=s.getBCHTypeInfo(x),k=0;k<15;k+=1){var H=!M&&(D>>k&1)==1;k<6?m[k][8]=H:k<8?m[k+1][8]=H:m[h-15+k][8]=H}for(var k=0;k<15;k+=1){var H=!M&&(D>>k&1)==1;k<8?m[8][h-k-1]=H:k<9?m[8][15-k-1+1]=H:m[8][15-k-1]=H}m[h-8][8]=!M},le=function(M,E){for(var x=-1,D=h-1,k=7,H=0,V=s.getMaskFunction(E),K=h-1;K>0;K-=2)for(K==6&&(K-=1);;){for(var ie=0;ie<2;ie+=1)if(m[D][K-ie]==null){var ce=!1;H<M.length&&(ce=(M[H]>>>k&1)==1);var Q=V(D,K-ie);Q&&(ce=!ce),m[D][K-ie]=ce,k-=1,k==-1&&(H+=1,k=7)}if(D+=x,D<0||h<=D){D-=x,x=-x;break}}},de=function(M,E){for(var x=0,D=0,k=0,H=new Array(E.length),V=new Array(E.length),K=0;K<E.length;K+=1){var ie=E[K].dataCount,ce=E[K].totalCount-ie;D=Math.max(D,ie),k=Math.max(k,ce),H[K]=new Array(ie);for(var Q=0;Q<H[K].length;Q+=1)H[K][Q]=255&M.getBuffer()[Q+x];x+=ie;var ge=s.getErrorCorrectPolynomial(ce),fe=r(H[K],ge.getLength()-1),Vt=fe.mod(ge);V[K]=new Array(ge.getLength()-1);for(var Q=0;Q<V[K].length;Q+=1){var Yt=Q+Vt.getLength()-V[K].length;V[K][Q]=Yt>=0?Vt.getAt(Yt):0}}for(var Jt=0,Q=0;Q<E.length;Q+=1)Jt+=E[Q].totalCount;for(var Et=new Array(Jt),ot=0,Q=0;Q<D;Q+=1)for(var K=0;K<E.length;K+=1)Q<H[K].length&&(Et[ot]=H[K][Q],ot+=1);for(var Q=0;Q<k;Q+=1)for(var K=0;K<E.length;K+=1)Q<V[K].length&&(Et[ot]=V[K][Q],ot+=1);return Et},Te=function(M,E,x){for(var D=l.getRSBlocks(M,E),k=d(),H=0;H<x.length;H+=1){var V=x[H];k.put(V.getMode(),4),k.put(V.getLength(),s.getLengthInBits(V.getMode(),M)),V.write(k)}for(var K=0,H=0;H<D.length;H+=1)K+=D[H].dataCount;if(k.getLengthInBits()>K*8)throw"code length overflow. ("+k.getLengthInBits()+">"+K*8+")";for(k.getLengthInBits()+4<=K*8&&k.put(0,4);k.getLengthInBits()%8!=0;)k.putBit(!1);for(;!(k.getLengthInBits()>=K*8||(k.put(C,8),k.getLengthInBits()>=K*8));)k.put(T,8);return de(k,D)};_.addData=function(M,E){E=E||"Byte";var x=null;switch(E){case"Numeric":x=p(M);break;case"Alphanumeric":x=u(M);break;case"Byte":x=c(M);break;case"Kanji":x=b(M);break;default:throw"mode:"+E}f.push(x),P=null},_.isDark=function(M,E){if(M<0||h<=M||E<0||h<=E)throw M+","+E;return m[M][E]},_.getModuleCount=function(){return h},_.make=function(){if(y<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),x=d(),D=0;D<f.length;D++){var k=f[D];x.put(k.getMode(),4),x.put(k.getLength(),s.getLengthInBits(k.getMode(),M)),k.write(x)}for(var H=0,D=0;D<E.length;D++)H+=E[D].dataCount;if(x.getLengthInBits()<=H*8)break}y=M}O(!1,B())},_.createTableTag=function(M,E){M=M||2,E=typeof E>"u"?M*4:E;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+E+"px;",x+='">',x+="<tbody>";for(var D=0;D<_.getModuleCount();D+=1){x+="<tr>";for(var k=0;k<_.getModuleCount();k+=1)x+='<td style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: 0px;",x+=" width: "+M+"px;",x+=" height: "+M+"px;",x+=" background-color: ",x+=_.isDark(D,k)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",x},_.createSvgTag=function(M,E,x,D){var k={};typeof arguments[0]=="object"&&(k=arguments[0],M=k.cellSize,E=k.margin,x=k.alt,D=k.title),M=M||2,E=typeof E>"u"?M*4:E,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,x.idLine truncated
`}return x%2&&M>0?fe.substring(0,fe.length-x-1)+Array(x+1).join("▀"):fe.substring(0,fe.length-1)};return _.createASCII=function(M,E){if(M=M||1,M<2)return ae(E);M-=1,E=typeof E>"u"?M*2:E;var x=_.getModuleCount()*M+E*2,D=E,k=x-E,H,V,K,ie,ce=Array(M+1).join("██"),Q=Array(M+1).join(" "),ge="",fe="";for(H=0;H<x;H+=1){for(K=Math.floor((H-D)/M),fe="",V=0;V<x;V+=1)ie=1,D<=V&&V<k&&D<=H&&H<k&&_.isDark(K,Math.floor((V-D)/M))&&(ie=0),fe+=ie?ce:Q;for(K=0;K<M;K+=1)ge+=fe+`
`}return ge.substring(0,ge.length-1)},_.renderTo2dContext=function(M,E){E=E||2;for(var x=_.getModuleCount(),D=0;D<x;D++)for(var k=0;k<x;k++)M.fillStyle=_.isDark(D,k)?"black":"white",M.fillRect(D*E,k*E,E,E)},_};i.stringToBytesFuncs={default:function($){for(var N=[],C=0;C<$.length;C+=1){var T=$.charCodeAt(C);N.push(T&255)}return N}},i.stringToBytes=i.stringToBytesFuncs.default,i.createStringToBytes=function($,N){var C=(function(){for(var y=F($),A=function(){var S=y.read();if(S==-1)throw"eof";return S},m=0,h={};;){var P=y.read();if(P==-1)break;var f=A(),_=A(),O=A(),G=String.fromCharCode(P<<8|f),B=_<<8|O;h[G]=B,m+=1}if(m!=N)throw m+" != "+N;return h})(),T=63;return function(y){for(var A=[],m=0;m<y.length;m+=1){var h=y.charCodeAt(m);if(h<128)A.push(h);else{var P=C[y.charAt(m)];typeof P=="number"?(P&255)==P?A.push(P):(A.push(P>>>8),A.push(P&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var $=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],N=1335,C=7973,T=21522,y={},A=function(m){for(var h=0;m!=0;)h+=1,m>>>=1;return h};return y.getBCHTypeInfo=function(m){for(var h=m<<10;A(h)-A(N)>=0;)h^=N<<A(h)-A(N);return(m<<10|h)^T},y.getBCHTypeNumber=function(m){for(var h=m<<12;A(h)-A(C)>=0;)h^=C<<A(h)-A(C);return m<<12|h},y.getPatternPosition=function(m){return $[m-1]},y.getMaskFunction=function(m){switch(m){case a.PATTERN000:return function(h,P){return(h+P)%2==0};case a.PATTERN001:return function(h,P){return h%2==0};case a.PATTERN010:return function(h,P){return P%3==0};case a.PATTERN011:return function(h,P){return(h+P)%3==0};case a.PATTERN100:return function(h,P){return(Math.floor(h/2)+Math.floor(P/3))%2==0};case a.PATTERN101:return function(h,P){return h*P%2+h*P%3==0};case a.PATTERN110:return function(h,P){return(h*P%2+h*P%3)%2==0};case a.PATTERN111:return function(h,P){return(h*P%3+(h+P)%2)%2==0};default:throw"bad maskPattern:"+m}},y.getErrorCorrectPolynomial=function(m){for(var h=r([1],0),P=0;P<m;P+=1)h=h.multiply(r([1,o.gexp(P)],0));return h},y.getLengthInBits=function(m,h){if(1<=h&&h<10)switch(m){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:"+m}else if(h<27)switch(m){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:"+m}else if(h<41)switch(m){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:"+m}else throw"type:"+h},y.getLostPoint=function(m){for(var h=m.getModuleCount(),P=0,f=0;f<h;f+=1)for(var _=0;_<h;_+=1){for(var O=0,G=m.isDark(f,_),B=-1;B<=1;B+=1)if(!(f+B<0||h<=f+B))for(var S=-1;S<=1;S+=1)_+S<0||h<=_+S||B==0&&S==0||G==m.isDark(f+B,_+S)&&(O+=1);O>5&&(P+=3+O-5)}for(var f=0;f<h-1;f+=1)for(var _=0;_<h-1;_+=1){var q=0;m.isDark(f,_)&&(q+=1),m.isDark(f+1,_)&&(q+=1),m.isDark(f,_+1)&&(q+=1),m.isDark(f+1,_+1)&&(q+=1),(q==0||q==4)&&(P+=3)}for(var f=0;f<h;f+=1)for(var _=0;_<h-6;_+=1)m.isDark(f,_)&&!m.isDark(f,_+1)&&m.isDark(f,_+2)&&m.isDark(f,_+3)&&m.isDark(f,_+4)&&!m.isDark(f,_+5)&&m.isDark(f,_+6)&&(P+=40);for(var _=0;_<h;_+=1)for(var f=0;f<h-6;f+=1)m.isDark(f,_)&&!m.isDark(f+1,_)&&m.isDark(f+2,_)&&m.isDark(f+3,_)&&m.isDark(f+4,_)&&!m.isDark(f+5,_)&&m.isDark(f+6,_)&&(P+=40);for(var W=0,_=0;_<h;_+=1)for(var f=0;f<h;f+=1)m.isDark(f,_)&&(W+=1);var te=Math.abs(100*W/h/h-50)/5;return P+=te*10,P},y})(),o=(function(){for(var $=new Array(256),N=new Array(256),C=0;C<8;C+=1)$[C]=1<<C;for(var C=8;C<256;C+=1)$[C]=$[C-4]^$[C-5]^$[C-6]^$[C-8];for(var C=0;C<255;C+=1)N[$[C]]=C;var T={};return T.glog=function(y){if(y<1)throw"glog("+y+")";return N[y]},T.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return $[y]},T})();function r($,N){if(typeof $.length>"u")throw $.length+"/"+N;var C=(function(){for(var y=0;y<$.length&&$[y]==0;)y+=1;for(var A=new Array($.length-y+N),m=0;m<$.length-y;m+=1)A[m]=$[m+y];return A})(),T={};return T.getAt=function(y){return C[y]},T.getLength=function(){return C.length},T.multiply=function(y){for(var A=new Array(T.getLength()+y.getLength()-1),m=0;m<T.getLength();m+=1)for(var h=0;h<y.getLength();h+=1)A[m+h]^=o.gexp(o.glog(T.getAt(m))+o.glog(y.getAt(h)));return r(A,0)},T.mod=function(y){if(T.getLength() Line truncated
`),hostName:o,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:o};return n.dns[0]&&(l.dns1=n.dns[0]),n.dns[1]&&(l.dns2=n.dns[1]),l}function Zn(i){let t="";for(let n=0;n<i.length;n+=32768)t+=String.fromCharCode(...i.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xn(i){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let n=new t.Blob([i]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,i.length,!1),s.set(a,4),s}catch{return null}}async function sn(i,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(Qn(i,t))),s=n?await Xn(a):null;return`vpn://${Zn(s??a)}`}function Z(i){if(!i||i<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=i;for(;a>=1024&&n<t.length-1;)a/=1024,n++;return`${a>=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function $e(i){let t=i*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function ue(i,t=Date.now()/1e3){if(!i)return"never";let n=Math.max(0,Math.round(t-i));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(i*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function on(i){if(!i||i<0)return"—";let t=Math.floor(i/86400),n=Math.floor(i%86400/3600),a=Math.floor(i%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function Ne(i){let t=new Date(i*1e3),n=new Date,a=t.toDateString()===n.toDateString(),s=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?s:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${s}`}function _e(i){if(!i)return"";let[t,n,a]=i.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(i,t=Date.now()){if(!i)return null;let[n,a,s]=i.split("-").map(Number),o=new Date(n,a-1,s,23,59,59).getTime();return Math.ceil((o-t)/864e5)}var Ue={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var rn=["computer","phone","tablet","router","other"],Se={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Pt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Re(i){let t=i.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(n+a).toUpperCase()}function rt(i){let t=n=>n.disabled?3:n.online?0:n.handshake?1:2;return i.map((n,a)=>[n,a]).sort((n,a)=>t(n[0])-t(a[0])||n[1]-a[1]).map(([n])=>n)}var ln="https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl",ea="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",ta="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",na={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Qe=null;function aa(i){let t=window;return i.appendChild(e("link",{rel:"stylesheet",href:`${ln}.css`})),t.maplibregl?Promise.resolve(t.maplibregl):Qe||(Qe=new Promise((n,a)=>{let s=e("script",{src:`${ln}.js`});s.onload=()=>t.maplibregl?n(t.maplibregl):a(new Error("MapLibre failed to load")),s.onerror=()=>{Qe=null,a(new Error("Could not load the map library (no internet access from this browser?)"))},i.appendChild(s)}),Qe)}function lt(){let i=document.documentElement.getAttribute("data-darkmode");return i!=null?i==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function sa(i,t,n=48){let a=(i[0]+t[0])/2,s=(i[1]+t[1])/2,o=t[0]-i[0],r=t[1]-i[1],l=Math.hypot(o,r)||1,d=Math.min(.25*l,12),p=a-r/l*d,u=s+o/l*d,c=[];for(let b=0;b<=n;b++){let g=b/n,w=1-g;c.push([w*w*i[0]+2*w*g*p+g*g*t[0],w*w*i[1]+2*w*g*u+g*g*t[1]])}return c}function ia(i,t){let n=new Map;for(let a of i.geo.points){if(i.person&&a.person!==i.person||(t==="online"?!a.online:i.now-a.ts>na[t]))continue;let s=n.get(a.device);(!s||a.online&&!s.online||a.online===s.online&&a.ts>s.ts)&&n.set(a.device,a)}return[...n.values()]}var qe=class{constructor(t,n="online",a=380){this.cb=t;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.anim=0;this.data=null;this.fitted=!1;this.range=n,this.status=e("div",{class:"dl-map-status"}),this.el=e("div",{class:"dl-geomap",style:`height:${a}px`},this.status)}async mount(t){this.data=t;try{this.gl=await aa(this.el)}catch(n){this.status.textContent=n.message;return}this.map=new this.gl.Map({container:this.el,style:lt()?ea:t Line truncated
${c.detail}`:""}`,where:ut[c.src]??c.src,by:""}))].sort((c,b)=>c.ts-b.ts).map(({ts:c,...b})=>({time:new Date(c*1e3).toISOString(),...b})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${n}`;if(n==="json"){ve(d,JSON.stringify(r,null,2),"application/json");return}let p=["time","category","type","person","device","detail","where","by"],u=[p.join(","),...r.map(c=>p.map(b=>va(c[b])).join(","))].join(`
`);ve(d,u,"text/csv")}var ba=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Ce(i,t,n,a,s,o=!1){let r=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Xe.map(d=>e("option",{value:d,selected:d===s?"selected":null},Ge[d])),o?e("option",{value:"system",selected:s==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ba.map(([d,p])=>e("option",{value:d},p)));se(i,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),r]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[e("button",{class:"cbi-button cbi-button-neutral",click:X},"Cancel")," ",R("Clear",async()=>{let d=await U(async()=>{let p=o&&(r.value==="system"||r.value==="")?await z.serviceLogClear(l.value):{removed:0},u=r.value==="system"?{removed:0}:await z.logsClear({...n,category:r.value,older_days:l.value});return{removed:p.removed+u.removed}});d&&(X(),ne(d.removed?`${d.removed} event${d.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function Fe(i,t,n,a){let s=i==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:i==="person"?`Clears ${n}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";se(i==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},s)],[e("button",{class:"cbi-button cbi-button-neutral",click:X},"Cancel")," ",R("Reset",async()=>{await U(()=>z.usageClear(i,t),"Traffic history reset")&&(X(),a())},"negative")])}var mt=null;function xa(i){return i?new Date(i*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function un(i,t,n=!1){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},i),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>he(t,`${i} copied`)},[e("span",{},t),v("copy")])])}function gt(i,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},i),e("span",{class:"dl-kvrow-v"},t)])}function mn(i,t){if(/^\s*\[.+\]\s*$/.test(i))return e("span",{class:"dl-conf-sec"},i);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(i);if(!n)return document.createTextNode(i);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(i);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function wa(i){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,i.conf.split(`
`).flatMap((r,l)=>l?[`
`,mn(r,t)]:[mn(r,t)])),s=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(s,[v(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let o=new Blob([i.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},i.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${o} bytes · import it in the app`)]),R([v("download")," Download"],()=>ve(i.filename,i.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[v("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),s,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),he(i.conf,"Configuration copied")}},[v("copy"),"Copy"])]),n])])}async function It(i,t="file"){if(!i.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let n=await sn(i,`${i.server} · ${i.person} · ${i.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Oe(i.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},n),R("Copy",()=>he(n,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>wa(i)},s=e("div",{class:"dl-connect-body"}),o=e("div",{class:"dl-seg"}),r=l=>{o.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(s,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])o.appendChild(e("button",{type:"button","data-id":l,click:()=>r(l)},d));return r(t),e("div",{class:"dl-stack gap12"},[o,s])}function ya(i,t,n,a){mt?.close();let s=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[i,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},v("x"))]),e("div",{class:"dl-drawer-body"},t),n?e("div",{class:"dl-drawer-foot"},n):""]),o=e("div",{class:"dl-drawer-overlay dl-root",click:p=>{p.target===o&&l()}},s),r=p=>{p.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),o.classList.remove("open"),setTimeout(()=>o.remove(),220),mt===d&&(mt=null),a()}let d={close:l,panel:s};return document.addEventListener("keydown",r),document.body.appendChild(o),requestAnimationFrame(()=>o.classList.add("open")),mt=d,d}var gn={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function ka(i,t){let n=i.filter(a=>a.device===t&&gn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[s,o,r]=gn[a.type],l=a.type==="connect"?[a.detail?e("span",{class:"dl-muted"},` from ${a.detail}`):"",a.where?e("span",{class:"dl-muted"},` · ${a.where}`):""]:a.type==="roam"?[e("span",{class:"dl-muted"},` · ${a.detail??""}`)]:a.type==="device_added"||a.type==="device_removed"||a.type==="device_keys"?[e("span",{class:"dl-muted"},xe(a)==="portal"?" on the portal":xe(a)==="admin"?" by you":"")]:[],d=new Date(a.ts*1e3);return e("div",{class:`dl-dev-log-row${xe(a)==="admin"?" dl-ev-by-admin":""}`},[xe(a)==="admin"?e("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},v("admin")):e("span",{class:`dl-ev-tile ev ${s}`},v(r)),e("span",{class:"dl-row-main"},[e("span",{},o),...l]),e("span",{class:"dl-faint dl-nowrap",title:d.toLocaleString()},ue(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function $a(i){return i.disabled?e("span",{class:"dl-dstat"},"Disabled"):i.online?e("span",{class:"dl-dstat ok"},"Connected"):i.handshake?e("span",{class:"dl-dstat"},`Last seen ${ue(i.handshake)}`):e("span",{class:"dl-dstat warn"},"Waiting for the first connection")}async function De(i,t,n,a){let s=await U(()=>z.deviceConfig(t.id));if(!s)return;let o=t,r=i,l=await It(s),d=e("div",{class:"dl-drawer-title"}),p=e("div",{}),u=e("div",{}),c=e("div",{},e("div",{class:"dl-sub"},"Loading…")),b=[],g=async()=>{let h=await z.events(5e3).catch(()=>null);h&&(b=h.events.filter(P=>P.device===o.id),dom.content(c,ka(h.events,o.id)))},w=()=>{let h=a?.points.find(f=>f.device===o.id&&f.ip===o.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${o.online?" on":""}`},v(o.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},o.name),R([v("edit")],()=>Y(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Se[o.kind]}`])])]);let P=o.spark.reduce((f,_)=>f+_,0);dom.content(p,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),$a(o)]),e("div",{ Line truncated
`),d=e("div",{class:"dl-pgrid"},[s("Junk packets","zap",o?`${o} random packet${o===1?"":"s"} of ${i.jmin}–${i.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),s("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),s("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),s("Signatures","globe",r,["i1","i2","i3","i4","i5"]),s("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),s("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[v("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(n.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),he(l,"Parameters copied")}},"Copy as config")]),d])}var jt=(i,t)=>{let n=new URLSearchParams;i&&n.set("server",i),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},st=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await z.status(31),n=t.servers.length?null:await z.setupDefaults();return[t,n]}render([t,n]){if(this.st=t,!t.servers.length&&n)return this.wizard(n);let a=new URLSearchParams(location.search),s=a.get("section")??"",o=Ua[s]??s;return Sn.some(([r])=>r===o)&&(this.section=o),this.srvId=(t.servers.find(r=>r.id===a.get("server"))??t.servers[0]).id,dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),poll.add(async()=>{if(this.section!=="overview")return;let r=await z.status(31).catch(()=>null);if(!r||!r.servers.length)return;this.st=r;let l=this.current();dom.content(this.headEl,this.head(l)),this.paintTabs(),this.ov[l.id]?.update(r)},10),this.root}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await z.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=jt())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(n=>e("button",{type:"button",role:"tab",class:`dl-srvtab${n.id===t.id?" on":""}`,"aria-selected":n.id===t.id?"true":"false",click:()=>{n.id!==this.srvId&&(this.srvId=n.id,this.paint())}},[e("i",{class:`dot ${n.up?"ok":"bad"}`}),e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`:${n.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[v("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},Sn.map(([t,n])=>e("button",{type:"button",role:"tab","data-section":t,class:t===this.section?"on":"","aria-selected":t===this.section?"true":"false",click:()=>this.showSection(t)},n))))}go(t,n){let a=this.pp[this.current().id];if(n&&a)a.filter=n,a.el&&a.decorate();else if(n){let s=this.pp[this.current().id]=new Be;s.filter=n}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(n=>n.el),...Object.values(this.pp).map(n=>n.el)];for(let n of t)n&&this.bodyEl.contains(n)&&n.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(r=>{let l=r.dataset.section===t;r.classList.toggle("on",l),r.setAttribute("aria-selected",l?"true":"false")});let n=this.st,a=this.current(),o={overview:()=>{let r=this.ov[a.id];return r?(r.update(n),r.el):(this.ov[a.id]=new pt(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var p,u;let r=this.pp[a.id];if(r?.el)return r.poll(),r.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((p=this.pp)[u=a.id]??(p[u]=new Be)).embed(n,a.id).then(c=>{l.isConnected?dom.content(l,c):l.replaceChildren(c)}),l},connection:()=>this.connection(a),access:()=>this.access(a),disguise:()=>this.disguise(a),tunnel:()=>this.tunnel(a)}[t]();this.detachKept(),dom.content(this.bodyEl,o)}head(t){let n=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[v(l),...d]),s=`${t.endpoint||"—"}:${t.port}`,o=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[o?R([v("play")," Turn on"],async()=>{n.settings.paused_all&&!await U(()=>z.pauseAll(!1))||(t.enabled?await this.refresh():await this.save(t,{enabled Line truncated
`))]):"",h=y.length+(o?.update?1:0)+(r?.update?1:0),P=[s?.version?`OpenWrt ${s.version} · ${s.target}`:"",t.check?h?`${h} update${h===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${Ne(t.check.time)}`:""].filter(Boolean).join(" · ");dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Updates"),e("span",{class:"dl-faint"},P)]),R([v("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),g,j,A,m])}async runAwg(t,n,a){await re(a?`Install AmneziaWG ${a}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${n?":ru":""}`)}async runPkgs(t,n,a=t){await re(`Update ${n}?`,`${a.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&this.start(`pkgs:${t.join(",")}`)}async run(t){t!=="check"&&!await re(`Update ${t==="app"?"Dawnline":t}?`,"A backup is made first. The page reloads when it finishes.","Update")||this.start(t)}async start(t){if(await U(()=>z.updatesRun(t))){this.running=!0;let n=await z.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function Kt(i){return`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`}function Za(i,t,n,a=30){let s=i?new Date(`${i}T12:00:00`):new Date;return t==="day"?s.setDate(s.getDate()+n):t==="week"?s.setDate(s.getDate()+7*n):t==="month"?s.setMonth(s.getMonth()+n):t==="year"?s.setFullYear(s.getFullYear()+n):s.setDate(s.getDate()+a*n),Kt(s)}var Xa={internet:"Browse the internet through your router. No access to devices at home, and home cannot reach theirs.",lan:"Reach devices at home, and home reaches theirs. Internet stays on their own connection.",both:"Home devices and the internet, all through your router. Home reaches their devices too."},Lt=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.refreshSeq=0;this.refreshShown=0}async load(){this.id=new URLSearchParams(location.search).get("id")??"";let[t,n,a]=await Promise.all([z.status(30),z.events(5e3).catch(()=>({events:[]})),z.personUsage(this.id,30).catch(()=>null)]);return this.series=a?.person??[],this.devSeries=a?.devices??{},[t,n.events]}render([t,n]){this.st=t,this.events=n;let a=t.people.find(l=>l.id===this.id);if(!a)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=a;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let s=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Ze(a.server)},t.servers.find(l=>l.id===a.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Ze(a.server)},"People"),e("span",{},"/"),e("span",{},a.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let o=new URLSearchParams(location.search),r=o.get("device")&&a.devices.find(l=>l.id===o.get("device"));return r?setTimeout(()=>De(this.p,r,()=>this.refresh(),this.st.geo),50):o.get("add")&&setTimeout(()=>Ke(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),s}async refresh(t=!1){let n=++this.refreshSeq,[a,s,o]=await Promise.all([z.status(30).catch(()=>null),z.events(5e3).catch(()=>null),z.personUsage(this.id,30).catch(()=>null)]);if(!a||n<this.refreshShown)return;this.refreshShown=n,this.st=a,s&&(this.events=s.events),o&&(this.series=o.person,this.devSeries=o.devices);let r=a.people.find(l=>l.id===this.id);if(!r){t||(location.href=Ze(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var o;let a=await U(()=>z.personUpdate(this.p.id,t),n);if(!a)return;let s=this.st.people.findIndex(r=>r.id===this.p.id);(o=a.person).rate??(o.rate=this.p.rate),s>=0&&(this.st.people[s]=a.person),this.p=a.person,this.paint()}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}mapCard(){let t=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),this.st.geo.enabled?dt("30d",n=>this.map?.setRange(n),!1):"",R("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new qe({openPerson:()=>{},openDevice:(n,a)=>{let s=this.p.devices.find(o=>o.id===a);s&&De(this.p,s,()=>this.refresh(),this.st.geo)}},"30d",280),requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[t,this.map.el])):e("div",{class:"dl-panel flush"},[t,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them Line truncated
`)}d.push(w),c+=g-1}let u=R([v("more")],()=>we(u,[{label:"Export CSV",icon:v("download"),run:()=>Le(this.st,l,"csv",t.id)},{label:"Export JSON",icon:v("download"),run:()=>Le(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:v("trash"),danger:!0,run:()=>Ce(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>this.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},l.length>10?`latest 10 of ${l.length}`:""),e("span",{class:"dl-spacer"}),u]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},"Disabled"):t.online?e("span",{class:"dl-dstat ok"},"Connected"):t.handshake?e("span",{class:"dl-dstat"},`Last seen ${ue(t.handshake,this.st.now)}`):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},"Not set up yet")}deviceBars(t){let n=(this.devSeries[t]??[]).slice(-30),a=n.map(r=>r.rx+r.tx),s=Math.max(1,...a),o=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},n.map((r,l)=>{let d=e("i",{class:`${a[l]?"":"zero"}${l===n.length-1?" hi":""}`});return d.style.height=`${Math.max(8,a[l]/s*100)}%`,pe(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${o(r.day)}`:o(r.day)),e("div",{},Z(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=rt(t.devices).map(o=>{let r=()=>De(t,o,n,this.st.geo);return e("article",{class:`dl-dcard${o.online?" online":""}${o.disabled?" off":""}`},[e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},v(o.kind)),e("button",{type:"button",class:"dl-dcard-title",click:r},[e("b",{},o.name),this.deviceStatus(o),o.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),R([v("more")],r,"neutral",{title:`${o.name}: connect, rename, keys, remove`,class:"cbi-button cbi-button-neutral dl-icon-only"})]),o.handshake?e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},Z(o.month[0]+o.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(o.id)]):o.disabled?e("div",{class:"dl-sub"},`${Se[o.kind]} · created ${ue(o.created,this.st.now)} ${o.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>this.showDeviceQr(o)},[v("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(o)},[v("download"),"Config"])])])}),s=t.devices.length>=t.device_limit;a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Ke(t,n)},[e("span",{class:"dl-dslot-ic"},v("plus")),e("span",{class:"dl-stack"},[e("b",{},"Add device"),s?e("span",{class:"dl-sub"},`Over the limit · ${t.devices.length} of ${t.device_limit}`):""])])),dom.content(this.parts.devices,e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`)]),e("div",{class:"dl-dgrid"},a)]))}paintLimits(){let t=this.p,n=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(m=>e("button",{type:"button",role:"radio",class:t.access===m?"on":"","aria-checked":t.access===m?"true":"false",click:()=>t.access!==m&&this.patch({access:m},`Access: ${Ue[m]}`)},[v(m==="internet"?"globe":m==="lan"?"home":"shield"),m==="internet"?"Internet":m==="lan"?"Home":"Both"]))),a=ze(t.expires),s=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});s.addEventListener("change",()=>s.value&&this.patch({expires:s.value},`Access until ${_e(s.value)}`));let o=(m,h,P)=>{let f=Za(t.expires&&(a??-1)>=0?t.expires:"",m,h);return this.patch({expires:f},`Access until ${_e(f)}`),P},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([m,h,P])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>o(m,h,P)},P)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{s.showPicker()}catch{s.focus()}}},[v("calendar"),t.expires?_e(t.expires):"Date"]),s]),d={pause:"pause access",notify:"keep access",remove:"remove their devices"}[t.expire_action],p=e("div",{class:"dl-tile2"},[e("div",{class:"dl-tile2-label"},[e("span",{},"Access ends"),t.expires?e("span",{class:a!=null&&a<0?"dl-bad":a!=null&&a<=t.expire_warn?"dl-warn":"dl-ok"},a!=null&&a<0?"ended":`${a} day${a===1?"":"s"} left`):e("span",{class:"dl-faint"},"no end date")]),e("div",{class:"dl-chips-row"},[...r,l,t.expires?e("button",{type:"button",class:"dl-chipbtn",click:()=>this.patch({expires:""},"No end date")},"No end"):""]),e("div",{class:"dl-tile2-foot"},[e("span",{class:"dl-muted"},`When it ends: ${d}${t.expire_warn?`, warn ${t.expire_warn} day${t.expire_warn===1?"":"s"} before`:""}`),e("a" Line truncated
var Oa=Object.create;var Gn=Object.defineProperty;var ja=Object.getOwnPropertyDescriptor;var Ua=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ga=Object.prototype.hasOwnProperty;var qa=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Fa=(n,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ua(t))!Ga.call(n,r)&&r!==o&&Gn(n,r,{get:()=>t[r],enumerable:!(a=ja(t,r))||a.enumerable});return n};var Ka=(n,t,o)=>(o=n!=null?Oa(Wa(n)):{},Fa(t||!n||!n.__esModule?Gn(o,"default",{value:n,enumerable:!0}):o,n));var eo=qa((Zn,Xn)=>{"use strict";var Qn=(function(){var n=function(w,I){var C=236,T=17,b=w,A=o[I],u=null,f=0,N=null,P=[],H={},J=function(M,E){f=b*4+17,u=(function(k){for(var z=new Array(k),y=0;y<k;y+=1){z[y]=new Array(k);for(var B=0;B<k;B+=1)z[y][B]=null}return z})(f),W(0,0),W(f-7,0),W(0,f-7),G(),$(),oe(M,E),b>=7&&q(M),N==null&&(N=me(b,A,P)),O(N,E)},W=function(M,E){for(var k=-1;k<=7;k+=1)if(!(M+k<=-1||f<=M+k))for(var z=-1;z<=7;z+=1)E+z<=-1||f<=E+z||(0<=k&&k<=6&&(z==0||z==6)||0<=z&&z<=6&&(k==0||k==6)||2<=k&&k<=4&&2<=z&&z<=4?u[M+k][E+z]=!0:u[M+k][E+z]=!1)},te=function(){for(var M=0,E=0,k=0;k<8;k+=1){J(!0,k);var z=r.getLostPoint(H);(k==0||M>z)&&(M=z,E=k)}return E},$=function(){for(var M=8;M<f-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var E=8;E<f-8;E+=1)u[6][E]==null&&(u[6][E]=E%2==0)},G=function(){for(var M=r.getPatternPosition(b),E=0;E<M.length;E+=1)for(var k=0;k<M.length;k+=1){var z=M[E],y=M[k];if(u[z][y]==null)for(var B=-2;B<=2;B+=1)for(var Y=-2;Y<=2;Y+=1)B==-2||B==2||Y==-2||Y==2||B==0&&Y==0?u[z+B][y+Y]=!0:u[z+B][y+Y]=!1}},q=function(M){for(var E=r.getBCHTypeNumber(b),k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[Math.floor(k/3)][k%3+f-8-3]=z}for(var k=0;k<18;k+=1){var z=!M&&(E>>k&1)==1;u[k%3+f-8-3][Math.floor(k/3)]=z}},oe=function(M,E){for(var k=A<<3|E,z=r.getBCHTypeInfo(k),y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<6?u[y][8]=B:y<8?u[y+1][8]=B:u[f-15+y][8]=B}for(var y=0;y<15;y+=1){var B=!M&&(z>>y&1)==1;y<8?u[8][f-y-1]=B:y<9?u[8][15-y-1+1]=B:u[8][15-y-1]=B}u[f-8][8]=!M},O=function(M,E){for(var k=-1,z=f-1,y=7,B=0,Y=r.getMaskFunction(E),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var ce=0;ce<2;ce+=1)if(u[z][V-ce]==null){var be=!1;B<M.length&&(be=(M[B]>>>y&1)==1);var X=Y(z,V-ce);X&&(be=!be),u[z][V-ce]=be,y-=1,y==-1&&(B+=1,y=7)}if(z+=k,z<0||f<=z){z-=k,k=-k;break}}},F=function(M,E){for(var k=0,z=0,y=0,B=new Array(E.length),Y=new Array(E.length),V=0;V<E.length;V+=1){var ce=E[V].dataCount,be=E[V].totalCount-ce;z=Math.max(z,ce),y=Math.max(y,be),B[V]=new Array(ce);for(var X=0;X<B[V].length;X+=1)B[V][X]=255&M.getBuffer()[X+k];k+=ce;var Se=r.getErrorCorrectPolynomial(be),Ce=s(B[V],Se.getLength()-1),jn=Ce.mod(Se);Y[V]=new Array(Se.getLength()-1);for(var X=0;X<Y[V].length;X+=1){var Un=X+jn.getLength()-Y[V].length;Y[V][X]=Un>=0?jn.getAt(Un):0}}for(var Wn=0,X=0;X<E.length;X+=1)Wn+=E[X].totalCount;for(var gn=new Array(Wn),Nt=0,X=0;X<z;X+=1)for(var V=0;V<E.length;V+=1)X<B[V].length&&(gn[Nt]=B[V][X],Nt+=1);for(var X=0;X<y;X+=1)for(var V=0;V<E.length;V+=1)X<Y[V].length&&(gn[Nt]=Y[V][X],Nt+=1);return gn},me=function(M,E,k){for(var z=l.getRSBlocks(M,E),y=d(),B=0;B<k.length;B+=1){var Y=k[B];y.put(Y.getMode(),4),y.put(Y.getLength(),r.getLengthInBits(Y.getMode(),M)),Y.write(y)}for(var V=0,B=0;B<z.length;B+=1)V+=z[B].dataCount;if(y.getLengthInBits()>V*8)throw"code length overflow. ("+y.getLengthInBits()+">"+V*8+")";for(y.getLengthInBits()+4<=V*8&&y.put(0,4);y.getLengthInBits()%8!=0;)y.putBit(!1);for(;!(y.getLengthInBits()>=V*8||(y.put(C,8),y.getLengthInBits()>=V*8));)y.put(T,8);return F(y,z)};H.addData=function(M,E){E=E||"Byte";var k=null;switch(E){case"Numeric":k=p(M);break;case"Alphanumeric":k=c(M);break;case"Byte":k=m(M);break;case"Kanji":k=v(M);break;default:throw"mode:"+E}P.push(k),N=null},H.isDark=function(M,E){if(M<0||f<=M||E<0||f<=E)throw M+","+E;return u[M][E]},H.getModuleCount=function(){return f},H.make=function(){if(b<1){for(var M=1;M<40;M++){for(var E=l.getRSBlocks(M,A),k=d(),z=0;z<P.length;z++){var y=P[z];k.put(y.getMode(),4),k.put(y.getLength(),r.getLengthInBits(y.getMode(),M)),y.write(k)}for(var B=0,z=0;z<E.length;z++)B+=E[z].dataCount;if(k.getLengthInBits()<=B*8)break}b=M}J(!1,te())},H.createTableTag=function(M,E){M=M||2,E=typeof E>"u"?M*4:E;var k="";k+='<table style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: "+E+"px;",k+='">',k+="<tbody>";for(var z=0;z<H.getModuleCount();z+=1){k+="<tr>";for(var y=0;y<H.getModuleCount();y+=1)k+='<td style="',k+=" border-width: 0px; border-style: none;",k+=" border-collapse: collapse;",k+=" padding: 0px; margin: 0px;",k+=" width: "+M+"px;",k+=" height: "+M+"px;",k+=" background-color: ",k+=H.isDark(z,y)?"#000000":"#ffffff",k+=";",k+='"/>';k+="</tr>"}return k+="</tbody>",k+="</table>",k},H.createSvgTag=function(M,E,k,z){var y={};typeof arguments[0]=="object"&&(y=arguments[0],M=y.cellSize,E=y.margin,k=y.alt,z=y.title),M=M||2,E=typeof E>"u"?M*4:E,k=typeof k=="string"?{text:k}:k||{},k.text=k.text||null,k.id=kLine truncated
`}return k%2&&M>0?Ce.substring(0,Ce.length-k-1)+Array(k+1).join("▀"):Ce.substring(0,Ce.length-1)};return H.createASCII=function(M,E){if(M=M||1,M<2)return ge(E);M-=1,E=typeof E>"u"?M*2:E;var k=H.getModuleCount()*M+E*2,z=E,y=k-E,B,Y,V,ce,be=Array(M+1).join("██"),X=Array(M+1).join(" "),Se="",Ce="";for(B=0;B<k;B+=1){for(V=Math.floor((B-z)/M),Ce="",Y=0;Y<k;Y+=1)ce=1,z<=Y&&Y<y&&z<=B&&B<y&&H.isDark(V,Math.floor((Y-z)/M))&&(ce=0),Ce+=ce?be:X;for(V=0;V<M;V+=1)Se+=Ce+`
`}return Se.substring(0,Se.length-1)},H.renderTo2dContext=function(M,E){E=E||2;for(var k=H.getModuleCount(),z=0;z<k;z++)for(var y=0;y<k;y++)M.fillStyle=H.isDark(z,y)?"black":"white",M.fillRect(z*E,y*E,E,E)},H};n.stringToBytesFuncs={default:function(w){for(var I=[],C=0;C<w.length;C+=1){var T=w.charCodeAt(C);I.push(T&255)}return I}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(w,I){var C=(function(){for(var b=R(w),A=function(){var $=b.read();if($==-1)throw"eof";return $},u=0,f={};;){var N=b.read();if(N==-1)break;var P=A(),H=A(),J=A(),W=String.fromCharCode(N<<8|P),te=H<<8|J;f[W]=te,u+=1}if(u!=I)throw u+" != "+I;return f})(),T=63;return function(b){for(var A=[],u=0;u<b.length;u+=1){var f=b.charCodeAt(u);if(f<128)A.push(f);else{var N=C[b.charAt(u)];typeof N=="number"?(N&255)==N?A.push(N):(A.push(N>>>8),A.push(N&255)):A.push(T)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],I=1335,C=7973,T=21522,b={},A=function(u){for(var f=0;u!=0;)f+=1,u>>>=1;return f};return b.getBCHTypeInfo=function(u){for(var f=u<<10;A(f)-A(I)>=0;)f^=I<<A(f)-A(I);return(u<<10|f)^T},b.getBCHTypeNumber=function(u){for(var f=u<<12;A(f)-A(C)>=0;)f^=C<<A(f)-A(C);return u<<12|f},b.getPatternPosition=function(u){return w[u-1]},b.getMaskFunction=function(u){switch(u){case a.PATTERN000:return function(f,N){return(f+N)%2==0};case a.PATTERN001:return function(f,N){return f%2==0};case a.PATTERN010:return function(f,N){return N%3==0};case a.PATTERN011:return function(f,N){return(f+N)%3==0};case a.PATTERN100:return function(f,N){return(Math.floor(f/2)+Math.floor(N/3))%2==0};case a.PATTERN101:return function(f,N){return f*N%2+f*N%3==0};case a.PATTERN110:return function(f,N){return(f*N%2+f*N%3)%2==0};case a.PATTERN111:return function(f,N){return(f*N%3+(f+N)%2)%2==0};default:throw"bad maskPattern:"+u}},b.getErrorCorrectPolynomial=function(u){for(var f=s([1],0),N=0;N<u;N+=1)f=f.multiply(s([1,i.gexp(N)],0));return f},b.getLengthInBits=function(u,f){if(1<=f&&f<10)switch(u){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:"+u}else if(f<27)switch(u){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:"+u}else if(f<41)switch(u){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:"+u}else throw"type:"+f},b.getLostPoint=function(u){for(var f=u.getModuleCount(),N=0,P=0;P<f;P+=1)for(var H=0;H<f;H+=1){for(var J=0,W=u.isDark(P,H),te=-1;te<=1;te+=1)if(!(P+te<0||f<=P+te))for(var $=-1;$<=1;$+=1)H+$<0||f<=H+$||te==0&&$==0||W==u.isDark(P+te,H+$)&&(J+=1);J>5&&(N+=3+J-5)}for(var P=0;P<f-1;P+=1)for(var H=0;H<f-1;H+=1){var G=0;u.isDark(P,H)&&(G+=1),u.isDark(P+1,H)&&(G+=1),u.isDark(P,H+1)&&(G+=1),u.isDark(P+1,H+1)&&(G+=1),(G==0||G==4)&&(N+=3)}for(var P=0;P<f;P+=1)for(var H=0;H<f-6;H+=1)u.isDark(P,H)&&!u.isDark(P,H+1)&&u.isDark(P,H+2)&&u.isDark(P,H+3)&&u.isDark(P,H+4)&&!u.isDark(P,H+5)&&u.isDark(P,H+6)&&(N+=40);for(var H=0;H<f;H+=1)for(var P=0;P<f-6;P+=1)u.isDark(P,H)&&!u.isDark(P+1,H)&&u.isDark(P+2,H)&&u.isDark(P+3,H)&&u.isDark(P+4,H)&&!u.isDark(P+5,H)&&u.isDark(P+6,H)&&(N+=40);for(var q=0,H=0;H<f;H+=1)for(var P=0;P<f;P+=1)u.isDark(P,H)&&(q+=1);var oe=Math.abs(100*q/f/f-50)/5;return N+=oe*10,N},b})(),i=(function(){for(var w=new Array(256),I=new Array(256),C=0;C<8;C+=1)w[C]=1<<C;for(var C=8;C<256;C+=1)w[C]=w[C-4]^w[C-5]^w[C-6]^w[C-8];for(var C=0;C<255;C+=1)I[w[C]]=C;var T={};return T.glog=function(b){if(b<1)throw"glog("+b+")";return I[b]},T.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return w[b]},T})();function s(w,I){if(typeof w.length>"u")throw w.length+"/"+I;var C=(function(){for(var b=0;b<w.length&&w[b]==0;)b+=1;for(var A=new Array(w.length-b+I),u=0;u<w.length-b;u+=1)A[u]=w[u+b];return A})(),T={};return T.getAt=function(b){return C[b]},T.getLength=function(){return C.length},T.multiply=function(b){for(var A=new Array(T.getLength()+b.getLength()-1),u=0;u<T.getLength();u+=1)for(var f=0;f<b.getLength();f+=1)A[u+f]^=i.gexp(i.glog(T.getAt(u))+i.glog(b.getAt(f)));return s(A,0)},T.mod=function(b){if(T.ge Line truncated
`)}function rr(n){let t=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:t,devices:o}}function je(n,t,o,a="",r=[]){let i=rr(n),s=[...t.map(c=>({ts:c.ts,category:$t(c.type),type:c.type,person:c.person?i.people.get(c.person)??c.pname??c.person:"",device:c.device?i.devices.get(c.device)??c.dname??c.device:"",detail:c.detail??"",where:c.where??"",by:Le(c)??""})),...r.map(c=>({ts:c.ts,category:"system",type:`${c.src}.${c.level}`,person:"",device:"",detail:`${c.who?`${c.who} `:""}${c.msg}${c.detail?`
${c.detail}`:""}`,where:_t[c.src]??c.src,by:""}))].sort((c,m)=>c.ts-m.ts).map(({ts:c,...m})=>({time:new Date(c*1e3).toISOString(),...m})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){$e(d,JSON.stringify(s,null,2),"application/json");return}$e(d,ro(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var ir=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],io=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Fe(n,t,o,a,r,i=!1){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...pt.map(d=>e("option",{value:d,selected:d===r?"selected":null},nt[d])),i?e("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=e("select",{class:"cbi-input-select"},ir.map(([d,p])=>e("option",{value:d},p)));ae(n,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),l])],[se()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await S.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(p){Q(ve(p),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await S.serviceLogClear(l.value)).removed}catch(p){le(),Q(`${s.value==="system"?"":`Activity: ${io(d).toLowerCase()}. `}The service log was not cleared: ${ve(p)}`,"error",1e4),a();return}le(),Q(io(d),"success",3e3),a()},"negative")])}function ut(n,t,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[e("p",{class:"dl-muted"},r)],[se()," ",D("Reset",async()=>{await U(()=>S.usageClear(n,t),"Traffic history reset")&&(le(),a())},"negative")])}function fe(n,t,o){let a=e("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":t,click:()=>{let r=!a.classList.contains("on");Sn(a,r),o?.(r)}},e("i"));return a}function Sn(n,t){n.classList.toggle("on",t),n.setAttribute("aria-checked",t?"true":"false")}var Ee=n=>n.classList.contains("on");function xe(n,t,o={}){n.some(([i])=>i===t)||(n=[...n,[t,t]]);let a=e("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":t}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(e("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function Ue(n,t,o,a={}){return e("button",{type:"button",...a,class:`dl-chipbtn${t?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":t?"true":"false",click:o},n)}function Wt(n,t){n.classList.toggle("on",t),n.setAttribute("aria-pressed",t?"true":"false")}function re(n,t={}){return e("input",{type:"text",class:"cbi-input-text",value:n,...t})}var sr={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:""},lr={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 dr(n){let t={};for(let[o,a]of Object.entries(lr))n[o]!=null&&n[o]!==""&&(t[a]=String(n[o]));return t}function cr(n,t){let o=n.amnezia,a=o.obfuscation??{},r=d=>a[d]!=null&&a[d]!==""?String(a[d]):sr[d],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...dr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function pr(n){let t="";for(let o=0;o<n.length;o+=32768)t+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ur(n){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let o=new t.Blob([n]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Cn(n,t,o=!0){let a=new TextEncoder().encode(JSON.stringify(cr(n,t))),r=o?await ur(a):null;return`vpn://${pr(r??a)}`}var lo=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Et=n=>lo.find(t=>t.id===n),mr={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)."},hr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function so(n,t){return e("span",{class:"dl-dots",title:`${t}: ${n} of 4`},[e("span",{class:"dl-dots-label"},t),e("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>e("i",{class:o<n?"on":""})))])}function Gt(n,t,o,a,r=!0){let i=e("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,lo.map(l=>{let d=!l.needs||n[l.needs],p=l.id===t;return e("button",{type:"button",role:"radio","aria-checked":p?"true":"false","aria-disabled":d?null:"true",class:`dl-method${p?" on":""}${d?"":" off"}`,click:()=>{!d||p||(t=l.id,s(),o(l.id))}},[e("div",{class:"dl-method-head"},[e("span",{class:"dl-method-ic"},g(l.ic)),e("b",{},l.title),l.id===a?e("span",{class:"dl-pill ok"},"Current"):""]),e("p",{},l.text),e("div",{class:"dl-method-meters"},[so(l.stealth,"Stealth"),so(l.speed,"Speed")]),e("div",{class:"dl-method-foot"},d?[g("phone"),e("span",{},l.apps)]:[g("alert"),e("span",{},(r?mr:hr)[l.needs])])])}));return s(),i}function co(n,t,o,a){return e("div",{class:"dl-corehead"},[e("h3",{},n),e("span",{class:`dl-pill ${t}`},o),a?e("span",{class:"dl-sub"},a):""])}var po=[["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 fr(n){let t=p=>n[p]!=null&&n[p]!=="",o=po.filter(([p])=>t(p));if(!o.length)return null;let a=(p,c)=>e("span",{class:"dl-pv"},[e("i",{},c),e("b",{},p==="header_protection_key"?`${n[p].slice(0,6)}••••`:n[p])]),r=(p,c,m,v)=>{let h=po.filter(([x])=>v.includes(x)&&t(x));return h.length?e("div",{class:"dl-pgroup"},[e("div",{class:"dl-pgroup-head"},[g(c),e("b",{},p)]),e("p",{},m),e("div",{class:"dl-pvals"},h.map(([x,R])=>a(x,R)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([p,c])=>`${c} = ${n[p]}`).join(`
`),d=e("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(o.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:p=>{p.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),d])}function uo(n,t){if(/^\s*\[.+\]\s*$/.test(n))return e("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return e("span",{},[e("span",{class:"dl-conf-k"},o[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function gr(n){let t=!1,o=e("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,uo(s,t)]:[uo(s,t)])),r=e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),t=!t,dom.content(r,[g(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[g("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},n.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([g("download")," Download"],()=>$e(n.filename,n.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),r,e("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[g("copy"),"Copy"])]),o])])}async function vr(n,t="file"){if(!n.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Cn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>e("div",{class:"dl-qr-pane"},[qe(ct(n.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},o),D("Copy",()=>pe(o,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>gr(n)},r=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,a[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(e("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(t),e("div",{class:"dl-stack gap12"},[i,r])}async function br(n,t,o,a){let r=Et(o),s=n.st.people.filter(d=>d.server===t.id).reduce((d,p)=>d+p.devices.length,0);await ne(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await U(()=>S.serverObfuscation(t.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 xr(n,t){let o=n.st,a=re(String(t.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=re(String(t.mtu??""),{placeholder:"1380",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=re(String(t.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Et(t.preset)?t.preset:void 0,l=s??"standard",d=D("",()=>br(n,t,l,l===s),"neutral"),p=()=>dom.content(d,l===s?[g("reset")," Generate new values"]:[`Switch to ${Et(l).title}`]);p();let c=o.people.filter(v=>v.server===t.id).reduce((v,h)=>v+h.devices.length,0),m=o.awg_state?.tools!==!1;return kt("",[co("AmneziaWG",t.up?"ok":"bad",t.up?"Running":"Not running",`${t.ifname} · ${c} device${c===1?"":"s"}`),he("globe","Listening","Where devices reach this core from the internet",[Z("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",[Z("MTU",r,"Lower it if some sites hang on mobile networks."),Z("Keep-alive",i,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Gt(o.awg,l,v=>{l=v,p()},s,m),m&&!o.awg.v3?dt("info",["This router runs an older AmneziaWG. ",e("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",fr(t.obf??{})??"",e("div",{class:"dl-row-end"},[e("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),e("details",{class:"dl-params"},[e("summary",{},[g("chevron"),e("span",{},"Tunnel"),e("span",{class:"dl-pcount"},"3")]),e("div",{class:"dl-params-body"},[Z("Interface",e("span",{class:"dl-mono"},`${t.ifname} · router ${t.address}`)),Z("Tunnel subnet",e("span",{class:"dl-mono"},t.subnet),"Device addresses come from it."),Z("Server public key",e("span",{class:"dl-keyrow"},[e("code",{class:"dl-mono"},t.public_key),D([g("copy")],()=>pe(t.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[e("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:i.value},"AmneziaWG saved"),"positive")])}function wr(n){let t=Et(n.preset),o=n.obf??{},a=(s,l)=>e("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>e("i",{class:d<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2","s3","s4"].filte Line truncated
`),"Log copied"))]),c,m]),[v],"wide"),x([e("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let _=o??null,j=o?.id,w,I=0,C=u=>{j!==u.id&&(j=u.id,t.onJob?.(u))};if(o)t.onJob?.(o);else try{let u=await S.updatesStatus().catch(()=>null);w=u?.job?.id,I=u?.now??0;let f=await S.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==w&&(_=f.job,C(f.job))}catch(u){return h=[ve(u)],c.textContent=h[0],dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},ve(u))])),x([R(!0)]),Q(ve(u),"error"),null}let T=null,b=0;for(;;){if(await Mo(1e3),T=await S.updatesStatus().catch(()=>null),!T){if(++b>60)break;continue}b=0;let u=T.job;if(!u||!To(u,j,w,I)){if(Date.now()-i>15e3)break;continue}if(C(u),_=u,u.log.length){h=u.log;let f=c.scrollTop+c.clientHeight>=c.scrollHeight-8;c.textContent=h.join(`
`),f&&(c.scrollTop=c.scrollHeight)}if(l.textContent=Co(u,t.version??""),!l.isConnected&&l.textContent&&s.after(l),p.textContent=So((u.finished??T.now)-u.started),u.state==="running"){d.hidden=!u.phase,d.textContent=u.phase;continue}break}if(c.scrollTop=c.scrollHeight,d.hidden=!1,!_||_.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(m,e("div",{class:"dl-comp-status warn"},[g("alert"),e("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),x([R()]),t.onDone?.(T),_;if(_.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(m,e("div",{class:"dl-comp-status bad"},[g("x"),e("span",{},[e("b",{},_.error??"Operation failed"),r?"":". Nothing else was changed."])])),x([D("Copy log",()=>pe(h.join(`
`),"Log copied")),R(!0)]),Q(`${Qt[a]??"Update"}: ${_.error??"failed"}`,"error"),t.onDone?.(T),_;if(d.className="dl-pill ok",d.textContent="Finished",r&&T){let u=Lo(T,a);if(dom.content(m,e("div",{class:`dl-comp-status ${u.tone}`},[g(u.tone==="ok"?"check":u.tone==="warn"?"alert":"download"),e("span",{},u.text)])),Q(u.text,u.tone==="warn"?"warning":"success"),t.onDone?.(T),u.update&&t.onUpdate){let f=T;x([R(),D(`Update to ${u.update}`,()=>t.onUpdate(f),"positive")])}else x([R()]),u.tone==="ok"&&setTimeout(()=>m.isConnected&&le(),1200);return _}if(a==="app"&&_.to){let u=_.to,f=e("span",{},"Waiting for the router to restart its services…");dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},[e("b",{},`Dawnline ${u} is installed. `),f])]));let N=()=>{ui.menu?.flushCache(),location.reload()};x([R(),D("Reload now",N,"positive")]),Q(`Dawnline updated to ${u}`,"success",6e3);for(let P=1;P<=30;P++)if(f.textContent=`Waiting for the router to restart its services (${P} of 30)…`,await Mo(1500),(await S.updatesStatus().catch(()=>null))?.version===u)return f.textContent="Services are back. Reloading…",setTimeout(N,800),_;return f.textContent="Services restarted. Reload the page to use the new version.",_}let A=a==="pkgs"?`Updated ${[..._.result?.pkgs?.updated??[],..._.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${_.to?` ${_.to}`:""} is installed`:"Operation completed";return dom.content(m,e("div",{class:"dl-comp-status ok"},[g("check"),e("span",{},A)])),x([R()]),Q(A,"success"),t.onDone?.(T),_}var Rr={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Po(n,t,o,a){return!await ne(`Install ${t}?`,o,"Install")||(await Mt(n,{title:`Installing ${t}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function Xt(n){return Po("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Pt(n,t,o){return n==="awg"?Xt(o):t.length?Po(`pkgs:${t.join(",")}`,Rr[n],`${t.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function Do(n,t){if(n==="awg")return Xt(t);let o=await U(()=>S.updatesStatus());return o?Pt(n,o.needs?.[n]??[],t):!1}var Hr=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Ir={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ao(n,t,o){let a=n.id,r=t,i=e("div",{class:"dl-stack gap16"},e("section",{class:"dl-setsec"},e("div",{class:"dl-setsec-body"},e("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",p=!0,c=!0,m="all",v=!1,h=$o(r,a,o),x=new Set,R="",_=()=>JSON.stringify([c,l,l?"":d,p,[...x].sort()]),j=()=>s.detected.lan||s.saved.lan||"",w=()=>(l?s.detected.wan||s.saved.wan:d)||"",I=()=>new Map(s.devices.map($=>[$.name,$])),C=()=>{let $=I();return[...p&&j()?[j()]:[],...[...x].filter(q=>q!==j())].filter(q=>q!==w()).map(q=>$.get(q)??{name:q,nets:[],missing:!0})},T=($,G)=>{s=$,G&&(l=$.config.auto_wan,d=$.config.wan_device||$.detected.wan||$.saved.wan||"",p=$.config.auto_lan,c=$.config.lan_like,m=$.config.mesh??($.config.device_mesh?"all":"off"),x=new Set($.config.lan_devices),R=_()),W()},b=async $=>{let G=await S.interfaces(a).catch(q=>(Q(q.message,"error"),null));G&&T(G,$)};function A($){let G=p&&$.name===j(),q=!!$.own||!!$.master||$.name===w()||G;return G||x.has($.name)||!q&&($.nets.length>0||!!$.missing)}function u($){let G=p&&$.name===j(),q=$.name===w(),oe=!G&&x.has($.name),F=!(!!$.own||!!$.master||q||G)&&($.nets.length>0||oe||!!$.missing),me=(oe||G)&&!$.zone&&!$.missing,ie=$.missing?"Not present right now":$.own?"This server":$.master?`Port of ${$.master}`:q?`Internet${$.zone?` · zone ${$.zone}`:""}`:$.nets.length?$.nets.join(", "):"No IPv4 network",ge=e("button",{type:"button",class:`dl-if${oe?" sel":""}${G?" auto":""}${!F&&!oe&&!G?" off":""}${me?" warn":""}`,"aria-pressed":oe||G?"true":"false","aria-disabled":F?null:"true",click:()=>{F&&(x.has($.name)?x.delete($.name):x.add($.name),W())}},[e("span",{class:"dl-if-ic"},g(Ir[$.kind]??"link")),e("span",{class:"dl-if-main"},[e("span",{class:"dl-if-name"},$.name),e("span",{class:"dl-if-sub"},ie)]),G?e("span",{class:"dl-if-badge ok"},"Auto"):oe?e("span",{class:"dl-if-check"},g("check")):""]);return ue(ge,()=>[e("div",{class:"dl-tip-title"},$.name),e("div",{class:"dl-muted"},[$.logical?`Interface ${$.logical}`:"No netifd interface",$.zone?` · zone ${$.zone}`:" · no firewall zone"]),$.members.length?e("div",{class:"dl-muted"},`Ports: ${$.members.join(", ")}`):"",$.nets.length?e("div",{class:"dl-mono"},$.nets.join(", ")):"",me?e("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",$.master?e("div",{class:"dl-muted"},`Choose ${$.master} to include it.`):""]),ge}function f(){let $=s.like_home;return!c||!s.config.lan Line truncated
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let p=/^(#{1,6})\s+(.*)$/.exec(d),c=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);p?(s(),t.push(e("h5",{},o(p[2])))):c?(r.length&&s(),a||(a=e("ul",{}),t.push(a)),a.appendChild(e("li",{},o(c[1])))):d.trim()?(a&&(a=null),r.push(d.trim())):s()}return i&&t.push(e("pre",{},i.join(`
`))),s(),t}function Zo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||t.push(a)}return t.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function zt(n,t,o,a){let r=e("div",{class:"dl-notes"},e("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=e("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([g("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",se("Close")],"wide");try{let l=await S.updatesNotes(n,t,a??"");s=Zo(l.body||"");let d=Yo(l.url);dom.content(i,[l.published?e("span",{class:"dl-pill"},Ae(l.published)):"",l.prerelease?e("span",{class:"dl-pill warn"},"Pre-release"):"",e("span",{class:"dl-spacer"}),d?e("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",g("open")]):""]),dom.content(r,s.trim()?Qo(s):e("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,e("p",{class:"dl-muted"},ve(l)))}}var Xo={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Hn=n=>n?Ae(n):"";function ri(n){let t=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return t||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function ta(n,t){let o=n.st,a=o.policy,r=o.kept?.app,i=t?.update&&t.tag?t.tag:o.version,s=v=>()=>zt("app",v,`What’s new in Dawnline ${v.replace(/^v/,"")}`),l=t?.tag&&(t.update||t.status==="latest")?ii(n,t.tag,t.update?o.version:""):null,d=t?.tag??i,p=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,c=(v,h)=>e("div",{class:"dl-stack gap4"},[e("span",{class:"dl-metric-label"},v),e("span",{class:"dl-comp-side-v"},h)]),m=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return e("section",{class:"dl-panel flush dl-comp-hero"},[e("div",{class:"dl-comp-hero-main"},[e("div",{class:"dl-comp-hero-head"},[e("span",{class:"dl-group-ic"},g("sunrise")),e("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",t,t?.latest??""),e("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),m,!0)]),e("div",{class:"dl-comp-verrow"},[e("div",{class:"dl-stack"},[e("div",{class:"dl-comp-big"},[o.version,t?.update?e("small",{},`→ ${t.latest}`):t?.status==="dev"&&t.latest?e("small",{class:"dl-faint"},`release ${t.latest}`):""]),e("span",{class:"dl-faint dl-comp-meta"},t?.error?"":t?.update?t.published?`released ${Hn(t.published)}`:"":t?.status==="dev"?"ahead of the latest release":t?`latest release${t.published?` · released ${Hn(t.published)}`:""}`:"not checked yet")])]),l?.items.length?e("div",{class:"dl-stack gap4"},[e("ul",{class:"dl-comp-bullets"},l.items.map(v=>e("li",{},v))),l.total>l.items.length?e("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",t?.error?e("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},t.error):"",t?.update?e("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",si(n)]),e("div",{class:"dl-comp-hero-side"},[c("Source",[g("globe"),e("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),c("Auto-update",[a.auto?ke("ok","On"):ke("","Off"),e("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Xo[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Xo[a.interval]}`:"checks off")]),c("Last check",o.check?[de(o.check.time,o.now),p>o.now?e("span",{class:"dl-faint"},`· next in ${st(p-o.now)}`):""]:["Never"]),c("Rollback",r?[e("span",{class:"dl-mono"},r.version),e("span",{class:"dl-faint"},"kept on flash")]:[e("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ii(n,t,o){if(n.notes.has(t))return n.notes.get(t)??null;n.notes.set(t,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await S.updatesNotes("app",t,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await S.updatesChanges(o,t).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>ri(a(l))),total:i.length};n.notes.set(t,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function si(n){let t=e("div",{class:"dl-params-body"}),o=e("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[e("summary",{},[g("chevron"),e("span",{},"Versions"),e("span",{class:"dl-sub"},"install any release")]),t]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&dn(n,t)}),n.versOpen&&dn(n,t),o}async function dn(n,t){let o=re("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=c=>{if(c=c.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(c))return Q("Enter a release tag like 0.3.1","warning");ea(n,c)};o.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),a(o.value))});let r=e("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=c=>{n.versPage=Math.max(1,n.versPage+c),dn(n,t)},l=c=>e("div",{class:"dl-comp-pager"},[e("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),e("span",{class:"dl-faint"},`Page ${i}`),e("button",{type:"button",class:"dl-linkbtn",disabled:c?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(t,[r,e("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await S.updatesReleases(i)).releases}catch(c){if(i!==n.versPage||!t.isConnected)return;dom.content(t,[r,e("div",{class:"dl-row-actions"},[e("span",{class:"dl-muted"},`Failed to load versions: ${ve(c)}`),D("Try again",()=>dn(n,t))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!t.isConnected)return}if(!d.length)return dom.content(t,[r,e("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let p=n.st.version;dom.content(t,[r,...d.map(c=>{let m=c.tag.replace(/^v/,"");return e("div",{class:"dl-comp-ver"},[e("span",{class:"dl-mono"},m),e("span",{class:"dl-sub"},Hn(c.published)),c.prerelease?ke("warn","Pre-release"):"",e("span",{class:"dl-comp-ic"},ye("file","What’s new",()=>zt("app",c.tag,`What’s new in Dawnline ${m}`))),m===p?ke("ok","Installed"):D("Install",()=>ea(n,c.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function ea(n,t){let o=t.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ne(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${t}`,`Installing Dawnline ${o}`,n.st.version)}function na(n,t){let o=n.st,a=o.kept?.amneziawg,r=t?.sources??{},i=Object.keys(r),s=t?.current??null,l=s?r[s]:void 0,d=!!t?.ru,p=o.needs?.awg??[],c=p.length?null:t?.installed??null,m=[];s&&c&&m.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",c)}),a&&m.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ne(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",c??void 0)}});let v=[t?.release?{label:"What’s new",ic:"file",run:()=>zt("amneziawg",t.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...m.length?[null,...m]:[]].filter((u,f,N)=>u!==null||f>0&&N[f-1]!==null),h=o.tunnels??[],x=h.length?`Switching restarts ${h.length===1?"the tunnel":`${h.length} tunnels`} for a few seconds: ${h.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",R=h.length>1?`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`:h[0],_=h.length?`Switching restarts ${R} for a few seconds.`:"Switching takes a few seconds.",j=async u=>{let f=r[u];await ne(c?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${x}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,c?"Switch":"Install")&&n.op(`amneziawg:${u}${d?":ru":""}`,c?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",c??void 0)},w=u=>{let f=r[u],N=s===u&&!!c;return e("div",{class:"dl-row"},[e("span",{class:"dl-row-main dl-stack"},[e("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),e("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),e("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),e("span",{class:"dl-comp-bact"},N?ke("ok","Active"):f.version?D(c?"Switch":"Install",()=>j(u),c?"neutral":"positive",{disabled:n.busy}):ke("","No build"))])},I=i.map(u=>r[u]?.newer?`${r[u].label} moves to ${r[u].newer.gen} with OpenWrt ${r[u].newer.tag.replace( Line truncated
`)}r.push(c),l+=p-1}let s=D([g("more")],()=>we(s,[{label:"Export CSV",icon:g("download"),run:()=>je(o,a,"csv",t.id)},{label:"Export JSON",icon:g("download"),run:()=>je(o,a,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:g("trash"),danger:!0,run:()=>Fe(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),e("span",{class:"dl-spacer"}),s]),r.length?r:e("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var pn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(t){let[o,a,r]=await Promise.all([S.status(30),t?S.events(5e3).catch(()=>null):Promise.resolve(null),t?S.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(t){this.take(t);let o=this.st.people.find(s=>s.id===this.id);if(!o)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=e("div",{});this.parts.devices.className="dl-person-devices";let a=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:ht(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:ht(o.server)},"People"),e("span",{},"/"),e("span",{},o.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>He(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ot(this.p,this.deviceOpts()),50),this.poller=Ke({fetch: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(t){this.st=t.st,t.ev&&(this.events=t.ev),t.use&&(this.series=t.use.person,this.devSeries=t.use.devices)}apply(t,o){this.take(t);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=ht(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(t,o){var i;this.poller?.claim();let a=await U(()=>S.personUpdate(this.p.id,t),o);if(!a)return;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint()}get today(){return Ne(this.series.length?this.series:this.st.series)}get core(){return mt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(t=!1){_e(this.parts.head,pa(this),t),_e(this.parts.traffic,ua(this),t),_e(this.parts.devices,ma(this),t),_e(this.parts.limits,wa(this),t),this.paintPlaces(t),_e(this.parts.activity,ka(this),t)}paintPlaces(t=!1){let o=ya(this);o&&_e(this.parts.places,o,t&&!this.mapOpen)}};var bi={ok:"check",warn:"alert",error:"x",skip:"pause"},un=class{constructor(t,o,a,r){this.el=e("div",{});this.wdEl=e("div",{});this.checksEl=e("div",{class:"dl-panel"});this.recentEl=e("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=e("div",{});this.open=new Set;this.st=t,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,e("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(t){let o=t?await rn(t):await S.health().catch(()=>null);o&&(this.take(o),t==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(t){this.checks=t.checks,this.paintChecks(),this.paintLive(t,this.events)}paintChecks(){let t=this.checks;if(!t){dom.content(this.summary,""),dom.content(this.checksEl,[e("div",{class:"dl-panel-head"},[e("h3",{},"Checks")]),e("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=t.filter(s=>s.status==="error").length,a=t.filter(s=>s.status==="warn").length;dom.content(this.summary,o?dt("error",`${o} problem${o>1?"s":""} need attention.`):a?dt("warn",`${a} warning${a>1?"s":""}.`):dt("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs)r.set(s.id Line truncated
`);function Ia(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=Ri,n}function rt(n){return()=>{let t=new n;return Object.assign({load:()=>t.load(),render:async a=>{let r=await t.render(a),i=document.createElement("div");return i.className="dl-root",i.append(Ia(),r),i},addFooter(){return t.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Uf=rt(At),Wf=rt(at),Gf=rt(At),qf=rt(ln),Ff=rt(pn),Kf=rt(fn),Jf=rt(cn);function Ba(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 Vf=Ba(""),Yf=Ba("log");return baseclass.extend({ activity: Yf, diagnostics: Kf, health: Vf, overview: Uf, people: Wf, person: Ff, server: Gf, settings: qf, updates: Jf });
@@ -20,6 +20,14 @@ rm -f /www/luci-static/resources/view/dawnline/backups.js
# Portal assets moved out of the web root (served only with a valid code).
rm -rf /usr/share/dawnline/portal/www/assets
# "Find home devices" (0.3.0) is gone: its option and dnsmasq records too.
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.]*\)\.bonjour=.*/\1/p'); do uci -q delete "dawnline.$s.bonjour"; done
uci -q commit dawnline
if ls /tmp/dnsmasq*.d/dawnline-bonjour.conf >/dev/null 2>&1; then
rm -f /tmp/dnsmasq*.d/dawnline-bonjour.conf /var/run/dawnline/bonjour.json
/etc/init.d/dnsmasq restart 2>/dev/null
fi
# LuCI caches: menu index, and module URLs (?v= follows the opkg status time).
rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null
touch /usr/lib/opkg/status 2>/dev/null
@@ -0,0 +1 @@
/etc/dawnline/
+65 -26
View File
@@ -6,9 +6,15 @@ import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as view from 'dawnline.view';
import * as ops from 'dawnline.ops';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as pc from 'dawnline.portalcert';
import * as watchdog from 'dawnline.watchdog';
import { VERSION, slog, sh_out, q, take_iface_intent } from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import {
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util';
const args = ARGV;
const cmd = args[0] ?? 'help';
@@ -30,7 +36,7 @@ function help() {
Usage: dawnline <command>
apply Reconcile router configuration and runtime state
sync Push devices and access rules to the tunnel
sync Push devices and access rules to the tunnels
status People and devices with live state (JSON)
health Run health checks (JSON)
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
@@ -38,7 +44,7 @@ Usage: dawnline <command>
person link <slug> Print the personal portal link
person rm <slug> Remove a person and their devices
device add <slug> <name> [--kind phone|computer|tablet|router]
device conf <id> Print a device configuration
device 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
@@ -48,9 +54,47 @@ Usage: dawnline <command>
version`);
}
function commit(c) {
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
/*
* netifd retries a tunnel that fails to start every few seconds (a kernel
* module that won't load, AmneziaWG removed): one line per interface every
* 10 minutes, with how many attempts failed meanwhile. A start clears it.
*/
const FAILS = `${RUN_DIR}/ifup-failed.json`;
const FAIL_EVERY = 600;
function ifup_failed(ifname, who) {
let now = time();
// Attempts since the last line (a quiet spell starts a new count), and over how long.
let r = with_lock('ifup-failed', () => {
let all = read_json(FAILS, {});
let f = all[ifname];
if (!f || now - f.last > FAIL_EVERY)
f = all[ifname] = { logged: 0, count: 0, since: now };
f.count++;
f.last = now;
let out = null;
if (now - f.logged >= FAIL_EVERY) {
out = { n: f.count, mins: int((now - f.since) / 60) };
f.logged = f.since = now;
f.count = 0;
}
ensure_dir(RUN_DIR);
write_json(FAILS, all, 0o600);
return out;
});
if (r)
slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start",
watchdog.iface_errors(ifname), who);
}
function ifup_ok(ifname) {
with_lock('ifup-failed', () => {
let all = read_json(FAILS, {});
if (all[ifname]) {
delete all[ifname];
write_json(FAILS, all, 0o600);
}
});
}
try {
@@ -59,18 +103,16 @@ try {
else if (cmd == 'sync')
out(apply.sync());
else if (cmd == 'status') {
let m = core.load(), u = core.load_usage(), d = live.dump(), st = view.states(m, u);
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
}
else if (cmd == 'health')
out(ops.health());
out(health.health());
else if (cmd == 'person' && args[1] == 'add') {
let c = core.open_cursor(), m = core.load(c);
let id = core.create_person(c, m, {
let id = store.transact((c, m) => core.create_person(c, m, {
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
});
commit(c);
}));
let m2 = core.load();
out(core.portal_url(m2, m2.people[id]) ?? id);
}
@@ -80,33 +122,29 @@ try {
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.');
}
else if (cmd == 'person' && args[1] == 'rm') {
let c = core.open_cursor(), m = core.load(c);
core.delete_person(c, m, args[2]);
commit(c);
store.transact((c, m) => core.delete_person(c, m, args[2]));
apply.sync();
}
else if (cmd == 'device' && args[1] == 'add') {
let c = core.open_cursor(), m = core.load(c);
let id = core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin' });
commit(c);
// Keys first: generating them runs the awg tool, not worth holding the config lock for.
let keys = awg.new_keys();
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys }));
apply.sync();
out(id);
}
else if (cmd == 'device' && args[1] == 'conf') {
let m = core.load();
let d = m.devices[args[2]] ?? die('Unknown device.');
print(core.client_config(m, d).conf);
print(awg.client_config(m, d).conf);
}
else if (cmd == 'device' && args[1] == 'rm') {
let c = core.open_cursor(), m = core.load(c);
core.delete_device(c, m, args[2]);
commit(c);
store.transact((c, m) => core.delete_device(c, m, args[2]));
apply.sync();
}
else if (cmd == 'backup')
out(ops.backup_create(opt('reason')));
out(backup.backup_create(opt('reason')));
else if (cmd == 'portal-cert') {
let c = ops.portal_cert(core.load().settings);
let c = pc.portal_cert(core.load().settings);
out(`${c.cert} ${c.key}`);
}
else if (cmd == 'portal-http-port') {
@@ -137,6 +175,7 @@ try {
if (srv.ifname == ifname)
who = srv.name;
if (args[1] == 'ifup') {
ifup_ok(ifname);
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who);
}
@@ -152,7 +191,7 @@ try {
], (x) => x)), who);
}
else if (args[1] == 'ifup-failed')
slog('awg', 'error', "couldn't start", watchdog.iface_errors(ifname), who);
ifup_failed(ifname, who);
}
else if (cmd == 'teardown')
apply.teardown();
@@ -1,9 +1,11 @@
#!/usr/bin/ucode
// Dawnline agent (procd instance). Every minute it:
// * folds AmneziaWG counters into usage (tmpfs; flushed to flash hourly)
// Dawnline agent (procd instance). Every second its watcher reads the tunnels
// and, the moment a device connects, its session expires or it roams, logs
// it, folds the counters, locates the new address and moves the revision the
// admin UI polls (presence.json, see dawnline.live). Every minute it:
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
// * saves the activity log to flash as often as Settings says (or never)
// * keeps the "like a home device" path and the Home-only resolver up
// * logs connects, disconnects and roaming
// * enforces end dates, quotas, schedules and pauses (peers + nft sets)
// * watches the tunnel interfaces and repairs what it can (dawnline.watchdog)
'use strict';
@@ -11,33 +13,42 @@
import * as uloop from 'uloop';
import { readfile, writefile, stat, unlink } from 'fs';
import {
read_json, write_json, ensure_dir, sh_out, q, 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, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as ops from 'dawnline.ops';
import * as backup from 'dawnline.backup';
import * as pc from 'dawnline.portalcert';
import * as geo from 'dawnline.geo';
import * as watchdog from 'dawnline.watchdog';
import * as net from 'dawnline.net';
import * as bonjour from 'dawnline.bonjour';
import * as store from 'dawnline.store';
import * as upd from 'dawnline.updates';
import * as awg from 'dawnline.awg';
const TICK = 60 * 1000;
const WATCH = 1000;
const FLUSH_EVERY = 3600;
const LOG_FLUSH = { '10min': 600, hourly: 3600 };
const RESYNC_EVERY = 600;
const CONFIG_FILE = '/etc/config/dawnline';
let usage = live.load_usage();
let last_states = null;
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
// swallow connects that happened in between.
let presence = read_json(`${RUN_DIR}/presence.json`, {});
let presence = read_json(live.PRESENCE, {});
let last_online = presence.online ?? {};
let last_endpoint = presence.endpoint ?? {};
let offline_ticks = {};
let rev = +(presence.rev ?? 0);
let person_rev = presence.people ?? {};
let last_flush = time();
let last_log_flush = time();
let last_net = null;
// The network as apply() last saw it (apply.NET_SIG; this when it never ran),
// and a different one seen on the previous tick.
let base_net = null;
let pending_net = null;
let rate_prev = null;
/**
@@ -96,6 +107,7 @@ function record_rate(m) {
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
}
let last_sync = 0;
let conf_mtime = null;
let cert_mtime = null;
const REASON = {
@@ -114,12 +126,10 @@ function check_people(m, states, events) {
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
// "Remove their devices" when the end date passes.
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) {
let c = core.open_cursor();
let mm = core.load(c);
for (let d in mm.people[id]?.devices ?? [])
core.delete_device(c, mm, d);
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
store.transact((c, mm) => {
for (let d in mm.people[id]?.devices ?? [])
core.delete_device(c, mm, d);
});
push(events, { type: 'devices_removed', person: id, detail: 'end date reached' });
last_sync = 0;
}
@@ -160,41 +170,98 @@ function named(e) {
return e;
}
function check_devices(m, lv, events) {
for (let id, d in lv) {
let dev = m.devices[id];
/* ---------- the watcher ---------- */
// Per device: its latest real handshake, kept when apply re-adds the peer
// (its counters and handshake restart from zero, or it is briefly missing).
let last_hs = {};
// The model, read again only when the config file changes (the watcher runs every second).
let wm = null, wm_sig = null;
function watch_model() {
// uci commits replace the file: a new inode even within the same second.
let st = stat(CONFIG_FILE);
let sig = st ? `${st.mtime}/${st.inode}` : null;
if (wm == null || sig != wm_sig) {
wm = core.load();
wm_sig = sig;
}
return wm;
}
/** Move the revisions (all, and these people's) and save who is online. */
function save_presence(people) {
rev++;
for (let pid in people)
person_rev[pid] = rev;
ensure_dir(RUN_DIR);
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
}
/*
* One look at the tunnels. Connects (a new handshake from a device that was
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
* a phone asleep looks the same as one switched off, so silence alone is not
* enough) and roaming (a new address) are acted on at
* once: the log, the counters and the map, then the revision the UI polls.
* Only from a complete read: a failed one says nothing about anyone.
*/
function watch() {
let d = awg.dump();
if (!d.ok)
return;
let m = watch_model();
let now = time();
let events = [], people = {}, ips = [];
for (let id, dev in m.devices) {
let peer = d.peers[dev.public_key];
let ep = '';
if (peer) {
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
ep = live.endpoint_ip(peer.endpoint);
}
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
let was = last_online[id];
// A device we have never seen before that is online now counts as a connect.
if (was == null && d.online && d.present)
was = false;
// Debounce: a device has to look offline on two ticks in a row before
// a disconnect is logged (handshakes are renewed only every 2-3 min).
if (was && !d.online) {
offline_ticks[id] = (offline_ticks[id] ?? 0) + 1;
if (offline_ticks[id] < 2)
continue;
if (on && !was) {
push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
push(ips, ep);
}
else
delete offline_ticks[id];
if (was != null && was != d.online) {
if (d.online)
push(events, named({ type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) }));
else
push(events, { type: 'disconnect', person: dev.person, device: id });
else if (!on && was)
push(events, { type: 'disconnect', person: dev.person, device: id });
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) {
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
push(ips, ep);
}
else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint)
push(events, named({ type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` }));
last_online[id] = d.online;
if (d.endpoint)
last_endpoint[id] = d.endpoint;
if (on != !!was || (ep && ep != last_endpoint[id]))
people[dev.person] = true;
last_online[id] = on;
if (ep)
last_endpoint[id] = ep;
}
for (let id in keys(last_online))
if (!m.devices[id]) {
delete last_online[id];
delete last_endpoint[id];
delete last_hs[id];
}
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600);
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);
}
for (let e in events)
if (e.type == 'connect')
e.where = place_of(e.detail);
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
save_presence(keys(people));
}
// What the service log was already told. On flash: the public address often
@@ -218,7 +285,7 @@ function cert_end(path) {
function check_cert(m) {
if (!m.settings.portal_enabled)
return;
let c = ops.portal_cert(m.settings);
let c = pc.portal_cert(m.settings);
let mt = stat(c.cert)?.mtime;
if (cert_mtime != null && mt != null && mt != cert_mtime) {
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal');
@@ -269,13 +336,22 @@ function nightly_backup() {
let st = read_json(`${DATA_DIR}/backup-state.json`, {});
if (sum && sum != st.auto) {
try {
ops.backup_create('auto');
backup.backup_create('auto');
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
}
catch (e) {}
}
}
/**
* Settings → Updates: an automatic check or update when one is due. The
* updater does the work in its own process; this only decides when.
*/
function check_updates(m) {
if (upd.due(m.settings.updates, upd.auto_state()) && !upd.busy())
system('start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- auto');
}
/**
* Traffic history resets requested from LuCI (rpcd cannot touch the
* counters this process holds in memory). Applied, then saved to flash.
@@ -292,84 +368,130 @@ function check_usage_reset(m) {
return true;
}
/*
* Push devices and access rules when people's states changed, the config
* file was written (by anyone: rpcd, the portal, the CLI, a restore), or
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
*/
function sync_runtime(t) {
// uci commits replace the file: a new inode even within the same second.
let st = stat(CONFIG_FILE);
let mt = st ? `${st.mtime}/${st.inode}` : null;
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
(conf_mtime != null && mt != conf_mtime);
if (changed || time() - last_sync > RESYNC_EVERY) {
apply.sync(t.m, usage);
last_sync = time();
}
conf_mtime = mt;
last_states = t.states;
}
/*
* The router's network changed under us: re-derive everything. Only a change
* seen on two ticks in a row (a bridge recreated or an interface restarting
* passes), compared with what the last apply() used.
*/
function check_network(t) {
let sig = apply.net_signature(t.m);
let applied = readfile(apply.NET_SIG) ?? base_net;
if (applied == null || sig == applied) {
base_net ??= sig;
pending_net = null;
return;
}
if (pending_net != sig) {
pending_net = sig;
return;
}
pending_net = null;
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
apply.apply();
base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load());
}
/*
* One tick is a list of steps, each on its own: a failing step is logged
* (each new message once in the service log, every time in syslog) and the
* others still run. Steps that need the model wait for it; the counters and
* the logs are saved at the end whatever happened.
*/
const STEPS = [
{ who: 'Dawnline', run: (t) => {
t.m = core.load();
t.pol = live.policy(t.m.settings.retention);
} },
{ who: 'Traffic', run: (t) => {
t.reset = check_usage_reset(t.m);
live.collect(t.m, usage, live.dump(t.m));
} },
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
{ who: 'People', run: (t) => {
t.states = apply.states_for(t.m, usage);
check_people(t.m, t.states, t.events);
} },
{ who: 'Access rules', run: (t) => {
if (t.states)
sync_runtime(t);
} },
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
{ who: 'Activity', run: (t) => {
live.add_events(t.events, t.pol);
// Pauses and resumes on their own: the UI shows them without waiting for its next poll.
if (length(t.events))
save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person)));
} },
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
{ who: 'Router', run: check_network },
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
{ who: 'Personal portal', run: (t) => check_cert(t.m) },
{ who: 'Router', quiet: true, run: (t) => check_wan(t.m) },
{ who: 'Backup', run: (t) => nightly_backup() },
{ who: 'updates', quiet: true, run: (t) => check_updates(t.m) },
{ who: 'geo', quiet: true, run: (t) => check_geo(t.m) },
];
// Step → the last error it logged (cleared when it works again).
let step_err = {};
function step(i, s, fn) {
try {
fn();
delete step_err[i];
}
catch (e) {
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
if (!s.quiet && step_err[i] != e.message)
slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who);
step_err[i] = e.message;
}
}
function tick() {
ensure_dir(RUN_DIR);
writefile(watchdog.BEAT, `${time()}`);
// A restore or import drops the live counters; start over from flash.
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
let m = core.load();
let reset = check_usage_reset(m);
let pol = live.policy(m.settings.retention);
let dmp = live.dump();
let lv = live.collect(m, usage, dmp);
try {
record_rate(m);
}
catch (e) {}
let states = apply.states_for(m, usage);
let events = [];
let t = { m: null, pol: null, reset: false, events: [] };
for (let i, s in STEPS)
if (i == 0 || t.m)
step(i, s, () => s.run(t));
check_devices(m, lv, events);
check_people(m, states, events);
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
let changed = last_states == null || sprintf('%J', states) != sprintf('%J', last_states);
if (changed || time() - last_sync > RESYNC_EVERY) {
apply.sync(m, usage);
last_sync = time();
}
last_states = states;
live.add_events(events, pol);
let persist = reset || time() - last_flush >= FLUSH_EVERY;
live.save_usage(usage, persist);
slog_trim(persist);
if (persist)
last_flush = time();
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
live.persist_events(pol);
last_log_flush = time();
}
try {
apply.sync_loop(m, usage);
// The router's network changed under us: re-derive everything.
let sig = apply.net_signature(m);
if (last_net != null && sig != last_net) {
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
apply.apply();
sig = apply.net_signature(core.load());
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
step('save', { who: 'Traffic' }, () => {
live.save_usage(usage, persist);
if (persist)
last_flush = time();
});
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
step('events', { who: 'Activity' }, () => {
let pol = t.pol ?? live.policy();
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
live.persist_events(pol);
last_log_flush = time();
}
last_net = sig;
}
catch (e) {
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Internet like a home device');
}
try {
watchdog.run(core.load());
}
catch (e) {
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Watchdog');
}
check_cert(m);
try {
check_wan(m);
}
catch (e) {}
try {
bonjour.sync(m);
}
catch (e) {
slog('dawnline', 'error', `failed: ${e.message}`, null, 'Find home devices');
}
nightly_backup();
try {
check_geo(m);
}
catch (e) {
system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`);
}
});
}
function shutdown() {
@@ -418,6 +540,12 @@ timer = uloop.timer(1000, function() {
timer.set(TICK);
});
let watcher;
watcher = uloop.timer(WATCH, function() {
step('watch', { who: 'Connections' }, watch);
watcher.set(WATCH);
});
if (type(uloop.signal) == 'function') {
uloop.signal('TERM', () => { shutdown(); uloop.end(); });
uloop.signal('INT', () => { shutdown(); uloop.end(); });
@@ -1,64 +1,52 @@
#!/usr/bin/ucode
// Dawnline background update worker, started detached by luci.dawnline.
// Dawnline background update worker, started detached by luci.dawnline and
// by the agent (automatic runs).
//
// updater check
// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:<name,…>|all
// updater check [app|amneziawg|packages]
// updater install app | app@<tag> | app:reinstall | app:rollback
// updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
// updater install pkgs:<name,…>
// updater auto (Settings → Updates: check, then install)
//
// Progress: /var/run/dawnline/update-job.json; check results:
// /var/run/dawnline/update-check.json. The Updates tab polls both.
// One job at a time: the job holds the update lock (dawnline.updates) until
// it exits. Progress: /var/run/dawnline/update-job.json; check results:
// /var/run/dawnline/update-check.json. The Components tab polls both. The
// components themselves are dawnline.upd_app, upd_awg and upd_pkgs.
'use strict';
import * as fs from 'fs';
import { cursor } from 'uci';
import { connect } from 'ubus';
import { VERSION, REPO, slog, iface_intent } from 'dawnline.util';
import { slog, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as upd from 'dawnline.updates';
import * as app from 'dawnline.upd_app';
import * as awg from 'dawnline.upd_awg';
import * as pkgs from 'dawnline.upd_pkgs';
const STATE_DIR = '/var/run/dawnline';
const JOB_FILE = `${STATE_DIR}/update-job.json`;
const CHECK_FILE = `${STATE_DIR}/update-check.json`;
const WORK_DIR = '/tmp/dawnline-update';
// Builds per OpenWrt release (tag = firmware version); the kernel module must match the firmware.
// Which AmneziaWG a build carries (2.0 or 3.1) is read from the package, per firmware.
const AWG_SOURCES = {
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
};
const AWG_PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
const AWG_RU = 'luci-i18n-amneziawg-ru';
// OpenWrt packages Dawnline runs on (the Updates tab groups and names them).
// What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the
// stock system): the home-like link, and HTTPS plus certificates for the personal portal.
const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme', 'umdns' ];
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
// half old and half new.
const PKG_FAMILY = [
[ /^ip-full$/, /^ip-/ ],
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
[ /^(acme|luci-app-acme$)/, /^acme/ ],
];
function family(p) {
for (let f in PKG_FAMILY)
if (match(p, f[0]))
return f[1];
return null;
}
const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0];
const POL = core.load().settings.updates;
const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check };
const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install };
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' };
let job = {
action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
phase: '', log: [], error: null, result: null,
id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
pid: PID, auto: false, phase: '', from: null, to: null, log: [], error: null, result: null,
};
// An automatic run only shows up as a job once it installs something.
let quiet = ARGV[0] == 'auto';
// What to restart once the job is over (never in the middle of it).
let after = {};
function save() {
fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job));
fs.rename(`${JOB_FILE}.tmp`, JOB_FILE);
if (!quiet)
write_json(upd.JOB_FILE, job, 0o644);
}
function log(msg) {
let t = localtime();
push(job.log, sprintf('%02d:%02d:%02d %s', t.hour, t.min, t.sec, msg));
if (length(job.log) > 300)
splice(job.log, 0, length(job.log) - 300);
if (length(job.log) > 400)
splice(job.log, 0, length(job.log) - 400);
save();
}
@@ -67,478 +55,261 @@ function phase(p) {
log(p);
}
function q(s) {
return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'";
}
/** A command, its output in the log: { code, out }. */
function run(cmd) {
let p = fs.popen(cmd + ' 2>&1', 'r');
if (!p)
return { code: 127, out: '' };
let out = p.read('all') ?? '';
return { code: p.close(), out };
}
function run_logged(cmd) {
let r = run(cmd);
for (let line in split(trim(r.out), '\n'))
let r = { code: p.close(), out };
for (let line in split(trim(out), '\n'))
if (length(trim(line)))
log(` ${line}`);
return r;
}
function repo() {
return REPO;
const ctx = {
pol: POL,
work: `/tmp/dawnline-update.${PID}`,
log, phase, run, save,
versions: (from, to) => {
job.from = from;
job.to = to;
save();
},
after: (what) => after[what] = true,
};
/* ---------- check results ---------- */
function checks_file() {
return read_json(upd.CHECK_FILE, null)?.components ?? {};
}
function have_curl() {
return fs.access('/usr/bin/curl', 'x');
/** Components' results into the check file (the others stay as they were). */
function save_check(res) {
let c = read_json(upd.CHECK_FILE, null) ?? {};
c.components ??= {};
for (let k, v in res)
c.components[k] = { ...v, time: time() };
c.time = time();
write_json(upd.CHECK_FILE, c, 0o644);
}
function download(url, dest) {
let r = have_curl()
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 2 -o ${q(dest)} ${q(url)}`)
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(url)}`);
return r.code == 0 && (fs.stat(dest)?.size ?? 0) > 0;
/** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */
function found_in(res) {
let found = [];
if (res.app?.update)
push(found, `Dawnline ${res.app.latest}`);
if (res.amneziawg?.update && res.amneziawg.installed)
push(found, `AmneziaWG ${res.amneziawg.latest}`);
if (res.packages?.updates)
push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`);
return found;
}
/** Latest release tag; the /releases/latest redirect avoids API rate limits. */
function latest_tag(rp) {
if (have_curl()) {
let r = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`);
let m = match(trim(r.out), /\/releases\/tag\/([^\/?#]+)$/);
if (m)
return m[1];
}
let r = run(`uclient-fetch -q -T 20 -O - ${q('https://api.github.com/repos/' + rp + '/releases/latest')}`);
try {
return json(r.out)?.tag_name;
}
catch (e) {
return null;
}
}
function version_cmp(a, b) {
let pa = split(replace(`${a}`, /^v/, ''), /[.~+-]/), pb = split(replace(`${b}`, /^v/, ''), /[.~+-]/);
for (let i = 0; i < length(pa) || i < length(pb); i++) {
let x = pa[i] ?? '0', y = pb[i] ?? '0';
if (match(x, /^[0-9]+$/) && match(y, /^[0-9]+$/)) {
if (int(x) != int(y))
return int(x) < int(y) ? -1 : 1;
function run_checks(which) {
let res = {};
for (let name in which) {
phase(`Checking ${WHO[name]}`);
try {
res[name] = CHECKS[name](ctx);
}
else if (x != y)
return x < y ? -1 : 1;
}
return 0;
}
function is_apk() {
return fs.access('/usr/bin/apk', 'x');
}
function pkg_version(name) {
let esc = replace(name, /[.+]/g, '\\$&');
if (is_apk()) {
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
return m ? m[1] : null;
}
// Libraries carry their ABI in the name (libustream-openssl20201210).
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
for (let line in split(run('opkg list-installed').out, '\n')) {
let m = match(trim(line), re);
if (m && (found == null || m[1] == null))
found = m;
}
return found ? trim(found[2]) : null;
}
function pkg_file_version(path) {
if (match(path, /\.ipk$/)) {
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
}
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
}
function workdir() {
run(`rm -rf ${WORK_DIR}`);
fs.mkdir(WORK_DIR, 0o700);
}
/* ---------- Dawnline itself ---------- */
function check_app() {
let rp = repo();
let tag = latest_tag(rp);
if (!tag)
return { installed: VERSION, latest: null, update: false, note: `No published release in ${rp}` };
let latest = replace(tag, /^v/, '');
return { installed: VERSION, latest, tag, repo: rp, update: version_cmp(VERSION, latest) < 0 };
}
function install_app() {
let c = check_app();
if (!c.latest)
die(c.note);
if (!c.update) {
log('Dawnline is up to date');
return { installed: VERSION };
}
// Releases carry luci-app-dawnline-<version>.ipk and .apk plus sha256sums.txt.
let asset = `luci-app-dawnline-${c.latest}.${is_apk() ? 'apk' : 'ipk'}`;
let base = `https://github.com/${c.repo}/releases/download/${c.tag}`;
workdir();
phase(`Downloading ${asset}`);
let f = `${WORK_DIR}/${asset}`, sums = `${WORK_DIR}/sha256sums.txt`;
if (!download(`${base}/${asset}`, f))
die(`Download failed: ${asset}`);
phase('Verifying package');
if (!download(`${base}/sha256sums.txt`, sums))
die('The release has no sha256sums.txt');
let want = null;
for (let line in split(fs.readfile(sums) ?? '', '\n')) {
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
if (m && m[2] == asset)
want = m[1];
}
let got = match(run(`sha256sum ${q(f)}`).out, /^([0-9a-f]{64})/)?.[1];
if (!want || got != want)
die(`Checksum mismatch for ${asset}`);
phase('Backing up configuration');
run('/usr/bin/dawnline backup --reason pre-update');
phase('Installing package');
if (run_logged(is_apk() ? `apk add --allow-untrusted ${q(f)}` : `opkg install ${q(f)}`).code != 0)
die('Installation failed');
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
// Restart after this job has saved its final state.
run('( sleep 3; /etc/init.d/rpcd reload; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
return { installed: c.latest };
}
/* ---------- AmneziaWG ---------- */
function awg_release() {
let u = connect();
let b = u?.call('system', 'board') ?? {};
u?.disconnect();
let rel = b.release ?? {};
let target = split(rel.target ?? '', '/');
let arch = rel.arch ?? trim(run("sed -n \"s/^DISTRIB_ARCH='\\(.*\\)'/\\1/p\" /etc/openwrt_release").out);
if (!rel.version || length(target) != 2 || !arch)
return null;
return {
tag: `v${rel.version}`,
postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`,
ext: is_apk() ? 'apk' : 'ipk',
};
}
function awg_download(r, name, rp) {
let file = `${name}${r.postfix}.${r.ext}`;
let dest = `${WORK_DIR}/${replace(rp, '/', '_')}_${file}`;
return download(`https://github.com/${rp}/releases/download/${r.tag}/${file}`, dest) ? dest : null;
}
/** When the build for this firmware was published (best effort). */
function release_date(rp, tag) {
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases/tags/${tag}`)}`);
try {
return json(r.out)?.published_at ?? null;
}
catch (e) {
return null;
}
}
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
function awg_gen(version) {
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
}
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
function newer_series_tag(rp, tag) {
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases?per_page=30`)}`);
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
let best = null;
try {
for (let x in json(r.out) ?? []) {
let t = x.tag_name;
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && version_cmp(t, tag) > 0 && (!best || version_cmp(t, best) > 0))
best = t;
catch (e) {
log(`Error: ${e.message}`);
res[name] = { error: e.message, status: '' };
}
}
catch (e) {}
return best;
save_check(res);
return res;
}
function awg_installed() {
let r = {};
for (let p in AWG_PKGS)
r[p] = pkg_version(p);
return r;
/** One line in Activity per new finding (the same finding is not repeated). */
function note_found(res, st, auto) {
let found = found_in(res);
let sig = join(', ', found);
if (length(found) && sig != st.announced) {
if (auto)
slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components');
upd.history_add({ kind: 'found', items: found, auto });
}
st.announced = sig;
}
function check_awg() {
let installed = awg_installed();
let ru = pkg_version(AWG_RU) != null;
let cur = installed['amneziawg-tools'];
let r = awg_release();
if (!r)
return { installed: cur, gen: awg_gen(cur), packages: installed, current: null, ru, sources: {}, update: false, note: 'Cannot detect the firmware target' };
workdir();
let sources = {};
for (let id, src in AWG_SOURCES) {
let f = awg_download(r, 'amneziawg-tools', src.repo);
let v = f ? pkg_file_version(f) : null;
let s2 = { label: src.label, repo: src.repo, tag: r.tag, version: v, gen: awg_gen(v), date: f ? release_date(src.repo, r.tag) : null };
// A newer firmware may already get 3.1 from this source.
if (s2.gen != '3.1') {
let nt = newer_series_tag(src.repo, r.tag);
if (nt) {
let nf = awg_download({ ...r, tag: nt, postfix: replace(r.postfix, r.tag, nt) }, 'amneziawg-tools', src.repo);
let nv = nf ? pkg_file_version(nf) : null;
if (awg_gen(nv) == '3.1')
s2.newer = { tag: nt, gen: '3.1' };
}
/* ---------- installs ---------- */
/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
function log_update(name, r) {
let how = job.auto ? ' automatically' : '';
if (name == 'amneziawg') {
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}`
: `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, 'AmneziaWG');
}
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
slog('dawnline', 'up', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
}
function split_target(w) {
let i = index(w, ':'), at = index(w, '@');
let cut = i < 0 ? at : at < 0 || i < at ? i : at;
if (cut < 0)
return [ w, null ];
return [ substr(w, 0, cut), substr(w, cut + (substr(w, cut, 1) == ':' ? 1 : 0)) ];
}
function app_status(installed, latest) {
if (!latest)
return 'latest';
let c = upd.version_cmp(installed, latest);
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
}
function install(what) {
job.result ??= {};
for (let w in what) {
let t = split_target(w), name = t[0], arg = t[1];
if (!INSTALLS[name])
die(`Unknown component ${name}`);
job.current = name;
phase(`Updating ${WHO[name]}`);
let r = INSTALLS[name](ctx, arg);
job.result[name] = r;
log_update(name, r);
// Installed components are current now: no stale "Update available".
let c = checks_file();
if (name == 'pkgs' && r.check)
save_check({ packages: r.check });
else if (name == 'app' && r.to && c.app) {
let s = app_status(r.to, c.app.latest);
save_check({ app: { ...c.app, installed: r.to, update: s == 'outdated', status: s } });
}
sources[id] = s2;
else if (name == 'amneziawg' && r.after)
save_check({ amneziawg: { ...(c.amneziawg ?? {}), installed: r.after['amneziawg-tools'], packages: r.after,
current: r.build ?? c.amneziawg?.current, update: false, status: 'latest' } });
upd.history_add({ kind: 'install', component: w, from: r.from, to: r.to, state: 'done', auto: job.auto,
took: time() - job.started });
delete job.current;
}
// The installed build: the source whose package matches, else the main one.
let current = null;
for (let id, x in sources)
if (!current && cur && x.version == cur)
current = id;
current ??= cur ? 'slava' : null;
let mine = current ? sources[current] : null;
return { installed: cur, gen: awg_gen(cur), packages: installed, current, ru, release: r.tag, sources,
latest: mine?.version ?? null,
update: cur == null || (mine?.version != null && version_cmp(cur, mine.version) < 0),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(r.tag, 1)} yet` : null };
}
function install_awg(arg) {
let parts = split(arg ?? '', ':');
let id = parts[0] || 'slava';
let src = AWG_SOURCES[id];
if (!src)
die(`Unknown AmneziaWG build ${id}`);
let want_ru = parts[1] == 'ru';
let r = awg_release();
if (!r)
die('Cannot detect the firmware target');
let before = awg_installed();
workdir();
let files = [];
for (let p in [ ...AWG_PKGS, ...(want_ru ? [ AWG_RU ] : []) ]) {
phase(`Downloading ${p} from ${src.repo}`);
let f = awg_download(r, p, src.repo);
if (!f)
die(`No ${p} build for OpenWrt ${substr(r.tag, 1)} in ${src.repo}`);
push(files, f);
}
phase('Refreshing package lists');
run_logged(is_apk() ? 'apk update' : 'opkg update');
phase(`Installing the ${src.label} build`);
let cmd = is_apk()
? `apk add --allow-untrusted ${join(' ', map(files, q))}`
: `opkg install --force-reinstall --force-downgrade ${join(' ', map(files, q))}`;
if (run_logged(cmd).code != 0)
die('Package installation failed');
if (!want_ru && pkg_version(AWG_RU))
run_logged(is_apk() ? `apk del ${AWG_RU}` : `opkg remove ${AWG_RU}`);
let after = awg_installed();
if (before['kmod-amneziawg'] && before['kmod-amneziawg'] != after['kmod-amneziawg']) {
// New kernel module: every AmneziaWG interface must be re-created.
let ifaces = [];
let c = cursor();
c.load('network');
c.foreach('network', 'interface', (s) => {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']);
});
phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
for (let i in ifaces) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
run(`ifdown ${q(i)}`);
}
run('rmmod amneziawg');
run_logged('modprobe amneziawg');
for (let i in ifaces)
run(`ifup ${q(i)}`);
}
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
return { build: id, before, after };
}
/* ---------- OpenWrt packages Dawnline uses ---------- */
// Installed packages with a newer version in the feeds: { name: latest }.
function upgradable(refresh) {
if (refresh) {
phase('Refreshing package lists');
run(is_apk() ? 'apk update' : 'opkg update');
}
let up = {};
if (is_apk()) {
for (let line in split(run('apk version -l "<"').out, '\n')) {
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
if (m)
up[m[1]] = m[3];
}
/** Settings → Updates: check when due, install what is allowed (scheduled or right away). */
function auto() {
let st = upd.auto_state();
let what = upd.due(POL, st);
if (!what)
return;
let now = time();
let res;
if (what == 'check' || now - (st.check ?? 0) >= 3600) {
res = run_checks(upd.TARGETS);
st.check = now;
note_found(res, st, true);
}
else
for (let line in split(run('opkg list-upgradable').out, '\n')) {
let m = match(line, /^(\S+) - (\S+) - (\S+)/);
if (m)
up[m[1]] = m[3];
}
return up;
res = checks_file();
if (what == 'install')
upd.mark_day(POL, st, now);
upd.auto_save(st);
if (!POL.auto || (what != 'install' && POL.mode != 'immediate'))
return;
let todo = [];
// Packages first, Dawnline last: it restarts rpcd and itself.
if (index(POL.targets, 'packages') >= 0 && res.packages?.updates) {
let names = filter(keys(res.packages.pkgs ?? {}), (p) => res.packages.pkgs[p].latest || length(res.packages.pkgs[p].with ?? []));
if (length(names))
push(todo, `pkgs:${join(',', names)}`);
}
let a = res.amneziawg;
if (index(POL.targets, 'amneziawg') >= 0 && a?.update && a.installed) {
// Only the same build, same generation: anything else needs a person to decide.
if (a.current && !a.gen_change)
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
else
slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG');
}
if (index(POL.targets, 'app') >= 0 && res.app?.update)
push(todo, 'app');
if (!length(todo))
return;
quiet = false;
job.action = 'install';
job.component = join(' ', todo);
job.auto = true;
job.log = [];
log(`Automatic update: ${join(', ', todo)}`);
install(todo);
}
// The packages to update for these names: each one plus its upgradable family.
function with_family(names, up) {
let set = {};
for (let n in names) {
if (up[n])
set[n] = true;
let f = family(n);
if (f)
for (let u in keys(up))
if (match(u, f))
set[u] = true;
}
return sort(keys(set));
}
function check_pkgs(refresh) {
let up = upgradable(refresh ?? true);
let res = {}, all = {};
for (let p in SYS_PKGS) {
let v = pkg_version(p);
let set = v ? with_family([ p ], up) : [];
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
for (let x in set)
all[x] = true;
}
return { pkgs: res, updates: length(keys(all)) };
}
// Before install_pkgs: ucode resolves a name at the point it is used.
function save_check(res, at) {
fs.writefile(CHECK_FILE, sprintf('%J', { time: at ?? time(), components: res }));
}
function install_pkgs(arg) {
let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names)
if (index(SYS_PKGS, n) < 0)
die(`${n} is not a package Dawnline manages`);
if (!length(names))
die('Nothing to install');
phase('Refreshing package lists');
run_logged(is_apk() ? 'apk update' : 'opkg update');
let missing = filter(names, (n) => pkg_version(n) == null);
let have = with_family(filter(names, (n) => pkg_version(n) != null), upgradable(false));
if (length(have)) {
phase(`Updating ${join(', ', have)}`);
if (run_logged(is_apk() ? `apk upgrade ${join(' ', map(have, q))}` : `opkg upgrade ${join(' ', map(have, q))}`).code != 0)
die('Update failed');
}
if (length(missing)) {
phase(`Installing ${join(', ', missing)}`);
if (run_logged(is_apk() ? `apk add ${join(' ', map(missing, q))}` : `opkg install ${join(' ', map(missing, q))}`).code != 0)
die('Installation failed');
}
// Show the new state right away instead of the check from before the update.
try {
let c = json(fs.readfile(CHECK_FILE) ?? '{}') ?? {};
c.components ??= {};
c.components.packages = check_pkgs(false);
save_check(c.components, c.time);
}
catch (e) {
log(`Could not refresh the package check: ${e.message}`);
}
// The portal's HTTPS runs in uhttpd. Restart after this job saved its state.
let touched = [ ...names, ...have ];
// A missing piece arrived: set up what waited for it (the portal, the home-like link).
// Bonjour: OpenWrt's mDNS daemon starts at once; the agent publishes what it finds.
if (index(missing, 'umdns') >= 0)
run('/etc/init.d/umdns enable; /etc/init.d/umdns start');
if (length(missing) && length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/))))
run('( sleep 3; /usr/bin/dawnline apply; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
run('( sleep 3; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
return { updated: have, installed: missing };
/** The restarts the job asked for, in one go, after its final state is saved. */
function restarts() {
let cmds = [];
if (after.app)
push(cmds, '/etc/init.d/rpcd reload');
else if (after.apply)
push(cmds, '/usr/bin/dawnline apply');
if (after.uhttpd)
push(cmds, '/etc/init.d/uhttpd restart');
if (after.app || after.apply || after.uhttpd)
push(cmds, '/etc/init.d/dawnline restart');
if (length(cmds))
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
}
/* ---------- main ---------- */
const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs };
const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs };
const UPDATE_WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages' };
/** A line in the service log for each finished update (nothing when there was nothing to do). */
function log_update(name, r) {
// Dawnline's own update is logged by the new agent when it starts (also after install.sh).
if (name == 'amneziawg') {
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
slog('awg', 'up', b && a && b != a ? `updated · ${b} → ${a}` : `installed the ${AWG_SOURCES[r?.build]?.label ?? r?.build} build${a ? ' · ' + a : ''}`,
null, 'AmneziaWG');
}
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
slog('dawnline', 'up', `updated · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
ensure_dir(RUN_DIR);
// One job at a time (LuCI refuses a second one; an automatic run just skips its turn).
let LOCK = null;
for (let i = 0; i < 10 && !LOCK; i++) {
LOCK = upd.try_lock();
if (!LOCK)
system('usleep 100000 2>/dev/null || sleep 1');
}
if (!fs.access(STATE_DIR))
fs.mkdir(STATE_DIR, 0o755);
if (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save();
try {
if (job.action == 'check') {
let res = {};
for (let name, fn in CHECKS) {
phase(`Checking ${name}`);
try {
res[name] = fn();
}
catch (e) {
res[name] = { error: e.message };
}
}
save_check(res);
job.result = res;
}
else if (job.action == 'install') {
let what = job.component == 'all' ? [ 'amneziawg', 'app' ] : [ job.component ];
job.result = {};
for (let w in what) {
let i = index(w, ':');
let name = i < 0 ? w : substr(w, 0, i), arg = i < 0 ? null : substr(w, i + 1);
if (!INSTALLS[name])
die(`Unknown component ${name}`);
phase(`Updating ${name}`);
job.result[name] = INSTALLS[name](arg);
log_update(name, job.result[name]);
}
let which = job.component ? [ job.component ] : upd.TARGETS;
for (let w in which)
if (!CHECKS[w])
die(`Unknown component ${w}`);
job.result = run_checks(which);
let st = upd.auto_state();
note_found(job.result, st, false);
if (length(which) == length(upd.TARGETS))
st.check = time();
upd.auto_save(st);
}
else if (job.action == 'install')
install([ job.component ]);
else if (job.action == 'auto')
auto();
else
die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:<names>|all');
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done';
phase('Finished');
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(`Error: ${e.message}`);
if (job.action == 'install') {
let name = split(job.component, ':')[0];
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', 'update failed', e.message, UPDATE_WHO[name] ?? 'Dawnline');
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
if (job.action != 'check') {
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', `${job.auto ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline');
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
took: time() - job.started });
}
else
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
}
run(`rm -rf ${WORK_DIR}`);
system(`rm -rf '${ctx.work}'`);
job.finished = time();
delete job.current;
save();
restarts();
@@ -1,6 +1,6 @@
"use strict";(()=>{var rt=Object.create;var Pe=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var lt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ct=(t,e,a,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of st(e))!ot.call(t,v)&&v!==a&&Pe(t,v,{get:()=>e[v],enumerable:!(i=at(e,v))||i.enumerable});return t};var ut=(t,e,a)=>(a=t!=null?rt(it(t)):{},ct(e||!t||!t.__esModule?Pe(a,"default",{value:t,enumerable:!0}):a,t));var Ge=lt((Ke,Ue)=>{"use strict";var Oe=(function(){var t=function(M,k){var b=236,w=17,l=M,m=a[k],s=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,s=(function(o){for(var d=new Array(o),p=0;p<o;p+=1){d[p]=new Array(o);for(var x=0;x<o;x+=1)d[p][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),H(),Q(c,u),l>=7&&z(c),y==null&&(y=tt(l,m,f)),W(y,u)},E=function(c,u){for(var o=-1;o<=7;o+=1)if(!(c+o<=-1||r<=c+o))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=o&&o<=6&&(d==0||d==6)||0<=d&&d<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=d&&d<=4?s[c+o][u+d]=!0:s[c+o][u+d]=!1)},P=function(){for(var c=0,u=0,o=0;o<8;o+=1){T(!0,o);var d=v.getLostPoint(g);(o==0||c>d)&&(c=d,u=o)}return u},H=function(){for(var c=8;c<r-8;c+=1)s[c][6]==null&&(s[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)s[6][u]==null&&(s[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var o=0;o<c.length;o+=1){var d=c[u],p=c[o];if(s[d][p]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?s[d+x][p+C]=!0:s[d+x][p+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[Math.floor(o/3)][o%3+r-8-3]=d}for(var o=0;o<18;o+=1){var d=!c&&(u>>o&1)==1;s[o%3+r-8-3][Math.floor(o/3)]=d}},Q=function(c,u){for(var o=m<<3|u,d=v.getBCHTypeInfo(o),p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<6?s[p][8]=x:p<8?s[p+1][8]=x:s[r-15+p][8]=x}for(var p=0;p<15;p+=1){var x=!c&&(d>>p&1)==1;p<8?s[8][r-p-1]=x:p<9?s[8][15-p-1+1]=x:s[8][15-p-1]=x}s[r-8][8]=!c},W=function(c,u){for(var o=-1,d=r-1,p=7,x=0,C=v.getMaskFunction(u),_=r-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(s[d][_-R]==null){var K=!1;x<c.length&&(K=(c[x]>>>p&1)==1);var L=C(d,_-R);L&&(K=!K),s[d][_-R]=K,p-=1,p==-1&&(x+=1,p=7)}if(d+=o,d<0||r<=d){d-=o,o=-o;break}}},ae=function(c,u){for(var o=0,d=0,p=0,x=new Array(u.length),C=new Array(u.length),_=0;_<u.length;_+=1){var R=u[_].dataCount,K=u[_].totalCount-R;d=Math.max(d,R),p=Math.max(p,K),x[_]=new Array(R);for(var L=0;L<x[_].length;L+=1)x[_][L]=255&c.getBuffer()[L+o];o+=R;var Y=v.getErrorCorrectPolynomial(K),j=A(x[_],Y.getLength()-1),De=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Be=L+De.getLength()-C[_].length;C[_][L]=Be>=0?De.getAt(Be):0}}for(var $e=0,L=0;L<u.length;L+=1)$e+=u[L].totalCount;for(var me=new Array($e),he=0,L=0;L<d;L+=1)for(var _=0;_<u.length;_+=1)L<x[_].length&&(me[he]=x[_][L],he+=1);for(var L=0;L<p;L+=1)for(var _=0;_<u.length;_+=1)L<C[_].length&&(me[he]=C[_][L],he+=1);return me},tt=function(c,u,o){for(var d=$.getRSBlocks(c,u),p=D(),x=0;x<o.length;x+=1){var C=o[x];p.put(C.getMode(),4),p.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(p)}for(var _=0,x=0;x<d.length;x+=1)_+=d[x].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(w,8);return ae(p,d)};g.addData=function(c,u){u=u||"Byte";var o=null;switch(u){case"Numeric":o=B(c);break;case"Alphanumeric":o=F(c);break;case"Byte":o=J(c);break;case"Kanji":o=U(c);break;default:throw"mode:"+u}f.push(o),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return s[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),o=D(),d=0;d<f.length;d++){var p=f[d];o.put(p.getMode(),4),o.put(p.getLength(),v.getLengthInBits(p.getMode(),c)),p.write(o)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(o.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+u+"px;",o+='">',o+="<tbody>";for(var d=0;d<g.getModuleCount();d+=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: "+c+"px;",o+=" height: "+c+"px;",o+=" background-color: ",o+=g.isDark(d,p)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(c,u,o,d){var p={};typeof arguments[0]=="object"&&(p=arguments[0],c=p.cellSize,u=p.margin,o=p.alt,d=p.title),c=c||2,u=typeof u=="undefined"?c*4:u,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
`}return o%2&&c>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return nt(u);c-=1,u=typeof u=="undefined"?c*2:u;var o=g.getModuleCount()*c+u*2,d=u,p=o-u,x,C,_,R,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<o;x+=1){for(_=Math.floor((x-d)/c),j="",C=0;C<o;C+=1)R=1,d<=C&&C<p&&d<=x&&x<p&&g.isDark(_,Math.floor((C-d)/c))&&(R=0),j+=R?K:L;for(_=0;_<c;_+=1)Y+=j+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var o=g.getModuleCount(),d=0;d<o;d++)for(var p=0;p<o;p++)c.fillStyle=g.isDark(d,p)?"black":"white",c.fillRect(d*u,p*u,u,u)},g};t.stringToBytesFuncs={default:function(M){for(var k=[],b=0;b<M.length;b+=1){var w=M.charCodeAt(b);k.push(w&255)}return k}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(M,k){var b=(function(){for(var l=I(M),m=function(){var H=l.read();if(H==-1)throw"eof";return H},s=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,s+=1}if(s!=k)throw s+" != "+k;return r})(),w=63;return function(l){for(var m=[],s=0;s<l.length;s+=1){var r=l.charCodeAt(s);if(r<128)m.push(r);else{var y=b[l.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(w)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},v=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,b=7973,w=21522,l={},m=function(s){for(var r=0;s!=0;)r+=1,s>>>=1;return r};return l.getBCHTypeInfo=function(s){for(var r=s<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(s<<10|r)^w},l.getBCHTypeNumber=function(s){for(var r=s<<12;m(r)-m(b)>=0;)r^=b<<m(r)-m(b);return s<<12|r},l.getPatternPosition=function(s){return M[s-1]},l.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(r,y){return(r+y)%2==0};case i.PATTERN001:return function(r,y){return r%2==0};case i.PATTERN010:return function(r,y){return y%3==0};case i.PATTERN011:return function(r,y){return(r+y)%3==0};case i.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case i.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case i.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+s}},l.getErrorCorrectPolynomial=function(s){for(var r=A([1],0),y=0;y<s;y+=1)r=r.multiply(A([1,h.gexp(y)],0));return r},l.getLengthInBits=function(s,r){if(1<=r&&r<10)switch(s){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:"+s}else if(r<27)switch(s){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:"+s}else if(r<41)switch(s){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:"+s}else throw"type:"+r},l.getLostPoint=function(s){for(var r=s.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=s.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var H=-1;H<=1;H+=1)g+H<0||r<=g+H||P==0&&H==0||E==s.isDark(f+P,g+H)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;s.isDark(f,g)&&(q+=1),s.isDark(f+1,g)&&(q+=1),s.isDark(f,g+1)&&(q+=1),s.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)s.isDark(f,g)&&!s.isDark(f,g+1)&&s.isDark(f,g+2)&&s.isDark(f,g+3)&&s.isDark(f,g+4)&&!s.isDark(f,g+5)&&s.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)s.isDark(f,g)&&!s.isDark(f+1,g)&&s.isDark(f+2,g)&&s.isDark(f+3,g)&&s.isDark(f+4,g)&&!s.isDark(f+5,g)&&s.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)s.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),h=(function(){for(var M=new Array(256),k=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)k[M[b]]=b;var w={};return w.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},w.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},w})();function A(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var b=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),s=0;s<M.length-l;s+=1)m[s]=M[s+l];return m})(),w={};return w.getAt=function(l){return b[l]},w.getLength=function(){return b.length},w.multiply=function(l){for(var m=new Array(w.getLength()+l.getLength()-1),s=0;s<w.getLength();s+=1)for(var r=0;r<l.getLength();r+=1)m[s+r]^=h.gexp(h.glog(w.getAt(s))+h.glog(l.getAt(r)));return A(m,0)},w.mod=function(l){if(w.getLen Line truncated
`),hostName:h,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(A),port:String(a.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:h};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function gt(t){let e="";for(let a=0;a<t.length;a+=32768)e+=String.fromCharCode(...t.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mt(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),i=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+i.length);return new DataView(v.buffer).setUint32(0,t.length,!1),v.set(i,4),v}catch{return null}}async function Me(t,e,a=!0){let i=new TextEncoder().encode(JSON.stringify(pt(t,e))),v=a?await mt(i):null;return`vpn://${gt(v!=null?v:i)}`}function n(t,e={},...a){let i=document.createElement(t);for(let[h,A]of Object.entries(e))A==null||A===!1||(h.startsWith("on")&&typeof A=="function"?i.addEventListener(h.slice(2),A):h==="class"?i.className=String(A):A===!0?i.setAttribute(h,""):i.setAttribute(h,String(A)));let v=h=>{h==null||h===!1||(Array.isArray(h)?h.forEach(v):i.appendChild(typeof h=="string"?document.createTextNode(h):h))};return a.forEach(v),i}function O(t){let e=n("span",{class:"ic"});return e.innerHTML=He(t,"ic-svg"),e}var yt='<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>',Le=document.getElementById("app"),je,pe=(je=Le.dataset.base)!=null?je:"",bt=Le.dataset.title||"Dawnline",Ae=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Ve=0,wt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(pe)?pe.slice(1):"",_e=class extends Error{constructor(a,i){super(i);this.status=a}};async function ne(t,e){var v;let a=await fetch(`${pe}/api/${t}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),i=null;try{i=await a.json()}catch{}if(!a.ok)throw new _e(a.status,(v=i==null?void 0:i.error)!=null?v:`Request failed (${a.status})`);return i}function te(t,e=!1){let a=n("div",{class:`toast${e?" bad":""}`,role:"status"},t);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function le(t,e="Copied"){try{await navigator.clipboard.writeText(t)}catch{let a=n("textarea",{class:"offscreen"},t);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}te(e)}function ze(t,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),i=n("a",{href:a,download:t,class:"offscreen"});document.body.appendChild(i),i.click(),setTimeout(()=>{URL.revokeObjectURL(a),i.remove()},1e3)}var Z=null;function Je(t,e){let a=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,h)=>n("div",{class:h?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};t.addEventListener("mouseenter",a),t.addEventListener("mousemove",a),t.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function xt(t){let e=Math.max(1,...t),a=n("div",{class:"spark"});return t.forEach((i,v)=>{let h=n("i",{class:i?"":"zero"});h.style.height=`${Math.max(8,i/e*100)}%`;let A=t.length-1-v,$=new Date(Date.now()-A*864e5);Je(h,()=>[A===0?"Today":A===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),a.appendChild(h)}),a}var oe=null,ce=null;function ee(t=!1){if(!oe)return;let e=oe;if(oe=null,document.body.classList.remove("locked"),ce==null||ce(),ce=null,t){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function fe(t,e,...a){let i=!!oe;ee(!0);let v=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":t},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},t),e?n("span",{class:"muted s"},e):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},O("x"))),n("div",{class:"sheet-body"},...a)),h=n("div",{class:"sheet",onclick:A=>{A.target===h&&ee()}},v);return document.body.appendChild(h),document.body.classList.add("locked"),i?h.classList.add("open"):requestAnimationFrame(()=>h.classList.add("open")),oe=h,v}document.addEventListener("keydown",t=>{t.key==="Escape"&&(ge(),ee())});var X=null;function ge(){X==null||X.remove(),X=null}document.addEventListener("click",t=>{X&&!X.contains(t.target)&&ge()});function Mt(t,e){ge();let a=n(" Line truncated
`).flatMap((h,A)=>A?[`
`,Ye(h,e)]:[Ye(h,e)])),v=n("button",{class:"btn small",onclick:h=>{h.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),n("span",{},e?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},t.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>ze(t.filename,t.conf)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),v,n("button",{class:"btn small",onclick:h=>{h.preventDefault(),le(t.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),a))}async function ue(t,e,a){let i=a!=null?a:await Ee(t);if(!i)return;let v=await Me(i,`${i.server} · ${i.name}`),h=Ae(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:v},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let I=n("div",{class:"qr"});return I.innerHTML=Fe(i.conf),n("div",{class:"pane center"},I,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},v),n("button",{class:"btn small",onclick:()=>le(v,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Bt(i)},$=h?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),F=n("div",{class:"tabs",role:"tablist"}),J=I=>{F.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===I)),B.replaceChildren(A[I]())};for(let I of $)F.appendChild(n("button",{role:"tab","data-id":I,onclick:()=>J(I)},D[I]));J(e&&$.includes(e)?e:$[0]);let U=n("div",{class:"waiting"}),N=I=>{I!=null&&I.online?U.replaceChildren(n("span",{class:"ok"},`${t.name} is connected`)):I!=null&&I.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${ye(I.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};N(t);let G=window.setInterval(async()=>{try{let I=await ne("state");S=I,N(I.person.devices.find(re=>re.id===t.id))}catch{}},5e3);fe(t.handshake?`Connect ${t.name}`:`${t.name} is ready`,h?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,B,U),ce=()=>{clearInterval(G),S&&de(S)}}function $t(t){let e=n("input",{type:"text",value:t.name,maxlength:48,"aria-label":"Device name"});fe(`Rename ${t.name}`,null,n("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{S=(await ne(`devices/${t.id}`,{action:"rename",name:e.value})).state,ee(),de(S),te("Renamed")}catch(i){te(i.message,!0)}}},e,n("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Pt(t,e){let a=e.here===t.id;fe(`New keys for ${t.name}?`,null,n("p",{class:"muted"},a?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:async()=>{try{let i=await ne(`devices/${t.id}`,{action:"rotate"});S=i.state,de(S),ue(t,void 0,i.config)}catch(i){te(i.message,!0)}}},"New keys")))}function St(t){fe(`Remove ${t.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:async()=>{try{S=(await ne(`devices/${t.id}`,{action:"delete"})).state,ee(),de(S),te("Device removed")}catch(e){te(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Ze=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function ke(){return Ze||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Rt=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],Ce="",Nt=(async()=>{var e;let t=navigator.userAgentData;if(!t||!/ Line truncated
"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 je=ft((Ve,Ye)=>{"use strict";var qe=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,d=[],g={},T=function(l,f){a=c*4+17,s=(function(o){for(var h=new Array(o),v=0;v<o;v+=1){h[v]=new Array(o);for(var w=0;w<o;w+=1)h[v][w]=null}return h})(a),D(0,0),D(a-7,0),D(0,a-7),G(),I(),Q(l,f),c>=7&&z(l),y==null&&(y=at(c,m,d)),W(y,f)},D=function(l,f){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)f+h<=-1||a<=f+h||(0<=o&&o<=6&&(h==0||h==6)||0<=h&&h<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=h&&h<=4?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){T(!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],v=l[o];if(s[h][v]==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][v+C]=!0:s[h+w][v+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),v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<6?s[v][8]=w:v<8?s[v+1][8]=w:s[a-15+v][8]=w}for(var v=0;v<15;v+=1){var w=!l&&(h>>v&1)==1;v<8?s[8][a-v-1]=w:v<9?s[8][15-v-1+1]=w:s[8][15-v-1]=w}s[a-8][8]=!l},W=function(l,f){for(var o=-1,h=a-1,v=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 K=!1;w<l.length&&(K=(l[w]>>>v&1)==1);var L=C(h,_-N);L&&(K=!K),s[h][_-N]=K,v-=1,v==-1&&(w+=1,v=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,f){for(var o=0,h=0,v=0,w=new Array(f.length),C=new Array(f.length),_=0;_<f.length;_+=1){var N=f[_].dataCount,K=f[_].totalCount-N;h=Math.max(h,N),v=Math.max(v,K),w[_]=new Array(N);for(var L=0;L<w[_].length;L+=1)w[_][L]=255&l.getBuffer()[L+o];o+=N;var Y=u.getErrorCorrectPolynomial(K),j=k(w[_],Y.getLength()-1),Pe=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var L=0;L<C[_].length;L+=1){var Ne=L+Pe.getLength()-C[_].length;C[_][L]=Ne>=0?Pe.getAt(Ne):0}}for(var Re=0,L=0;L<f.length;L+=1)Re+=f[L].totalCount;for(var be=new Array(Re),he=0,L=0;L<h;L+=1)for(var _=0;_<f.length;_+=1)L<w[_].length&&(be[he]=w[_][L],he+=1);for(var L=0;L<v;L+=1)for(var _=0;_<f.length;_+=1)L<C[_].length&&(be[he]=C[_][L],he+=1);return be},at=function(l,f,o){for(var h=$.getRSBlocks(l,f),v=E(),w=0;w<o.length;w+=1){var C=o[w];v.put(C.getMode(),4),v.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(v)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].dataCount;if(v.getLengthInBits()>_*8)throw"code length overflow. ("+v.getLengthInBits()+">"+_*8+")";for(v.getLengthInBits()+4<=_*8&&v.put(0,4);v.getLengthInBits()%8!=0;)v.putBit(!1);for(;!(v.getLengthInBits()>=_*8||(v.put(b,8),v.getLengthInBits()>=_*8));)v.put(x,8);return ae(v,h)};g.addData=function(l,f){f=f||"Byte";var o=null;switch(f){case"Numeric":o=B(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+f}d.push(o),y=null},g.isDark=function(l,f){if(l<0||a<=l||f<0||a<=f)throw l+","+f;return s[l][f]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var f=$.getRSBlocks(l,m),o=E(),h=0;h<d.length;h++){var v=d[h];o.put(v.getMode(),4),o.put(v.getLength(),u.getLengthInBits(v.getMode(),l)),v.write(o)}for(var w=0,h=0;h<f.length;h++)w+=f[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}T(!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 v=0;v<g.getModuleCount();v+=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,v)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,f,o,h){var v={};typeof arguments[0]=="object"&&(v=arguments[0],l=v.cellSize,f=v.margin,o=v.alt,h=v.title),l=l||2,f=typeof f=="undefined"?l*4:f,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||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,v=o-f,w,C,_,N,K=Array(l+1).join("██"),L=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<v&&h<=w&&w<v&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?K:L;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 v=0;v<o;v++)l.fillStyle=g.isDark(h,v)?"black":"white",l.fillRect(h*f,v*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(),T=m(),D=String.fromCharCode(y<<8|d),P=g<<8|T;a[D]=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,p.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 T=0,D=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||D==s.isDark(d+P,g+I)&&(T+=1);T>5&&(y+=3+T-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})(),p=(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]^=p.gexp(p.glog(x.getAt(s))+p.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen Line truncated
`),hostName:p,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:p};return r.dns[0]&&($.dns1=r.dns[0]),r.dns[1]&&($.dns2=r.dns[1]),$}function 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:pe(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[p,k]of Object.entries(t))k==null||k===!1||(p.startsWith("on")&&typeof k=="function"?i.addEventListener(p.slice(2),k):p==="class"?i.className=String(k):k===!0?i.setAttribute(p,""):i.setAttribute(p,String(k)));let u=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(u):i.appendChild(typeof p=="string"?document.createTextNode(p):p))};return r.forEach(u),i}function O(e){let t=n("span",{class:"ic"});return t.innerHTML=Ge(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):"",Le=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 Le(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,p)=>n("div",{class:p?"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 p=n("i",{class:i?"":"zero"});p.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;Xe(p,()=>[k===0?"Today":k===1?"Yesterday":ve(Ie(De(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(p)}),r}async function Be(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var oe=null,le=null;function ee(e=!1){if(!oe)return;let t=oe;if(oe=null,document.body.classList.remove("locked"),le==null||le(),le=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function fe(e,t,...r){let 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()},O("x"))),n("div",{class:"sheet-body"},...r)),p=n("div",{class:"sheet",onclick:k=>{k.target===p&&ee()}},u);return document.body.appendChild(p),document.body.classList.add("locked"),i?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),o Line truncated
`).flatMap((p,k)=>k?[`
`,Qe(p,t)]:[Qe(p,t)])),u=n("button",{class:"btn small",onclick:p=>{p.preventDefault(),t=!t,u.replaceChildren(O(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),i()}},O("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},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)},O("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},O("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:p=>{p.preventDefault(),ce(e.conf,"Configuration copied")}},O("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Se(e);if(!i)return;let u=await Ae(i,`${i.server} · ${i.name}`),p=Ce(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},O("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Je(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:()=>Rt(i)},$=p?["app","qr","key","file"]:["qr","key","file"],E={app:"Open in app",qr:"QR code",key:"Key",file:"File"},B=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),B.replaceChildren(k[H]())};for(let H of $)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},E[H]));J(t&&$.includes(t)?t:$[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${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`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,B,U),le=()=>{clearInterval(F),S&&de(S)}}function Ht(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 It(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 Ot(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 Kt=[[/^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
@@ -1,368 +1,21 @@
#!/usr/bin/ucode
// Dawnline personal portal (CGI behind a dedicated uhttpd instance).
//
// GET /<code> the app shell (<code> = three words, the personal link)
// GET /<code>/assets/<file> its script, styles, fonts
// GET /<code>/api/state
// POST /<code>/api/devices { name, kind, public_key? }
// GET /<code>/api/devices/<id>/config
// POST /<code>/api/devices/<id> { action: rename|delete, name? }
//
// The personal link is the key: every request carries its code, there are
// no sessions. Without a valid code every path answers the same bare 404 —
// the root, a person's link, the API and the assets alike — so nothing tells
// a scanner there is a portal here. Wrong codes are rate-limited per IP
// (blocked addresses get the same 404 even with the right code).
// Regenerating the code in LuCI locks the old link out at once. POST bodies
// must be JSON from the same origin; Referrer-Policy keeps the code out of
// other sites' logs.
//
// The portal can only manage the person's own devices within their limit.
// Dawnline personal portal as a CGI script: the request handling itself is
// dawnline.portal.
'use strict';
import { stdin, stat, unlink, readfile } from 'fs';
import {
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, sh_bg, VERSION, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as view from 'dawnline.view';
import { stdin } from 'fs';
import { serve } from 'dawnline.portal';
const RATE = `${RUN_DIR}/portal-rate.json`;
const ASSETS = '/usr/share/dawnline/portal/assets';
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2' };
const FAIL_LIMIT = 8;
const FAIL_WINDOW = 900;
let env = {};
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'X-Frame-Options': 'DENY',
'Cache-Control': 'no-store',
'Strict-Transport-Security': 'max-age=31536000',
};
function headers(status, extra) {
let h = `Status: ${status}\r\n`;
for (let k, v in { ...SECURITY_HEADERS, ...(extra ?? {}) })
h += `${k}: ${v}\r\n`;
print(h + '\r\n');
}
function send_json(status, obj, extra) {
headers(status, { 'Content-Type': 'application/json', ...(extra ?? {}) });
print(sprintf('%J', obj));
exit(0);
}
function fail(status, msg) {
send_json(status, { error: msg });
}
function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
function page(status, base, title, code) {
// The build's time joins the version so every update busts the hour-long asset cache.
let q = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
headers(status, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
});
print(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<meta name="robots" content="noindex, nofollow">
<title>${html_escape(title)}</title>
<link rel="icon" href="${base}/assets/icon.svg${q}" type="image/svg+xml">
<link rel="stylesheet" href="${base}/assets/portal.css${q}">
</head>
<body>
<div id="app" data-base="${html_escape(base ?? '')}" data-title="${html_escape(title)}"></div>
<script src="${base}/assets/portal.js${q}" defer></script>
</body>
</html>
`);
exit(0);
}
/* ---------- request ---------- */
const method = getenv('REQUEST_METHOD') ?? 'GET';
const uri = getenv('REQUEST_URI') ?? '/';
// Behind a Cloudflare-proxied hostname every request comes from Cloudflare,
// and uhttpd does not hand CF-Connecting-IP to CGI: all those visitors share
// one bucket with a higher limit (three-word codes can't be guessed anyway).
const peer = getenv('REMOTE_ADDR') ?? '';
const via_cf = cloudflare_ip(peer);
const ip = via_cf ? 'cloudflare' : peer;
const fail_limit = via_cf ? FAIL_LIMIT * 25 : FAIL_LIMIT;
const qpos = index(uri, '?');
const path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
const query = qpos >= 0 ? substr(uri, qpos + 1) : '';
const segs = filter(split(path, '/'), (s) => s != '');
function query_param(name) {
for (let kv in split(query, '&')) {
let eq = index(kv, '=');
if (eq > 0 && substr(kv, 0, eq) == name)
return substr(kv, eq + 1);
}
return null;
}
function body() {
let len = +(getenv('CONTENT_LENGTH') ?? 0);
if (len <= 0)
return {};
if (len > 8192)
fail('413 Payload Too Large', 'Request too large.');
let raw = stdin.read(len);
try {
let j = json(raw);
return type(j) == 'object' ? j : {};
}
catch (e) {
fail('400 Bad Request', 'Invalid JSON.');
}
}
/* ---------- rate limiting ---------- */
function rate_state() {
let st = read_json(RATE, {});
let now = time();
for (let k, v in st)
if (now - v.first > FAIL_WINDOW)
delete st[k];
return st;
}
function rate_blocked() {
let v = rate_state()[ip];
return v != null && v.count >= fail_limit;
}
function rate_fail() {
let l = lock('portal-rate');
let st = rate_state();
let v = st[ip] ?? { first: time(), count: 0 };
v.count++;
st[ip] = v;
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
if (v.count == fail_limit)
live.add_event({ type: 'portal_blocked', detail: ip });
}
// Older versions kept sign-in sessions on flash; they mean nothing now.
if (stat(`${DATA_DIR}/sessions.json`))
unlink(`${DATA_DIR}/sessions.json`);
/* ---------- routing ---------- */
let m = core.load();
const redirect = m.settings.portal_redirect;
/**
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
* Files and LuCI's own paths always get the 404: at home this script is LuCI's error page, and a
* missing script must not turn into someone's website.
*/
function not_found() {
let parts = split(split(uri, '?')[0], '/');
let file = match(uri, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
if (redirect && !file) {
headers('302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
print('Moved\n');
}
else {
headers('404 Not Found', { 'Content-Type': 'text/plain' });
print('Not found\n');
}
exit(0);
}
const title = m.settings.portal_title || 'Dawnline';
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
// for it); names, and LuCI's web server at home, stay HTTPS-only.
if (getenv('HTTPS') != 'on') {
let h = getenv('HTTP_HOST') ?? '';
h = match(h, /^\[/) ? h : split(h, ':')[0];
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
not_found();
}
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
not_found();
const code = segs[0];
const base = `/${code}`;
const rest = slice(segs, 1);
let person = null;
for (let id, p in m.people)
if (p.code == code)
person = p;
// A wrong code or a blocked address: indistinguishable from a path that does
// not exist. Only well-formed guesses count towards the limit.
if (rate_blocked())
not_found();
if (person == null) {
rate_fail();
not_found();
}
const person_id = person.id;
// The app shell; it reads the code from its own URL and sends it along.
if (length(rest) == 0 && method == 'GET')
page('200 OK', base, title, code);
// Script, styles, icon and fonts (kept outside the web root).
if (rest[0] == 'assets' && length(rest) == 2 && method == 'GET') {
let name = rest[1];
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2)$/)?.[1];
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
if (data == null)
not_found();
headers('200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
print(data);
exit(0);
}
if (rest[0] != 'api')
not_found();
// CSRF: only same-origin JSON requests (uhttpd passes no custom headers to
// CGI; a cross-site page cannot send application/json without CORS, and it
// would need the code anyway).
if (method == 'POST') {
let origin = getenv('HTTP_ORIGIN');
if (!match(getenv('CONTENT_TYPE') ?? '', /^application\/json/) ||
(origin != null && origin != `${getenv('HTTPS') == 'on' ? 'https' : 'http'}://${getenv('HTTP_HOST')}`))
fail('403 Forbidden', 'Cross-site request refused.');
}
else if (method != 'GET')
fail('405 Method Not Allowed', 'Method not allowed.');
const api = slice(rest, 1);
function state() {
let usage = core.load_usage();
let dmp = live.dump();
let v = view.person_view(m, person, usage, dmp, view.states(m, usage));
let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel.
let here = null;
for (let id, d in m.devices)
if (d.person == person.id && d.address == peer)
here = id;
return {
title,
person: v,
here,
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv), device_mesh: !!srv?.device_mesh },
can_add: length(person.devices) < person.device_limit,
kinds: core.KINDS,
version: VERSION,
};
}
function own_device(id) {
let d = m.devices[id];
if (!d || d.person != person.id)
fail('404 Not Found', 'Device not found.');
return d;
}
if (api[0] == 'state' && method == 'GET')
send_json('200 OK', state());
if (api[0] == 'devices' && length(api) == 1 && method == 'POST') {
let b = body();
let l = lock('config');
let id;
try {
let c = core.open_cursor();
m = core.load(c);
person = m.people[person_id];
id = core.create_device(c, m, person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key || null });
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
}
catch (e) {
unlock(l);
fail('400 Bad Request', e.message);
}
unlock(l);
apply.sync();
m = core.load();
person = m.people[person_id];
live.add_event({ type: 'device_added', person: person.id, device: id, detail: m.devices[id].name, by: 'portal' });
core.mark_issued(m, id);
send_json('200 OK', { id, config: core.client_config(m, m.devices[id]), state: state() });
}
if (api[0] == 'devices' && length(api) == 3 && api[2] == 'config' && method == 'GET') {
let d = own_device(api[1]);
core.mark_issued(m, d.id);
send_json('200 OK', core.client_config(m, d));
}
if (api[0] == 'devices' && length(api) == 2 && method == 'POST') {
own_device(api[1]);
let b = body();
let l = lock('config');
try {
let c = core.open_cursor();
m = core.load(c);
if (b.action == 'rename')
core.rename_device(c, m, api[1], b.name);
else if (b.action == 'rotate') {
if (m.devices[api[1]].disabled)
die('The admin has turned this device off.');
core.rotate_device(c, m, api[1]);
}
else if (b.action == 'delete') {
let d = m.devices[api[1]];
core.delete_device(c, m, api[1]);
live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: d.name, dname: d.name, dkind: d.kind, by: 'portal' });
}
else
die('Unknown action.');
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
}
catch (e) {
unlock(l);
fail('400 Bad Request', e.message);
}
unlock(l);
if (b.action == 'delete')
apply.sync();
m = core.load();
person = m.people[person_id];
if (b.action == 'rotate') {
let d = m.devices[api[1]];
live.add_event({ type: 'device_keys', person: person.id, device: d.id, detail: d.name, by: 'portal' });
// The device this page came through would lose its tunnel before the
// answer gets out: load the new key a moment after answering.
if (d.address == peer)
sh_bg('sleep 3; /usr/bin/dawnline sync');
else
apply.sync();
core.mark_issued(m, d.id);
send_json('200 OK', { ok: true, config: core.client_config(m, d), state: state() });
}
send_json('200 OK', { ok: true, state: state() });
}
fail('404 Not Found', 'Not found.');
serve({
env,
headers: {},
read: (n) => stdin.read(n),
write: (s) => print(s),
});
@@ -70,7 +70,7 @@
}
},
"admin/network/dawnline/updates": {
"title": "Updates",
"title": "Components",
"order": 70,
"action": {
"type": "view",
@@ -4,33 +4,30 @@
"read": {
"ubus": {
"luci.dawnline": [
"rev",
"status",
"setup_defaults",
"health",
"service_log",
"backup_list",
"updates_status",
"updates_releases",
"updates_notes",
"updates_changes",
"person_usage",
"settings_get",
"portal_info",
"interfaces",
"events"
]
},
"uci": [
"dawnline",
"network",
"firewall"
]
}
},
"write": {
"ubus": {
"luci.dawnline": [
"*"
]
},
"uci": [
"dawnline"
]
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -3,11 +3,12 @@
'use strict';
import { ip2int } from 'dawnline.util';
import { ip2int, in_nets } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg';
const STATE_TEXT = {
no_server: 'their server is turned off',
@@ -30,21 +31,13 @@ function stop(steps, s) {
return steps;
}
/** The first of `nets` (IPv4 CIDRs, any prefix) that holds `ip`. */
function in_any(ip, nets) {
let n = ip2int(ip);
if (n == null)
return null;
for (let c in nets) {
let mm = match(c, /^([0-9.]+)\/([0-9]+)$/);
let base = mm ? ip2int(mm[1]) : null;
if (base == null)
continue;
let size = 1 << (32 - +mm[2]);
if (+mm[2] == 0 || (n >= base - base % size && n < base - base % size + size))
return c;
}
return null;
/** The tunnel subnet (of any server) that holds `ip`: never home, whatever routes cover it. */
function in_tunnels(m, ip) {
let nets = [];
for (let id, s in m.servers)
for (let t in core.tunnels(s))
push(nets, t.subnet);
return in_nets(ip, nets);
}
/** "10.0.1.20:445" → [ip, port]; a device id → its address. */
@@ -70,10 +63,15 @@ function peer_of(dmp, d) {
return dmp.peers[d.public_key];
}
/** What the device sends to the router: its configuration's AllowedIPs. */
function routed(m, srv, p, d) {
return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null };
}
/** The home network (interface) of a server that holds an address. */
function home_dev_of(srv, ip, snap) {
for (let h in net.server_net(srv, snap).home)
if (in_any(ip, h.nets))
if (in_nets(ip, h.nets))
return h.dev;
return null;
}
@@ -99,7 +97,7 @@ function connected(dmp, d, who) {
let peer = peer_of(dmp, d);
if (!peer || !(peer.handshake > 0))
return step(false, `${who} has never connected`, 'There is no session the router could reach.');
if (time() - peer.handshake >= live.ONLINE_WINDOW)
if (!live.online(dmp, d.id, peer))
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
return step(true, `${who} is connected`, '');
}
@@ -113,12 +111,14 @@ function from_device(m, d, t, states, dmp, snap) {
let steps = [ person_ok(m, p, d, states) ];
if (!steps[0].ok)
return steps;
let allowed = core.allowed_ips(m, srv, p);
let r = routed(m, srv, p, d);
let allowed = r.nets;
let via = (ip) => {
let hit = in_any(ip, allowed);
let hit = in_nets(ip, allowed);
let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
return hit
? step(true, 'Its configuration sends it through the tunnel', `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`)
: step(false, "Its configuration doesn't send it through the tunnel", `AllowedIPs ${join(', ', allowed)}: the device's own network handles it.`);
? step(true, `${r.what} sends it to the router`, what)
: step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`);
};
// Another device.
@@ -164,6 +164,11 @@ function from_device(m, d, t, states, dmp, snap) {
return steps;
}
// A tunnel address no device has.
let tn = in_tunnels(m, t.ip);
if (tn)
return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${tn}.`));
// Home.
let sn = net.server_net(srv, snap);
let hdev = home_dev_of(srv, t.ip, snap);
@@ -185,7 +190,7 @@ function from_device(m, d, t, states, dmp, snap) {
}
else {
let h = core.person_home(srv, p, snap);
if (!in_any(t.ip, h.nets))
if (!in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`));
}
@@ -195,7 +200,7 @@ function from_device(m, d, t, states, dmp, snap) {
}
// Another private address, or the internet.
if (in_any(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.'));
if (p.access == 'lan')
return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`));
@@ -211,7 +216,7 @@ function to_device(m, ip, d, states, dmp, snap) {
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
let who = `${p.name} · ${d.name}`;
let hdev = home_dev_of(srv, ip, snap);
let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap);
if (!hdev)
return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ];
let steps = [ step(true, `${ip} is at home (${hdev})`, '') ];
@@ -219,7 +224,7 @@ function to_device(m, ip, d, states, dmp, snap) {
return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`,
'Home devices reach only people with home access.'));
let h = core.person_home(srv, p, snap);
if (!in_any(ip, h.nets))
if (!in_nets(ip, h.nets))
return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.'));
push(steps, person_ok(m, p, d, states));
if (!steps[length(steps) - 1].ok)
@@ -238,7 +243,7 @@ export function check(m, from, to) {
die(`"${to}" is not a device or an IPv4 address.`);
let usage = core.load_usage();
let states = view.states(m, usage);
let dmp = live.dump();
let dmp = live.dump(m);
let snap = net.snapshot(true);
let steps;
if (a.dev)
@@ -1,481 +1,38 @@
// Dawnline — reconciliation. Turns /etc/config/dawnline into router state:
// * network interfaces (proto amneziawg), peers applied live with `awg syncconf`
// * firewall zones, forwardings and WAN rules (named sections dawnline_*)
// * nft table `inet dawnline` enforcing each person's access
// * network interfaces (dawnline.netifd) and the devices loaded live into
// them (dawnline.awg)
// * firewall zones, forwardings, WAN rules and reply routes (dawnline.fw)
// * the nft table `inet dawnline` enforcing each person's access (dawnline.nft)
// * hostnames in /tmp/hosts/dawnline
// * the "like a home device" path and the Home-only resolver (dawnline.loop)
// Only objects created by Dawnline are ever modified.
//
// apply(), sync() and sync_loop() run under one lock ('apply') and read the
// model inside it, so a rebuild and a runtime update never interleave and the
// last one to run always works from the newest configuration. The config lock
// (dawnline.store) is never taken while 'apply' is held.
import { cursor } from 'uci';
import { readfile, writefile, stat, unlink } from 'fs';
import {
q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq,
lock, unlock, slog, iface_intent, RUN_DIR
} from 'dawnline.util';
import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as nft from 'dawnline.nft';
import * as fw from 'dawnline.fw';
import * as netifd from 'dawnline.netifd';
import * as migrate from 'dawnline.migrate';
const HOSTS_FILE = '/tmp/hosts/dawnline';
/*
* Our own answers leave by the main table: the portal's (TCP) and each
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark
* the router's own traffic to internet addresses and divert it locally, which
* swallows replies to outside clients. These rules sit before such fwmark
* rules and only match our listening ports.
*/
const PREF_REPLY = 90;
/** The network signature the last apply() worked from (the agent compares against it). */
export const NET_SIG = `${RUN_DIR}/net.sig`;
// The last access-table error that was logged (each distinct failure once).
const NFT_ERR = `${RUN_DIR}/nft.err`;
function log(who, msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, who);
}
/* ---------- helpers ---------- */
/** Set an option only when it differs; returns true if something changed. */
function put(c, conf, sec, opt, val) {
let cur = c.get(conf, sec, opt);
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
if (cur != null) {
c.delete(conf, sec, opt);
return true;
}
return false;
}
if (type(val) == 'array') {
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
return false;
}
else if (cur == `${val}`)
return false;
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
return true;
}
function ensure_section(c, conf, sec, stype) {
if (c.get(conf, sec) == stype)
return false;
if (c.get(conf, sec) != null)
c.delete(conf, sec);
c.set(conf, sec, stype);
return true;
}
/**
* After committing a config ourselves (and applying it), record its new
* checksum so a later `reload_config` does not treat it as changed and
* restart unrelated services that reload on any network change.
*/
function ack_config(confs) {
let md5f = '/var/run/config.md5';
if (!stat(md5f))
return;
let lines = split(trim(readfile(md5f) ?? ''), '\n');
for (let conf in confs) {
let path = `/var/run/config.check/${conf}`;
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
if (!sum)
continue;
let found = false;
for (let i = 0; i < length(lines); i++)
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
lines[i] = `${sum} ${path}`;
found = true;
}
if (!found)
push(lines, `${sum} ${path}`);
}
writefile(md5f, join('\n', lines) + '\n');
}
/* ---------- network ---------- */
function sync_network(m) {
let c = cursor();
c.load('network');
let changed = false, touched = [];
let want = {};
for (let id, srv in m.servers) {
if (!srv.private_key)
continue;
let ifn = srv.ifname;
want[ifn] = true;
let addr = core.server_address(srv);
let pc = parse_cidr(srv.subnet);
// Per server: with several, each changed one has to be brought up again.
let mine = ensure_section(c, 'network', ifn, 'interface');
let set = (opt, val) => {
if (put(c, 'network', ifn, opt, val))
mine = true;
};
set('proto', 'amneziawg');
set('private_key', srv.private_key);
set('listen_port', srv.port);
set('addresses', [ `${addr}/${pc.prefix}` ]);
set('mtu', srv.mtu);
set('disabled', srv.enabled ? null : '1');
set('auto', srv.enabled ? null : '0');
set('_dawnline', id);
// For the log once the server is gone.
set('_dawnline_name', srv.name);
for (let k in core.OBF_KEYS)
set(`awg_${k}`, srv.obf[k]);
if (mine) {
changed = true;
push(touched, ifn);
// The hotplug log says why the tunnel goes down (not a failure).
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
}
}
// Remove interfaces Dawnline created for servers that no longer exist.
let stale = [];
c.foreach('network', 'interface', (s) => {
if (s._dawnline && !want[s['.name']])
push(stale, s['.name']);
});
for (let ifn in stale) {
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
system(`ifdown ${q(ifn)} 2>/dev/null`);
c.delete('network', ifn);
changed = true;
}
if (changed) {
c.commit('network');
ack_config([ 'network' ]);
system('ubus call network reload');
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
system(`ifup ${q(ifn)}`);
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
}
return changed;
}
/* ---------- firewall ---------- */
const LOOP_ZONE = 'dl_loop';
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
function sync_firewall(m, dry) {
let c = cursor();
c.load('firewall');
let changed = false, want = {};
let sec = (name, stype, opts) => {
want[name] = true;
changed = ensure_section(c, 'firewall', name, stype) || changed;
for (let k, v in opts)
changed = put(c, 'firewall', name, k, v) || changed;
};
let snap = net.snapshot(true);
let portal_zone = null, want_loop = false;
for (let id, srv in m.servers) {
if (!srv.private_key)
continue;
let z = `dawnline_${id}`;
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
sec(`${z}_zone`, 'zone', {
// Forward within the zone (device to device) is decided by the inet dawnline table.
name: srv.ifname, network: [ srv.ifname ],
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
});
// Access per person is enforced by the inet dawnline table; the zone
// only needs to be allowed to reach each home-network zone and WAN.
// The home network may open connections to the devices too (a router
// or a NAS on the tunnel); their answers pass the table as established.
for (let i, zone in sn.zones)
if (zone != sn.wan.zone && zone != srv.ifname) {
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
}
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
if (srv.lan_like) {
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
want_loop = true;
}
sec(`${z}_port`, 'rule', {
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
});
}
// The link into the netns that re-enters the router from the LAN.
if (want_loop) {
sec('dawnline_loop', 'zone', {
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
});
// The Home-only resolver in the netns reaches its upstream DNS this way.
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
}
if (m.settings.portal_enabled) {
let wan = portal_zone ?? 'wan';
sec('dawnline_portal', 'rule', {
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
dest_port: m.settings.portal_port, target: 'ACCEPT',
});
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
if (core.portal_http(m)) {
sec('dawnline_portal_http', 'rule', {
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
dest_port: core.portal_http_port(m), target: 'ACCEPT',
});
if (core.portal_http_public(m) == 80)
sec('dawnline_portal_80', 'redirect', {
name: 'Dawnline-Portal-80', src: wan, proto: 'tcp',
src_dport: 80, dest_port: core.portal_http_port(m), target: 'DNAT',
});
}
// Links use 443: from outside it lands on the portal (LuCI stays closed there).
if (core.portal_public_port(m) == 443 && m.settings.portal_port != 443)
sec('dawnline_portal_443', 'redirect', {
name: 'Dawnline-Portal-443', src: wan, proto: 'tcp',
src_dport: 443, dest_port: m.settings.portal_port, target: 'DNAT',
});
}
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
c.delete('firewall', s);
changed = true;
}
if (dry)
return changed;
if (changed) {
c.commit('firewall');
ack_config([ 'firewall' ]);
system('fw4 -q reload');
system("logger -t dawnline 'firewall updated'");
}
return changed;
}
/* ---------- nft access table ---------- */
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
// lan_ok: home access (the router itself, the mesh); lan_all: every home
// network; lan_part: device . network for people limited to some networks;
// mesh_pairs: device . device within a circle (or one person's own devices).
let sets = { lan_ok: [], lan_all: [], lan_part: [], mesh_pairs: [], inet_ok: [], svc_ok: [], dns_real: [] };
let snap = net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
if (!p || d.disabled || !d.address || states[p.id] != 'active')
continue;
// Plain DNS for whoever's internet does not go through the router.
// Home names: the plain resolver (their internet does not use the tunnel).
if (p.access == 'lan' && p.dns_mode == 'home')
push(sets.dns_real, d.address);
if (p.access == 'internet' || p.access == 'both')
push(sets.inet_ok, d.address);
if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) {
push(sets.lan_ok, d.address);
let srv = m.servers[p.server];
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
if (h.all)
push(sets.lan_all, d.address);
else
for (let n in h.nets)
push(sets.lan_part, `${d.address} . ${n}`);
// Who this device may reach directly: its circle, or at least its owner's devices.
if (srv?.mesh == 'circles') {
let ci = core.person_circle(m, p);
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
}
}
else if (p.access == 'lan')
for (let sid in p.services) {
let s = m.services[sid];
if (!s || !s.address)
continue;
for (let port in s.ports)
if (match(port, /^[0-9]+$/))
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
}
}
for (let g, addrs in groups)
for (let a in addrs)
for (let b in addrs)
if (a != b)
push(sets.mesh_pairs, `${a} . ${b}`);
return sets;
};
function set_elems(arr) {
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
function nft_table(m, sets) {
let ifs = [], lan = [];
let dns_addr = loop.client_dns();
let rt = loop.resolver_target();
let snap = net.snapshot();
for (let id, srv in m.servers)
if (srv.private_key) {
push(ifs, `"${srv.ifname}"`);
push(lan, ...net.server_net(srv, snap).nets);
}
lan = net.collapse(lan);
let t = [];
push(t, 'table inet dawnline {');
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
push(t, ' chain pre {');
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
push(t, ' type filter hook prerouting priority -160; policy accept;');
if (length(ifs))
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
push(t, ' }');
push(t, ' chain guard {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct state established,related accept');
push(t, ' icmp type echo-request fib daddr type local accept');
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
push(t, ' fib daddr type local ip saddr @lan_ok accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
push(t, ' ip daddr @lan_nets ip saddr @lan_all accept');
push(t, ' ip saddr . ip daddr @lan_part accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
// firewall has no forwarding between different servers' zones.
for (let id, srv in m.servers)
if (srv.private_key && srv.mesh == 'all')
push(t, ` iifname "${srv.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
else if (srv.private_key && srv.mesh == 'circles')
push(t, ` iifname "${srv.ifname}" ip saddr . ip daddr @mesh_pairs accept`);
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
push(t, ' ip saddr @inet_ok accept');
push(t, ' counter drop');
push(t, ' }');
// The other way: fw4 lets the server's home zones reach the tunnel; here
// only connections from its home networks to people with home access pass
// (paused, ended and internet-only people are not reachable). The admin's
// own port forwards (DNAT) stay with fw4.
push(t, ' chain inbound {');
push(t, ' type filter hook forward priority filter - 5; policy accept;');
if (length(ifs))
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
push(t, ' }');
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
push(t, ' ip saddr @lan_nets ip daddr @lan_all accept');
push(t, ' ip daddr . ip saddr @lan_part accept');
push(t, ' counter reject with icmpx admin-prohibited');
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`;
let lan_dns = loop.lan_dns();
push(t, ' chain dns {');
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
if (length(ifs))
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
for (let id, srv in m.servers) {
let a = srv.private_key ? core.server_address(srv) : null;
if (!a)
continue;
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
push(t, ` iifname "${srv.ifname}" ip daddr ${a} meta l4proto { tcp, udp } th dport 53 ${target}`);
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
function nft_load(script) {
ensure_dir(RUN_DIR);
let f = `${RUN_DIR}/nft.rules`;
writefile(f, script);
let r = sh(`nft -f ${f}`);
if (r.code != 0)
log('Access rules', "couldn't load", 'error', trim(r.out));
return r.code == 0;
}
/** Full table rebuild (structure changes: servers, LAN subnets). */
export function rebuild_nft(m, sets) {
let s = 'table inet dawnline\ndelete table inet dawnline\n' + nft_table(m, sets);
return nft_load(s);
};
/** Atomically replace set contents only. */
export function update_sets(sets) {
let s = '';
for (let name in [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'dns_real' ]) {
s += `flush set inet dawnline ${name}\n`;
if (length(sets[name]))
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
}
return nft_load(s);
};
export function remove_nft() {
system('nft delete table inet dawnline 2>/dev/null');
};
/* ---------- AmneziaWG peers ---------- */
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
let res = {};
for (let id, srv in m.servers) {
if (!srv.private_key || !srv.enabled)
continue;
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
res[id] = 'down';
continue;
}
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
for (let did, d in m.devices) {
let p = m.people[d.person];
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
continue;
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
push(lines, `AllowedIPs = ${d.address}/32`, '');
}
let f = `${RUN_DIR}/${srv.ifname}.conf`;
write_file(f, join('\n', lines));
let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`);
unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0)
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
}
return res;
};
/* ---------- hostnames ---------- */
function host_label(s) {
@@ -489,7 +46,7 @@ export function sync_hosts(m) {
if (m.settings.hostnames)
for (let id, d in m.devices) {
let p = m.people[d.person];
if (p && d.address)
if (p && ip2int(d.address) != null)
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
}
let ls = loop.status();
@@ -511,7 +68,7 @@ export function sync_hosts(m) {
return true;
};
/* ---------- entry points ---------- */
/* ---------- access table ---------- */
export function states_for(m, usage) {
let st = {};
@@ -520,21 +77,84 @@ export function states_for(m, usage) {
return st;
};
/** Runtime sync: peers + access sets + hostnames. Cheap; safe to call often. */
export function sync(m, usage) {
m ??= core.load();
usage ??= core.load_usage();
/** Per-person runtime membership (dawnline.nft). */
export function access_sets(m, usage, states) {
return nft.access_sets(m, usage, states);
};
/** Log an access-table failure once per distinct error; true when the table is in place. */
function nft_result(err) {
let was = readfile(NFT_ERR);
if (err == null) {
if (was != null)
unlink(NFT_ERR);
return true;
}
if (was != err) {
log('Access rules', "couldn't load — devices aren't loaded into the tunnels until they do", 'error', err);
ensure_dir(RUN_DIR);
writefile(NFT_ERR, err);
}
return false;
}
/**
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
* when that fails (no table yet at boot, or an older shape) — an error only
* when the rebuild fails too.
*/
function load_table(m, sets, full) {
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
if (err != null && !full)
err = nft.rebuild(m, sets);
return nft_result(err);
}
/** Full table rebuild (structure changes: servers, LAN subnets). */
export function rebuild_nft(m, sets) {
return nft_result(nft.rebuild(m, sets));
};
/** Atomically replace set contents only. */
export function update_sets(sets) {
return nft.update(sets) == null;
};
export function remove_nft() {
nft.remove();
};
/** For the watchdog (dawnline.fw). */
export function firewall_drift(m) {
return fw.drift(m);
};
/* ---------- runtime sync ---------- */
/*
* With the lock held: access sets first, and devices into the tunnels only
* once the table that limits them is in place.
*/
function locked_sync(m, usage, full) {
let states = states_for(m, usage);
let l = lock('apply');
let peers = sync_peers(m, states);
let sets = access_sets(m, usage, states);
if (!update_sets(sets))
rebuild_nft(m, sets);
let sets = nft.access_sets(m, usage, states);
let peers = {};
if (load_table(m, sets, full))
peers = awg.sync_peers(m, states);
sync_hosts(m);
unlock(l);
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/states.json`, states, 0o644);
return { peers, states };
}
/**
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
* hostnames. Cheap; safe to call often. The model is always read again under
* the lock (`m` is accepted for older callers and not used); `usage` is the
* caller's (the agent holds the live counters).
*/
export function sync(m, usage) {
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
};
/**
@@ -552,179 +172,66 @@ export function net_signature(m) {
return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() });
};
const PORTAL_CGI = '/usr/share/dawnline/portal/www/cgi-bin/portal';
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
/*
* At home the portal's hostname usually points at the router itself, where
* LuCI's web server owns 443. Paths it does not know (the portal's) go to the
* portal CGI through its error page, so the same link works inside and out.
*/
function sync_uhttpd(m) {
let want = m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443;
let c = cursor();
c.load('uhttpd');
let cur = c.get('uhttpd', 'main', 'error_page');
let changed = false;
if (want) {
if (!stat(LAN_CGI))
system(`ln -sf ${PORTAL_CGI} ${LAN_CGI}`);
if (cur == null && c.get('uhttpd', 'main')) {
c.set('uhttpd', 'main', 'error_page', LAN_CGI_URL);
changed = true;
}
}
else {
if (cur == LAN_CGI_URL) {
c.delete('uhttpd', 'main', 'error_page');
changed = true;
}
if (stat(LAN_CGI))
unlink(LAN_CGI);
}
if (changed) {
c.commit('uhttpd');
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
system(`logger -t dawnline ${q(want ? 'portal answers through the LuCI web server' : 'portal removed from the LuCI web server')}`);
}
}
/**
* For the watchdog: what is wrong with Dawnline's firewall, or null.
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
*/
export function firewall_drift(m) {
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
if (t == '')
return 'off';
if (sync_firewall(m, true))
return 'changed';
// Named rules show up in fw4's ruleset as comments.
let names = [];
for (let id, srv in m.servers)
if (srv.private_key && srv.enabled)
push(names, `Dawnline-${srv.ifname}`);
if (m.settings.portal_enabled)
push(names, 'Dawnline-Portal');
for (let n in names)
if (index(t, `${n}"`) < 0)
return 'not loaded';
return null;
};
/** For the watchdog: LuCI's web server should hand portal links to the portal, but does not. */
export function uhttpd_drift(m) {
if (!(m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443))
return false;
let c = cursor();
c.load('uhttpd');
let cur = c.get('uhttpd', 'main', 'error_page');
// Someone else's error page is theirs: Health explains, nothing to repair.
return cur == null || (cur == LAN_CGI_URL && !stat(LAN_CGI));
};
/** One `ipproto <p> sport <port> lookup main` rule per listening port and family. */
function sync_reply_routes(m) {
let want = [];
if (m.settings.portal_enabled) {
push(want, `tcp ${+m.settings.portal_port}`);
if (core.portal_http(m))
push(want, `tcp ${core.portal_http_port(m)}`);
}
for (let id, srv in m.servers)
if (srv.private_key && srv.enabled && +srv.port)
push(want, `udp ${+srv.port}`);
want = uniq(want);
for (let fam in [ '-4', '-6' ]) {
let have = [];
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
let mm = match(line, /ipproto (tcp|udp) sport (\d+) lookup main/);
if (mm)
push(have, `${mm[1]} ${mm[2]}`);
}
for (let h in have)
if (index(want, h) < 0)
sh(`ip ${fam} rule del priority ${PREF_REPLY} ipproto ${split(h, ' ')[0]} sport ${split(h, ' ')[1]} lookup main 2>/dev/null`);
for (let w in want)
if (index(have, w) < 0)
sh(`ip ${fam} rule add priority ${PREF_REPLY} ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
}
}
/**
* Keep the "like a home device" path and the resolver in step (agent tick).
* Cheap when nothing changed; rebuilds the access table when the netns
* address appears, moves or goes away (the guard allows DNS to it).
*/
export function sync_loop(m, usage, force) {
m ??= core.load();
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
let p = loop.ensure(m, force);
loop.sync_resolver(m);
sync_reply_routes(m);
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) {
usage ??= core.load_usage();
rebuild_nft(m, access_sets(m, usage, states_for(m, usage)));
sync_hosts(m);
}
let p = with_lock('apply', () => {
let mm = core.load();
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
let lp = loop.ensure(mm, force);
loop.sync_resolver(mm);
fw.sync_reply_routes(mm);
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before)
locked_sync(mm, usage ?? core.load_usage(), true);
return lp;
});
loop.remember(p);
return p;
};
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
function ensure_word_codes() {
let c = cursor();
c.load('dawnline');
let changed = false;
c.foreach('dawnline', 'person', (s) => {
if (s.code != null && !match(s.code, core.WORD_CODE)) {
c.set('dawnline', s['.name'], 'code', core.new_code());
c.delete('dawnline', s['.name'], 'words');
changed = true;
}
});
if (changed) {
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
log('Personal links', 'moved to word codes');
}
}
/* ---------- entry points ---------- */
/** Full reconcile: router configuration + runtime state. */
export function apply(opts) {
opts ??= {};
ensure_word_codes();
let m = core.load();
let usage = core.load_usage();
let l = lock('reconcile');
let net = sync_network(m);
let fw = sync_firewall(m);
sync_uhttpd(m);
let lp = loop.ensure(m, true);
loop.sync_resolver(m);
sync_reply_routes(m);
let states = states_for(m, usage);
rebuild_nft(m, access_sets(m, usage, states));
unlock(l);
let r = sync(m, usage);
return { network: net, firewall: fw, like_home: lp.error ? { error: lp.error } : !lp.off, peers: r.peers };
migrate.run();
let r = with_lock('apply', () => {
let m = core.load();
let usage = core.load_usage();
let network = netifd.sync(m);
let firewall = fw.sync(m);
let lp = loop.ensure(m, true);
loop.sync_resolver(m);
fw.sync_reply_routes(m);
let s = locked_sync(m, usage, true);
ensure_dir(RUN_DIR);
write_file(NET_SIG, net_signature(m), 0o644);
return { network, firewall, lp, peers: s.peers };
});
loop.remember(r.lp);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers };
};
/** Remove everything Dawnline created (used by the uninstaller). */
export function teardown() {
let m = core.load();
loop.remove();
unlink(loop.RESOLVER.conf);
m.servers = {};
m.settings.portal_enabled = false;
sync_network(m);
sync_firewall(m);
sync_uhttpd(m);
sync_reply_routes(m);
remove_nft();
unlink(HOSTS_FILE);
system('killall -HUP dnsmasq 2>/dev/null');
with_lock('apply', () => {
let m = core.load();
loop.remove();
unlink(loop.RESOLVER.conf);
m.servers = {};
m.settings.portal_enabled = false;
netifd.sync(m);
fw.sync(m);
fw.sync_reply_routes(m);
nft.remove();
unlink(HOSTS_FILE);
unlink(NET_SIG);
system('killall -HUP dnsmasq 2>/dev/null');
});
migrate.uhttpd();
// The agent's heartbeat check.
if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0)
system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1");
@@ -0,0 +1,493 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters and what the
// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the
// disguise off.
import { readfile, stat, unlink } from 'fs';
import {
q, sh, sh_out, rand_int, rand_bytes, valid_key, ensure_dir, write_file, read_json, write_json, lock, unlock,
slog, iface_status, DATA_DIR, RUN_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
jc: 'Jc', jmin: 'Jmin', jmax: 'Jmax', s1: 'S1', s2: 'S2', s3: 'S3', s4: 'S4',
h1: 'H1', h2: 'H2', h3: 'H3', h4: 'H4', i1: 'I1', i2: 'I2', i3: 'I3', i4: 'I4', i5: 'I5',
header_protection_key: 'HeaderProtectionKey', content_padding_addition: 'ContentPaddingAddition',
rekey_after_time: 'RekeyAfterTime', rekey_timeout: 'RekeyTimeout', reject_after_time: 'RejectAfterTime',
keepalive_timeout: 'KeepaliveTimeout', max_handshake_attempts: 'MaxHandshakeAttempts',
random_trailers: 'RandomTrailers', disable_cookies: 'DisableCookies',
};
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
/** The packages AmneziaWG comes in (the Components tab installs them). */
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
function proto_handler() {
try {
return 'amneziawg' in (json(sh_out('ubus call network get_proto_handlers 2>/dev/null') || '{}') ?? {});
}
catch (e) {
return false;
}
}
/**
* What of AmneziaWG is on the router:
* tools the awg tool and the netifd protocol script (amneziawg-tools)
* kmod the kernel module, loaded or on disk for the running kernel
* loaded the module is loaded
* handler netifd lists the amneziawg protocol
* missing packages that are not installed; ok: everything is in place
*/
export function state() {
let tools = stat(TOOL) != null && stat(PROTO) != null;
let loaded = stat('/sys/module/amneziawg') != null;
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let kmod = loaded || (rel != '' && stat(`/lib/modules/${rel}/amneziawg.ko`) != null);
let handler = tools && proto_handler();
let missing = filter(PACKAGES, (p) => p == 'kmod-amneziawg' ? !kmod : !tools);
return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler };
};
/** The kernel module and the awg tool are on the router. */
export function installed() {
let s = state();
return s.tools && s.kmod;
};
/* ---------- keys ---------- */
export function genkey() {
return sh_out('awg genkey');
};
export function pubkey(priv) {
if (!valid_key(priv))
return null;
return sh_out(`printf %s ${q(priv)} | awg pubkey`);
};
/** A preshared key is 32 random bytes: no tool needed (`awg genpsk` does the same). */
export function genpsk() {
return b64enc(rand_bytes(32));
};
/**
* Keys for a new device. With `public_key` (made in the browser) the private
* key never reaches the router. Never without a preshared key.
*/
export function new_keys(public_key) {
let psk = genpsk();
if (!valid_key(psk))
die('Key generation failed (no random data).');
if (public_key) {
if (!valid_key(public_key))
die('Invalid public key.');
return { public_key, preshared_key: psk };
}
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
return { private_key: priv, public_key: pub, preshared_key: psk };
};
/** A server's own key pair (set up once, on the server). */
export function server_keys() {
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
return { private_key: priv, public_key: pub };
};
/* ---------- obfuscation ---------- */
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
function rand_h(used) {
for (let i = 0; i < 50; i++) {
let v = rand_int(5, 2147483647);
if (!used[v]) {
used[v] = true;
return `${v}`;
}
}
}
/**
* What the installed AmneziaWG can do, from the netifd protocol script (the
* options it passes on) and the `awg` tool (the keys it accepts):
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
*/
export function caps() {
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? '';
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
return { v2, v3 };
};
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
/**
* Generate obfuscation parameters for a method:
* off plain WireGuard-compatible packets
* standard junk packets and random headers (any AmneziaWG client)
* strong more and larger junk (any AmneziaWG client)
* max AmneziaWG 3.1: protected headers, random trailers, padding,
* jittered timers and a DNS-like first packet — the values
* AmneziaVPN itself uses for 3.1 servers
*/
export function obf_preset(name) {
if (name == 'max')
return {
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
s1: '12', s2: '12', s3: '12', s4: '12',
h1: '1', h2: '2', h3: '3', h4: '4',
i1: DNS_MIMIC,
header_protection_key: sh_out('awg genkey'),
content_padding_addition: '10-100',
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
random_trailers: 'on', disable_cookies: 'on',
};
if (name == 'off')
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
let strong = name == 'strong';
let o = {};
o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`;
let jmin = rand_int(64, strong ? 128 : 96);
o.jmin = `${jmin}`;
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
while (s1 + 56 == s2)
s2 = rand_int(15, 64);
o.s1 = `${s1}`;
o.s2 = `${s2}`;
let used = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
o[k] = rand_h(used);
return o;
};
export function obf_errors(o) {
let errs = [];
for (let k, r in OBF_SPEC) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) {
if (!(v == '0' && (k == 'jmin' || k == 'jmax')))
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
}
}
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
push(errs, 'jmin > jmax');
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, 's1 + 56 = s2');
let hs = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, `${k} must be a number or range`);
else if (hs[v])
push(errs, 'h1-h4 must be distinct');
hs[v] = true;
}
return errs;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
let nets = core.person_home(srv, p).nets;
// With devices reaching each other, the whole tunnel network (the router's
// address is in it); otherwise only the router's own address.
let a = core.server_address(srv);
if (srv.device_mesh && srv.subnet)
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
// The resolver address must be reachable through the tunnel too (not the fallback).
let dns = core.client_dns(m, srv, p)[0];
if (dns)
push(nets, `${dns}/32`);
return net.collapse(nets);
}
return [ '0.0.0.0/0', '::/0' ];
};
/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */
export function obf_neutral(o) {
for (let k in core.OBF_KEYS) {
let v = o?.[k];
if (v == null || v == '')
continue;
let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0';
if (`${v}` != want)
return false;
}
return true;
};
export function client_config(m, dev) {
let p = m.people[dev.person];
let srv = p ? m.servers[p.server] : null;
if (!srv)
return null;
let host = core.endpoint_host(m, srv);
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let dns = core.client_dns(m, srv, p);
let lines = [ '[Interface]' ];
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
push(lines, `Address = ${dev.address}/32`);
if (length(dns))
push(lines, `DNS = ${join(', ', dns)}`);
push(lines, `MTU = ${srv.mtu}`);
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
// out, so any WireGuard app accepts the file.
if (!obf_neutral(srv.obf))
for (let k in core.OBF_KEYS)
if (srv.obf[k] != null && srv.obf[k] != '')
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
push(lines, '', '[Peer]');
push(lines, `PublicKey = ${srv.public_key}`);
if (dev.preshared_key)
push(lines, `PresharedKey = ${dev.preshared_key}`);
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
push(lines, `Endpoint = ${ep}:${srv.port}`);
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
return {
name: dev.name,
person: p.name,
server: srv.name,
filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`,
conf: join('\n', lines) + '\n',
has_private_key: dev.private_key != '',
amnezia: {
host,
port: srv.port,
mtu: `${srv.mtu}`,
dns,
allowed_ips: allowed,
client_ip: dev.address,
client_priv_key: dev.private_key,
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
obfuscation: srv.obf,
},
};
};
/* ---------- the server's tunnel ---------- */
/** netifd options of the server's interface (proto amneziawg). */
export function netifd_options(srv) {
let addr = core.server_address(srv);
let prefix = split(srv.subnet, '/')[1];
let o = {
proto: 'amneziawg',
private_key: srv.private_key,
listen_port: srv.port,
addresses: [ `${addr}/${prefix}` ],
mtu: srv.mtu,
};
for (let k in core.OBF_KEYS)
o[`awg_${k}`] = srv.obf[k];
return o;
};
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
let res = {};
for (let id, srv in m.servers) {
// Only Dawnline's own interfaces: never another tunnel of the same name (core.tunnels).
if (!srv.enabled || !length(core.tunnels(srv)))
continue;
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
res[id] = 'down';
continue;
}
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
for (let did, d in m.devices) {
let p = m.people[d.person];
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
continue;
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
push(lines, `AllowedIPs = ${d.address}/32`, '');
}
let f = `${RUN_DIR}/${srv.ifname}.conf`;
write_file(f, join('\n', lines));
let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`);
unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0)
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
}
return res;
};
/**
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
* lines always have 9. The tool fails when any one interface can't be read,
* but still prints the others: those are kept and `ok` is false, so only the
* interfaces listed in `ifaces` are known.
*/
export function dump() {
let r = sh('awg show all dump');
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) == 9) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
endpoint: ep,
handshake: +f[5],
rx: +f[6],
tx: +f[7],
};
}
else if (length(f) >= 5) {
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
}
}
return out;
};
/** Is the server's tunnel up and listening (for status and Overview). */
export function server_state(srv) {
let st = iface_status(srv.ifname);
return { up: !!st?.up, uptime: st?.uptime ?? 0 };
};
/* ---------- watchdog ---------- */
/** Why a tunnel is down, from netifd and the last related syslog lines. */
export function iface_errors(ifname) {
let s = iface_status(ifname);
let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : ''));
// Only what explains a failure, not the ordinary "is now up/down" lines.
let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`);
return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x));
};
/**
* What the watchdog looks at for AmneziaWG (see dawnline.watchdog):
* AmneziaWG itself, then every running server's tunnel. `ctx.udp_listening`,
* `ctx.reapply` and `ctx.owner` (dawnline.netifd) come from the watchdog
* (ops, apply and netifd import this module).
*/
export function probes(m, ctx) {
let out = [];
let srvs = filter(values(m.servers), (x) => x.enabled && x.private_key);
if (!length(srvs))
return out;
// AmneziaWG itself first: without it no tunnel can run (they come back on the next pass).
// Missing packages and an unknown protocol are reported once; only the module can be loaded here.
let st = state();
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' };
if (!st.tools || !st.kmod) {
push(out, { ...base, ok: false, repair: null,
problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`,
detail: () => `Missing: ${join(', ', st.missing)}.` });
return out;
}
push(out, { ...base, ok: st.loaded && st.handler,
problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot",
detail: !st.loaded
? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4")
: () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
});
// Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one.
if (st.loaded && !st.handler)
return out;
for (let srv in srvs) {
// A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted:
// an interface of the same name that isn't Dawnline's may be your LAN.
let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null;
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"`
: own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null);
if (why) {
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: why, back: 'AmneziaWG is running again',
detail: () => 'Choose another interface name in the server settings.',
});
continue;
}
let s = iface_status(srv.ifname);
let up = !!s?.up;
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port),
problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`,
back: `AmneziaWG is running again · accepting connections on port ${srv.port}`,
detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply },
});
}
return out;
};
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
function fnv32(str) {
let h = 2166136261;
for (let i = 0; i < length(str); i++)
h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff;
return sprintf('%08x', h);
}
/** What a device holds, minus its private key: changes when it must import again. */
export function config_fingerprint(m, dev) {
let c = dev ? client_config(m, dev) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^PrivateKey/)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
export function issued() {
return read_json(ISSUED, {});
};
/** Remember that a device was just given its current configuration. */
export function mark_issued(m, id) {
let fp = config_fingerprint(m, m.devices[id]);
if (!fp)
return;
let l = lock('issued');
let all = issued();
if (all[id] != fp) {
all[id] = fp;
for (let k in keys(all))
if (!m.devices[k])
delete all[k];
ensure_dir(DATA_DIR, 0o700);
write_json(ISSUED, all, 0o600);
}
unlock(l);
};
@@ -0,0 +1,55 @@
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
// builds per OpenWrt release and target (the kernel module must match the
// firmware). Used by the updater and the Components RPCs.
import { readfile } from 'fs';
import { connect } from 'ubus';
import * as pkg from 'dawnline.pkg';
export const SOURCES = {
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
};
/** Tried in this order when no build is chosen. */
export const ORDER = [ 'slava', 'grey' ];
export const PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
export const RU = 'luci-i18n-amneziawg-ru';
/**
* This firmware as the builds name it: { tag: 'v24.10.6', postfix:
* '_v24.10.6_aarch64_cortex-a53_mediatek_filogic', ext }, or null.
*/
export function firmware() {
let u = connect();
let b = u?.call('system', 'board') ?? {};
u?.disconnect();
let rel = b.release ?? {};
let target = split(rel.target ?? '', '/');
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
if (!rel.version || length(target) != 2 || !arch)
return null;
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext() };
};
/** The file name of a package in a build. */
export function asset(fw, name) {
return `${name}${fw.postfix}.${fw.ext}`;
};
/** The same firmware, another release of its series (v24.10.6 → v24.10.8). */
export function for_tag(fw, tag) {
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
};
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
export function gen(version) {
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
};
/** The installed AmneziaWG packages: { name: version | null }. */
export function installed() {
let r = {};
for (let p in PKGS)
r[p] = pkg.version(p);
return r;
};
@@ -0,0 +1,285 @@
// Dawnline — backups (tar.gz of the config and its data files), restoring
// them, and the JSON export / import. Whatever comes back in is checked first:
// only Dawnline's own regular files, and servers that cannot take over one of
// the router's own interfaces or networks.
import { readfile, stat, unlink, lsdir } from 'fs';
import { cursor } from 'uci';
import {
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as health from 'dawnline.health';
const BACKUP_DIR = `${DATA_DIR}/backups`;
const KEEP_BACKUPS = 10;
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
/** What a backup holds (paths inside the archive, relative to /). */
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
const MAX_UNPACKED = 16 * 1024 * 1024;
/* ---------- checking a configuration before it is used ---------- */
/**
* What is wrong with the servers of a configuration about to replace the
* current one (cursor `c` holds it): each must have a valid, unique interface
* name that is not one of the router's own interfaces, a free subnet and a
* unique port. [] when it can be used.
*/
export function config_errors(c) {
let m = core.load(c);
let errs = [];
let nc = cursor();
nc.load('network');
let foreign = health.foreign_subnets();
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
let who = `Server ${srv.name}`;
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
push(errs, `${who}: ${e}`);
if (ifnames[srv.ifname])
push(errs, `${who}: interface ${srv.ifname} is also used by ${ifnames[srv.ifname]}.`);
ifnames[srv.ifname] = srv.name;
let t = nc.get('network', srv.ifname);
if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null)))
push(errs, `${who}: ${srv.ifname} is one of the router's own network interfaces.`);
if (ports[srv.port])
push(errs, `${who}: UDP ${srv.port} is also used by ${ports[srv.port]}.`);
ports[srv.port] = srv.name;
if (srv.subnet)
push(subnets, srv.subnet);
}
return errs;
};
/** Check the config file in `dir` (as /etc/config/dawnline would be); dies listing the problems. */
function check_config_dir(dir) {
ensure_dir(`${dir}/.delta`, 0o700);
// Its own delta directory: changes staged in LuCI must not leak into the check.
let c = cursor(dir, `${dir}/.delta`);
if (!c.load('dawnline'))
die('The configuration in this file cannot be read.');
let errs = config_errors(c);
if (length(errs))
die(`This configuration can't be used: ${join(' ', errs)}`);
}
/** A private scratch directory under RUN_DIR (the caller removes it). */
function scratch(kind) {
ensure_dir(RUN_DIR);
let dir = `${RUN_DIR}/${kind}.${rand_hex(4)}`;
system(`rm -rf ${q(dir)}; mkdir -m 700 -p ${q(dir)}`);
return dir;
}
/* ---------- backups ---------- */
export function backup_list() {
let out = [];
for (let f in lsdir(BACKUP_DIR) ?? []) {
let mm = match(f, NAME);
if (!mm)
continue;
let st = stat(`${BACKUP_DIR}/${f}`);
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
}
return sort(out, (a, b) => b.created - a.created);
};
/**
* Make a backup now; returns its name. The oldest beyond KEEP_BACKUPS are
* removed, except `keep` (the backup being restored, which must survive the
* backup made just before restoring it).
*/
export function backup_create(reason, keep) {
// Flush live counters first so the backup has current usage.
let u = read_json(`${RUN_DIR}/usage.json`, null);
if (u)
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
live.persist_events();
ensure_dir(BACKUP_DIR, 0o700);
let t = localtime();
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
let files = join(' ', map(filter(FILES, (f) => file_exists(`/${f}`)), q));
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
if (r.code != 0)
die(`Backup failed: ${trim(r.out)}`);
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let all = backup_list();
let old = filter(all, (b) => b.name != keep && b.name != name);
let room = KEEP_BACKUPS - 1 - (length(old) < length(all) - 1 ? 1 : 0);
for (let i = room; i < length(old); i++)
unlink(`${BACKUP_DIR}/${old[i].name}`);
return name;
};
function backup_path(name) {
if (!match(name ?? '', NAME))
die('Invalid backup name.');
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
return p;
}
/**
* Validate an archive: only Dawnline's own files, all of them regular files
* (no links, devices or directories), within a sane unpacked size.
*/
function check_archive(path) {
let r = sh(`tar -tvzf ${q(path)}`);
if (r.code != 0)
die('Not a valid backup archive.');
let has_config = false, total = 0;
for (let line in split(trim(r.out), '\n')) {
let f = split(trim(line), /[ \t]+/);
let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, '');
// "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b".
if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0)
die(`Unexpected entry in backup: ${name}`);
if (index(FILES, name) < 0)
die(`Unexpected file in backup: ${name}`);
total += +(f[2] ?? 0) || 0;
if (name == 'etc/config/dawnline')
has_config = true;
}
if (!has_config)
die('Backup does not contain /etc/config/dawnline.');
if (total > MAX_UNPACKED)
die('Backup is too large.');
}
/** Put the files unpacked in `dir` in place, under the config lock. */
function install_files(dir) {
ensure_dir(DATA_DIR, 0o700);
let l = lock('config');
for (let f in FILES) {
let data = readfile(`${dir}/${f}`);
if (data != null)
write_file(`/${f}`, data, 0o600);
}
unlock(l);
system('chmod 600 /etc/config/dawnline');
}
export function backup_restore(name, path) {
path ??= backup_path(name);
check_archive(path);
let dir = scratch('restore');
try {
let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`);
if (r.code != 0)
die('Not a valid backup archive.');
check_config_dir(`${dir}/etc/config`);
backup_create('pre-restore', name);
install_files(dir);
}
catch (e) {
system(`rm -rf ${q(dir)}`);
die(e.message);
}
system(`rm -rf ${q(dir)}`);
// Live counters must follow the restored file.
unlink(`${RUN_DIR}/usage.json`);
unlink(`${RUN_DIR}/events.json`);
return apply.apply();
};
export function backup_delete(name) {
unlink(backup_path(name));
return true;
};
export function backup_read(name) {
return b64enc(readfile(backup_path(name)));
};
export function backup_upload(data_b64) {
let data = b64dec(data_b64 ?? '');
if (!data || length(data) > 4 * 1024 * 1024)
die('Upload is empty or too large.');
ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data);
let res;
try {
res = backup_restore(null, tmp);
}
catch (e) {
unlink(tmp);
die(e.message);
}
unlink(tmp);
return res;
};
/* ---------- export / import (JSON) ---------- */
export function export_json() {
let c = cursor();
c.load('dawnline');
let sections = [];
c.foreach('dawnline', null, (s) => {
let o = { '.type': s['.type'], '.name': s['.name'] };
for (let k, v in s)
if (substr(k, 0, 1) != '.')
o[k] = v;
push(sections, o);
});
return { format: 'dawnline', version: VERSION, exported: time(), sections };
};
/** An export as /etc/config/dawnline text; dies on anything that is not one. */
function export_to_uci(data) {
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
die('Not a Dawnline export.');
let types = { settings: true, server: true, person: true, device: true, service: true, circle: true };
let esc = (x) => replace(`${x}`, "'", "'\\''");
let lines = [];
for (let s in data.sections) {
if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
die(`Invalid section ${s?.['.name']}.`);
push(lines, `config ${s['.type']} '${s['.name']}'`);
for (let k, v in s) {
if (substr(k, 0, 1) == '.')
continue;
if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))
die(`Invalid option ${k}.`);
if (type(v) == 'array')
for (let x in v) {
if (type(x) != 'string')
die(`Invalid option ${k}.`);
push(lines, `\tlist ${k} '${esc(x)}'`);
}
else
push(lines, `\toption ${k} '${esc(v)}'`);
}
push(lines, '');
}
return join('\n', lines);
}
export function import_json(data) {
let text = export_to_uci(data);
let dir = scratch('import');
try {
write_file(`${dir}/dawnline`, text, 0o600);
check_config_dir(dir);
}
catch (e) {
system(`rm -rf ${q(dir)}`);
die(e.message);
}
system(`rm -rf ${q(dir)}`);
backup_create('pre-import');
let l = lock('config');
write_file('/etc/config/dawnline', text, 0o600);
unlock(l);
return apply.apply();
};
@@ -1,149 +0,0 @@
// Dawnline: "Find home devices" (Bonjour over the tunnel). Multicast DNS does
// not cross WireGuard, so what umdns sees on the home networks is published
// as unicast DNS-SD records in dnsmasq: iPhone, iPad and Mac look there
// (browse domains under the home domain and the reverse zone of their own
// tunnel address) and list AirPlay, printers and shared Macs as at home.
'use strict';
import { readfile, writefile, unlink, lsdir, stat } from 'fs';
import { read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
import * as ops from 'dawnline.ops';
const FILE = 'dawnline-bonjour.conf';
const STATE = `${RUN_DIR}/bonjour.json`;
/** dnsmasq restarts to read the records: at most this often when only TXT data changed. */
const QUIET = 600;
/** Not useful from a phone, or not a service at all. */
const SKIP = [ '_device-info._tcp', '_companion-link._tcp', '_sleep-proxy._udp', '_workstation._tcp', '_rdlink._tcp', '_hap._udp' ];
export function enabled(m) {
for (let id, srv in m.servers)
if (srv.bonjour && srv.private_key)
return true;
return false;
};
/** dnsmasq's conf-dirs (one per instance), from its generated configs. */
function conf_dirs() {
let out = [];
for (let f in lsdir('/var/etc') ?? []) {
if (!match(f, /^dnsmasq\.conf\./))
continue;
for (let line in split(readfile(`/var/etc/${f}`) ?? '', '\n')) {
let mm = match(line, /^conf-dir=([^,]+)/);
if (mm && index(out, mm[1]) < 0)
push(out, mm[1]);
}
}
return out;
}
/** An instance name as dnsmasq takes it: printable ASCII, no dots or commas. */
function instance(s) {
s = replace(s ?? '', /[\u2018\u2019]/g, "'");
s = replace(s, /[\u201c\u201d]/g, '');
s = replace(s, /[^\x20-\x7e]/g, '');
s = replace(s, /[.,"\\]/g, ' ');
s = trim(replace(s, / +/g, ' '));
return substr(s, 0, 63);
}
function label(s) {
return substr(trim(replace(replace(s ?? '', /[^A-Za-z0-9-]+/g, '-'), /^-+|-+$/g, '')), 0, 63);
}
/** Reverse zone of a server's tunnel network (its /24), where devices look for browse domains. */
function reverse24(subnet) {
let mm = match(subnet ?? '', /^([0-9]+)\.([0-9]+)\.([0-9]+)\.[0-9]+\//);
return mm ? `0.${mm[3]}.${mm[2]}.${mm[1]}.in-addr.arpa` : null;
}
/** The records, and a signature of what matters without TXT data. */
export function records(m, services) {
let dom = m.settings.domain || 'lan';
let lines = [], sig = [];
let zones = [ dom ];
for (let id, srv in m.servers)
if (srv.bonjour && reverse24(srv.subnet))
push(zones, reverse24(srv.subnet));
for (let z in zones)
for (let b in [ 'b', 'db', 'lb' ])
push(lines, `ptr-record=${b}._dns-sd._udp.${z},${dom}`);
let types = {}, hosts = {};
for (let s in services) {
if (!s.port || index(SKIP, s.type) >= 0 || !match(s.type, /^_[A-Za-z0-9-]+\._(tcp|udp)$/))
continue;
let name = instance(s.name), host = label(s.host) || label(replace(s.address, /\./g, '-'));
if (name == '')
continue;
let full = `${name}.${s.type}.${dom}`;
types[s.type] = true;
hosts[host] = s.address;
push(lines, `ptr-record=${s.type}.${dom},${full}`);
push(lines, `srv-host=${full},${host}.${dom},${s.port}`);
let txt = filter(s.txt ?? [], (t) => type(t) == 'string' && length(t) <= 255 && !match(t, /["\\\n]/));
push(lines, length(txt) ? `txt-record=${full},${join(',', map(txt, (t) => `"${t}"`))}` : `txt-record=${full}`);
push(sig, `${full}|${host}|${s.port}`);
}
for (let t in sort(keys(types)))
push(lines, `ptr-record=_services._dns-sd._udp.${dom},${t}.${dom}`);
for (let h in sort(keys(hosts))) {
push(lines, `host-record=${h}.${dom},${hosts[h]}`);
push(sig, `${h}=${hosts[h]}`);
}
return { conf: '# Written by Dawnline: home devices for Bonjour over the tunnel.\n' + join('\n', lines) + '\n', sig: join('\n', sort(sig)) };
};
function restart_dnsmasq() {
system('/etc/init.d/dnsmasq restart >/dev/null 2>&1');
}
/**
* Keep the records in step with what umdns sees (agent tick and apply).
* Turned off: the records go away.
*/
export function sync(m, force) {
let dirs = conf_dirs();
if (!enabled(m) || !ops.mdns_running()) {
let removed = false;
for (let d in dirs)
if (stat(`${d}/${FILE}`)) {
unlink(`${d}/${FILE}`);
removed = true;
}
if (removed)
restart_dnsmasq();
unlink(STATE);
return false;
}
let r = records(m, ops.mdns_services());
let st = read_json(STATE, {});
let now = time();
let same = st.conf == r.conf;
let quiet = !force && st.sig == r.sig && now - (st.ts ?? 0) < QUIET;
let missing = length(filter(dirs, (d) => !stat(`${d}/${FILE}`)));
if ((same || quiet) && !missing)
return false;
for (let d in dirs) {
ensure_dir(d);
writefile(`${d}/${FILE}`, r.conf);
system(`chmod 644 ${d}/${FILE}`);
}
write_json(STATE, { conf: r.conf, sig: r.sig, ts: now }, 0o644);
restart_dnsmasq();
return true;
};
/** Turning it on: umdns must run and look at the home networks. */
export function start_mdns() {
system('/etc/init.d/umdns enable >/dev/null 2>&1; /etc/init.d/umdns start >/dev/null 2>&1');
};
export function view(m) {
let s = ops.mdns_running() ? ops.mdns_services() : [];
return {
running: ops.mdns_running(),
services: length(filter(s, (x) => x.port && index(SKIP, x.type) < 0)),
};
};
@@ -1,38 +1,34 @@
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it,
// allocates addresses, generates keys and renders client configurations.
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it
// and allocates addresses. Nothing here knows how the tunnel works: dawnline.awg
// renders AmneziaWG configurations and runs the tunnels.
import { cursor } from 'uci';
import { readfile } from 'fs';
import {
q, sh, sh_out, valid_name, valid_key, valid_host, valid_date, slugify,
parse_cidr, cidr_str, cidr_overlaps, int2ip, ip2int, in_cidr, rand_token, rand_hex, rand_int, rand_bytes,
date_end, month_key, read_json, write_json, ensure_dir, lock, unlock, DATA_DIR, RUN_DIR, uniq
valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import { policy as updates_policy } from 'dawnline.updates';
export const CONFIG = 'dawnline';
/**
* Servers whose network interface Dawnline may not set up (the name belongs
* to an interface it did not create, or is invalid): { id: why }. Written by
* dawnline.netifd; such a server has no tunnel anywhere (firewall, access
* table, "like a home device"), so nothing of Dawnline lands on that interface.
*/
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
export const ACCESS = [ 'lan', 'internet', 'both' ];
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
export const MESH = [ 'off', 'all', 'circles' ];
/** Circle colours (index into the admin palette). */
export const CIRCLE_COLORS = 8;
/** AmneziaWG obfuscation options stored on a server (netifd uses `awg_<key>`; dawnline.awg renders them). */
export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5',
// AmneziaWG 3.x
'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
jc: 'Jc', jmin: 'Jmin', jmax: 'Jmax', s1: 'S1', s2: 'S2', s3: 'S3', s4: 'S4',
h1: 'H1', h2: 'H2', h3: 'H3', h4: 'H4', i1: 'I1', i2: 'I2', i3: 'I3', i4: 'I4', i5: 'I5',
header_protection_key: 'HeaderProtectionKey', content_padding_addition: 'ContentPaddingAddition',
rekey_after_time: 'RekeyAfterTime', rekey_timeout: 'RekeyTimeout', reject_after_time: 'RejectAfterTime',
keepalive_timeout: 'KeepaliveTimeout', max_handshake_attempts: 'MaxHandshakeAttempts',
random_trailers: 'RandomTrailers', disable_cookies: 'DisableCookies',
};
function toint(v, dflt) {
if (v == null || v == '')
return dflt;
@@ -74,8 +70,6 @@ export function load(c) {
settings: {
portal_enabled: bool(s.portal_enabled, false),
portal_port: toint(s.portal_port, 8443),
// Also answer on 443 from the internet (mobile networks often drop TLS on other ports).
portal_443: bool(s.portal_443, true),
portal_host: s.portal_host ?? '',
// More addresses for the same links (the main one is portal_host).
portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''),
@@ -95,6 +89,8 @@ export function load(c) {
watchdog: bool(s.watchdog, true),
// Second DNS for "home names" devices, used by the device when the tunnel is down.
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'),
// Settings → Updates (automatic checks and updates of the components).
updates: updates_policy(s),
// Raw retention values; dawnline.live policy() interprets them.
retention: {
log_keep_days: s.log_keep_days, log_max: s.log_max, log_category: s.log_category,
@@ -109,6 +105,7 @@ export function load(c) {
circles: {},
};
let blocked = read_json(BLOCKED, {});
c.foreach(CONFIG, 'server', (r) => {
let id = r['.name'];
let srv = {
@@ -137,15 +134,16 @@ export function load(c) {
// (Older configs: device_mesh 0/1.)
mesh: index(MESH, r.mesh) >= 0 ? r.mesh : (bool(r.device_mesh, true) ? 'all' : 'off'),
enabled: bool(r.enabled, true),
// Home devices found over Bonjour are published as DNS-SD records (needs umdns).
bonjour: bool(r.bonjour, false),
// AmneziaWG disguise values, read by dawnline.awg.
obf: {},
};
// A person's own devices reach each other whenever the mesh is not off.
srv.device_mesh = srv.mesh != 'off';
for (let k in OBF_KEYS)
if (r[k] != null && r[k] != '')
srv.obf[k] = `${r[k]}`;
// A person's own devices reach each other whenever the mesh is not off.
srv.device_mesh = srv.mesh != 'off';
if (blocked[id])
srv.blocked = blocked[id];
m.servers[id] = srv;
});
@@ -293,37 +291,43 @@ export function load_usage() {
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
};
/* ---------- keys ---------- */
/* ---------- tunnels and addresses ---------- */
export function genkey() {
return sh_out('awg genkey');
/** A server's interface name: also a netifd section and an nft string, so nothing else. */
export function valid_ifname(s) {
return type(s) == 'string' && match(s, /^[a-z][a-z0-9_]{0,11}$/) != null;
};
export function pubkey(priv) {
if (!valid_key(priv))
return null;
return sh_out(`printf %s ${q(priv)} | awg pubkey`);
};
export function genpsk() {
return sh_out('awg genpsk');
};
/* ---------- networks ---------- */
/** IPv4 subnets of the router's LAN zone (from netifd), as CIDR strings. */
/** Router address inside the server subnet (first host). */
/** Router address inside the AmneziaWG subnet (first host). */
export function server_address(srv) {
let c = parse_cidr(srv.subnet);
return c ? int2ip(c.first) : null;
};
/**
* The link a server's devices come in on: { ifname, subnet, address (the
* router's) }, as a list so the access table, firewall zone, "like a home
* device" and DNS treat every tunnel interface alike. None for a server
* without keys, subnet or a valid interface name (an imported config), or
* whose interface name is taken (BLOCKED).
*/
export function tunnels(srv) {
let c = srv?.private_key && !srv.blocked && valid_ifname(srv.ifname) ? parse_cidr(srv.subnet) : null;
return c ? [ { ifname: srv.ifname, subnet: srv.subnet, address: int2ip(c.first) } ] : [];
};
/** The server's tunnel link, or null. */
export function tunnel(srv) {
return tunnels(srv)[0];
};
/** The first free address in the server's subnet (the router has the first). */
export function alloc_address(m, srv) {
let c = parse_cidr(srv.subnet);
if (!c)
let t = parse_cidr(srv.subnet);
if (!t)
return null;
let used = {};
used[c.first] = true;
used[t.first] = true;
for (let id, d in m.devices) {
let p = m.people[d.person];
if (p && p.server == srv.id) {
@@ -332,124 +336,24 @@ export function alloc_address(m, srv) {
used[n] = true;
}
}
for (let n = c.first + 1; n <= c.last; n++)
for (let n = t.first + 1; n <= t.last; n++)
if (!used[n])
return int2ip(n);
return null;
};
/* ---------- obfuscation ---------- */
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
function rand_h(used) {
for (let i = 0; i < 50; i++) {
let v = rand_int(5, 2147483647);
if (!used[v]) {
used[v] = true;
return `${v}`;
}
}
}
/**
* What the installed AmneziaWG can do, from the netifd protocol script (the
* options it passes on) and the `awg` tool (the keys it accepts):
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
*/
export function awg_caps() {
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? '';
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
return { v2, v3 };
};
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
/**
* Generate obfuscation parameters for a method:
* off plain WireGuard-compatible packets
* standard junk packets and random headers (any AmneziaWG client)
* strong more and larger junk (any AmneziaWG client)
* max AmneziaWG 3.1: protected headers, random trailers, padding,
* jittered timers and a DNS-like first packet — the values
* AmneziaVPN itself uses for 3.1 servers
*/
export function obf_preset(name) {
if (name == 'max')
return {
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
s1: '12', s2: '12', s3: '12', s4: '12',
h1: '1', h2: '2', h3: '3', h4: '4',
i1: DNS_MIMIC,
header_protection_key: genkey(),
content_padding_addition: '10-100',
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
random_trailers: 'on', disable_cookies: 'on',
};
if (name == 'off')
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
let strong = name == 'strong';
let o = {};
o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`;
let jmin = rand_int(64, strong ? 128 : 96);
o.jmin = `${jmin}`;
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
while (s1 + 56 == s2)
s2 = rand_int(15, 64);
o.s1 = `${s1}`;
o.s2 = `${s2}`;
let used = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
o[k] = rand_h(used);
return o;
};
export function obf_errors(o) {
let errs = [];
for (let k, r in OBF_SPEC) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) {
if (!(v == '0' && (k == 'jmin' || k == 'jmax')))
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
}
}
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
push(errs, 'jmin > jmax');
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, 's1 + 56 = s2');
let hs = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, `${k} must be a number or range`);
else if (hs[v])
push(errs, 'h1-h4 must be distinct');
hs[v] = true;
}
return errs;
};
/* ---------- client configuration ---------- */
/* ---------- what clients get ---------- */
export function endpoint_host(m, srv) {
return srv.endpoint || m.settings.portal_host || '';
};
/**
* DNS for a server's clients: the router's tunnel address, which never
* changes after setup. The router forwards each query where it belongs (the
* LAN's DNS, from the LAN side; or the plain resolver), so configurations on
* devices keep working when the LAN, its DNS or the netns address change.
* DNS for a server's clients: the router's address in the tunnel subnet,
* which never changes after setup. The router forwards each query where it
* belongs (the LAN's DNS, from the LAN side; or the plain resolver), so
* configurations on devices keep working when the LAN, its DNS or the netns
* address change.
*/
export function dns_list(m, srv) {
if (!srv)
@@ -461,10 +365,10 @@ export function dns_list(m, srv) {
};
/**
* DNS written into a device's configuration. Home-only people keep their
* device's DNS unless they chose home names; then the first server is
* Dawnline's plain resolver (reached through the tunnel) and the second the
* fallback the device uses when the tunnel is down.
* DNS a device uses. Home-only people keep their device's DNS unless they
* chose home names; then the first server is Dawnline's plain resolver
* (reached through the tunnel) and the second the fallback the device uses
* when the tunnel is down.
*/
export function client_dns(m, srv, p) {
if (p?.access != 'lan')
@@ -502,132 +406,6 @@ export function person_circle(m, p) {
return c && c.server == p.server ? c : null;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
let nets = person_home(srv, p).nets;
// With devices reaching each other, the whole tunnel network (the router's
// address is in it); otherwise only the router's own address.
let a = server_address(srv);
if (srv.device_mesh && srv.subnet)
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
// The resolver address must be reachable through the tunnel too (not the fallback).
let dns = client_dns(m, srv, p)[0];
if (dns)
push(nets, `${dns}/32`);
return net.collapse(nets);
}
return [ '0.0.0.0/0', '::/0' ];
};
/** Everything a client needs; `conf` is the .conf text. */
/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */
export function obf_neutral(o) {
for (let k in OBF_KEYS) {
let v = o?.[k];
if (v == null || v == '')
continue;
let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0';
if (`${v}` != want)
return false;
}
return true;
};
export function client_config(m, dev) {
let p = m.people[dev.person];
let srv = p ? m.servers[p.server] : null;
if (!srv)
return null;
let host = endpoint_host(m, srv);
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let dns = client_dns(m, srv, p);
let lines = [ '[Interface]' ];
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
push(lines, `Address = ${dev.address}/32`);
if (length(dns))
push(lines, `DNS = ${join(', ', dns)}`);
push(lines, `MTU = ${srv.mtu}`);
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
// out, so any WireGuard app accepts the file.
if (!obf_neutral(srv.obf))
for (let k in OBF_KEYS)
if (srv.obf[k] != null && srv.obf[k] != '')
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
push(lines, '', '[Peer]');
push(lines, `PublicKey = ${srv.public_key}`);
if (dev.preshared_key)
push(lines, `PresharedKey = ${dev.preshared_key}`);
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
push(lines, `Endpoint = ${ep}:${srv.port}`);
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
return {
name: dev.name,
person: p.name,
server: srv.name,
filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`,
conf: join('\n', lines) + '\n',
has_private_key: dev.private_key != '',
amnezia: {
host,
port: srv.port,
mtu: `${srv.mtu}`,
dns,
allowed_ips: allowed,
client_ip: dev.address,
client_priv_key: dev.private_key,
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
obfuscation: srv.obf,
},
};
};
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
function fnv32(str) {
let h = 2166136261;
for (let i = 0; i < length(str); i++)
h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff;
return sprintf('%08x', h);
}
/** What a device holds, minus its private key: changes when it must import again. */
export function config_fingerprint(m, dev) {
let c = dev ? client_config(m, dev) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^PrivateKey/)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
export function issued() {
return read_json(ISSUED, {});
};
/** Remember that a device was just given its current configuration. */
export function mark_issued(m, id) {
let fp = config_fingerprint(m, m.devices[id]);
if (!fp)
return;
let l = lock('issued');
let all = issued();
if (all[id] != fp) {
all[id] = fp;
for (let k in keys(all))
if (!m.devices[k])
delete all[k];
ensure_dir(DATA_DIR, 0o700);
write_json(ISSUED, all, 0o600);
}
unlock(l);
};
/* ---------- mutations (caller commits) ---------- */
function fail(msg) {
@@ -675,7 +453,9 @@ export function create_person(c, m, a) {
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
if (!match(base, /^[a-z0-9_]{1,32}$/))
fail('The id may use lowercase letters, digits and underscores.');
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || id == 'settings';
// Any kind of section (store.id_taken, which imports this module).
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] ||
index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0;
let slug = base;
for (let n = 2; taken(slug); n++) {
if (n > 99)
@@ -736,8 +516,9 @@ export function update_person(c, m, id, a) {
let n = toint(a.device_limit, 0);
if (n < 1 || n > 32)
fail('Device limit must be between 1 and 32.');
if (n < length(p.devices))
fail(`${p.name} already has ${length(p.devices)} devices. Remove one first to lower the limit to ${n}.`);
let have = length(p.devices);
if (n < have)
fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`);
set('device_limit', n);
}
if (a.expires != null) {
@@ -810,9 +591,9 @@ export function update_person(c, m, id, a) {
};
/**
* Add a device for a person. `opts.by` is 'admin' or 'portal'; the portal
* enforces the device limit. `opts.public_key` keeps the private key on the
* client (browser-generated keys).
* Add a device for a person. `opts.keys` = { private_key?, public_key,
* preshared_key } from dawnline.awg (or a public key the browser generated).
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
*/
export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {};
@@ -835,39 +616,29 @@ export function create_device(c, m, person_id, name, kind, opts) {
let addr = alloc_address(m, srv);
if (!addr)
fail('No free addresses left in the server subnet.');
let priv = '', pub;
if (opts.public_key) {
if (!valid_key(opts.public_key))
fail('Invalid public key.');
pub = opts.public_key;
}
else {
priv = genkey();
pub = pubkey(priv);
}
if (!pub)
let k = opts.keys ?? {};
if (!valid_key(k.public_key))
fail('Key generation failed (is amneziawg-tools installed?).');
for (let id, d in m.devices)
if (d.public_key == pub)
for (let o, d in m.devices)
if (d.public_key == k.public_key)
fail('This key is already in use.');
let id = `d_${rand_hex(4)}`;
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
c.set(CONFIG, id, 'device');
c.set(CONFIG, id, 'person', person_id);
c.set(CONFIG, id, 'name', name);
c.set(CONFIG, id, 'kind', kind);
c.set(CONFIG, id, 'address', addr);
c.set(CONFIG, id, 'public_key', pub);
if (priv)
c.set(CONFIG, id, 'private_key', priv);
c.set(CONFIG, id, 'preshared_key', genpsk());
c.set(CONFIG, id, 'created', `${time()}`);
c.set(CONFIG, id, 'created_by', opts.by ?? 'admin');
for (let f in [ 'public_key', 'private_key', 'preshared_key' ])
if (dev[f])
c.set(CONFIG, id, f, dev[f]);
c.set(CONFIG, id, 'created', `${dev.created}`);
c.set(CONFIG, id, 'created_by', dev.created_by);
// Keep the in-memory model consistent for callers that continue.
m.devices[id] = { id, person: person_id, name, kind, address: addr, public_key: pub, private_key: priv,
preshared_key: c.get(CONFIG, id, 'preshared_key'), created: time(), created_by: opts.by ?? 'admin', disabled: false };
m.devices[id] = dev;
push(p.devices, id);
return id;
};
@@ -897,16 +668,17 @@ export function delete_device(c, m, id) {
delete m.devices[id];
};
export function rotate_device(c, m, id) {
/** New keys from dawnline.awg (the caller makes them: the model does not run tools). */
export function rotate_device(c, m, id, keys) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
let priv = genkey(), pub = pubkey(priv);
if (!pub)
if (!valid_key(keys?.public_key) || !keys?.private_key)
fail('Key generation failed.');
c.set(CONFIG, id, 'private_key', priv);
c.set(CONFIG, id, 'public_key', pub);
c.set(CONFIG, id, 'preshared_key', genpsk());
c.set(CONFIG, id, 'private_key', keys.private_key);
c.set(CONFIG, id, 'public_key', keys.public_key);
if (keys.preshared_key)
c.set(CONFIG, id, 'preshared_key', keys.preshared_key);
};
export function delete_person(c, m, id) {
@@ -921,7 +693,7 @@ export function delete_person(c, m, id) {
/** Validate a server definition (as loaded) against the rest of the router. */
export function server_errors(m, srv, others_subnets) {
let errs = [];
if (!match(srv.ifname, /^[a-z][a-z0-9_]{0,11}$/))
if (!valid_ifname(srv.ifname))
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
if (srv.port < 1 || srv.port > 65535)
push(errs, 'Port must be 1-65535.');
@@ -936,7 +708,6 @@ export function server_errors(m, srv, others_subnets) {
}
if (srv.endpoint != '' && !valid_host(srv.endpoint))
push(errs, 'Endpoint must be a hostname or IP address.');
push(errs, ...obf_errors(srv.obf));
return errs;
};
@@ -949,18 +720,14 @@ export function wan_port_taken(port) {
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT')
return;
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
let m = match(p, /^(\d+)(?:[-:](\d+))?$/);
if (m && +m[1] <= port && port <= +(m[2] ?? m[1]))
let m = match(p, /^(\d+)([-:](\d+))?$/);
if (m && +m[1] <= port && port <= +(m[3] || m[1]))
taken = true;
}
});
return taken;
};
export function wan443_taken() {
return wan_port_taken(443);
};
/** Every address the links use, the main one first. */
export function portal_hosts(m) {
let out = [];
@@ -980,17 +747,14 @@ export function portal_http_port(m) {
return m.settings.portal_port + 1;
};
/** The port in plain-HTTP links: 80 when standard ports are on and free. */
/** The port in plain-HTTP links (the portal never takes 80 or 443 for itself). */
export function portal_http_public(m) {
return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m);
return portal_http_port(m);
};
/** The port in personal links: 443 when the portal also answers there. */
/** The port in personal links: the portal's own. */
export function portal_public_port(m) {
let s = m.settings;
if (s.portal_port == 443 || !s.portal_443 || wan443_taken())
return s.portal_port;
return 443;
return m.settings.portal_port;
};
/** The link on one address: https for names, plain http for IP addresses. */
@@ -0,0 +1,115 @@
// Dawnline — adding, changing, rotating and removing a person's devices: one
// code path for the admin UI (rpcd) and the portal, with the config lock,
// the runtime sync, the activity log and the "configuration issued" mark.
//
// opts = { by: 'admin' | 'portal', person?: the only person whose devices may
// be touched (the portal), defer?: load new keys a moment later (the portal
// page came through the device being rotated) }. The portal is held to the
// device limit (dawnline.core) and cannot touch a device the admin turned off.
import { sh_bg } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as apply from 'dawnline.apply';
import * as live from 'dawnline.live';
import * as store from 'dawnline.store';
/** AmneziaWG is on the router, so device keys can be made and loaded. */
export function ready() {
return awg.installed();
};
/** Dies with the admin's wording when AmneziaWG is missing. */
export function need_awg() {
if (!awg.installed()) {
let miss = awg.state().missing ?? [];
die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`);
}
};
/** The device `id` as `opts` may touch it (inside a transaction's model). */
function own(m, id, opts) {
let d = m.devices[id];
if (!d || (opts.person != null && d.person != opts.person))
die(opts.person != null ? 'Device not found.' : 'Unknown device.');
if (opts.by == 'portal' && d.disabled)
die('The admin has turned this device off.');
return d;
}
/** New device with fresh keys (or the browser's public key): { id, config }. */
export function add(person, name, kind, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
apply.sync();
let m = core.load();
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
awg.mark_issued(m, id);
return { id, config: awg.client_config(m, m.devices[id]) };
};
/**
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
* the admin turns devices off. Returns the runtime sync.
*/
export function update(id, ch, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
if (ch.disabled != null && by != 'admin')
die('Only the admin can turn devices off.');
let d0 = store.transact((c, m) => {
let d = own(m, id, opts);
let was = { ...d };
if (ch.name != null && ch.name != d.name)
core.rename_device(c, m, id, ch.name);
if (ch.disabled != null) {
if (ch.disabled)
c.set(core.CONFIG, id, 'disabled', '1');
else
c.delete(core.CONFIG, id, 'disabled');
}
return was;
});
let r = apply.sync();
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
else if (ch.name != null && ch.name != d0.name)
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
return r;
};
/** New keys for a device: returns its new configuration. */
export function rotate(id, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
store.transact((c, m) => {
own(m, id, opts);
core.rotate_device(c, m, id, awg.new_keys());
});
// The device a portal page came through would lose its tunnel before the
// answer gets out: load the new key a moment after answering.
if (opts.defer)
sh_bg('sleep 3; /usr/bin/dawnline sync');
else
apply.sync();
let m = core.load();
let d = m.devices[id];
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
awg.mark_issued(m, id);
return awg.client_config(m, d);
};
/** Remove a device. Returns the runtime sync. */
export function remove(id, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
let d = store.transact((c, m) => {
let d = own(m, id, opts);
core.delete_device(c, m, id);
return d;
});
let r = apply.sync();
live.add_event({ type: 'device_removed', person: d.person, device: id, detail: d.name, dname: d.name, dkind: d.kind, by });
return r;
};
@@ -0,0 +1,261 @@
// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings
// to home and WAN, the WAN rules for the tunnels and the portal (named
// sections dawnline_*), what the watchdog checks about them, and the nft
// table that keeps Dawnline's own answers out of proxies. Only sections
// 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 { cursor } from 'uci';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as nft from 'dawnline.nft';
const LOOP_ZONE = 'dl_loop';
/*
* Our own answers leave by the main table: the portal's (TCP) and each
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule to a
* `local default` table) mark the router's own traffic to internet addresses
* in an output route chain, which diverts replies to outside clients into lo.
* A policy rule on the source port can't exempt them: the reroute after the
* mark is set looks up without ports. So a later output route chain of our
* own clears exactly those proxy marks on packets from our listening ports,
* and the kernel routes them again by main. Forwarded traffic is not touched.
*/
const REPLY_TABLE = 'dawnline_reply';
const REPLY_SIG = `${RUN_DIR}/reply.nft`;
/** Older versions kept answers out of proxies with `ip rule` at this priority; it never matched. */
const PREF_REPLY = 90;
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
export function sync(m, dry) {
let c = cursor();
c.load('firewall');
let changed = false, want = {};
let sec = (name, stype, opts) => {
want[name] = true;
changed = uci_section(c, 'firewall', name, stype) || changed;
for (let k, v in opts)
changed = uci_put(c, 'firewall', name, k, v) || changed;
};
let snap = net.snapshot(true);
let portal_zone = null, want_loop = false;
for (let id, srv in m.servers) {
if (!length(core.tunnels(srv)))
continue;
let z = `dawnline_${id}`;
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
sec(`${z}_zone`, 'zone', {
// Forward within the zone (device to device) is decided by the inet dawnline table.
name: srv.ifname, network: [ srv.ifname ],
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
});
// Access per person is enforced by the inet dawnline table; the zone
// only needs to be allowed to reach each home-network zone and WAN.
// The home network may open connections to the devices too (a router
// or a NAS on the tunnel); their answers pass the table as established.
for (let i, zone in sn.zones)
if (zone != sn.wan.zone && zone != srv.ifname) {
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
}
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
if (srv.lan_like) {
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
want_loop = true;
}
sec(`${z}_port`, 'rule', {
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
});
}
// The link into the netns that re-enters the router from the LAN.
if (want_loop) {
sec('dawnline_loop', 'zone', {
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
});
// The Home-only resolver in the netns reaches its upstream DNS this way.
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
}
// Never open SSH, DNS or the LuCI web server for the portal, whatever the settings say.
let portal_port_ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
if (m.settings.portal_enabled && portal_port_ok(m.settings.portal_port)) {
let wan = portal_zone ?? 'wan';
sec('dawnline_portal', 'rule', {
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
dest_port: m.settings.portal_port, target: 'ACCEPT',
});
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
if (core.portal_http(m) && portal_port_ok(core.portal_http_port(m))) {
sec('dawnline_portal_http', 'rule', {
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
dest_port: core.portal_http_port(m), target: 'ACCEPT',
});
}
// The portal keeps its own port: 80 and 443 stay with the LuCI web server.
}
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
c.delete('firewall', s);
changed = true;
}
if (dry)
return changed;
if (changed) {
c.commit('firewall');
ack_config([ 'firewall' ]);
system('fw4 -q reload');
system("logger -t dawnline 'firewall updated'");
}
return changed;
};
/**
* For the watchdog: what is wrong with Dawnline's firewall, or null.
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
*/
export function drift(m) {
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
if (t == '')
return 'off';
if (sync(m, true))
return 'changed';
// Named rules show up in fw4's ruleset as comments.
let names = [];
for (let id, srv in m.servers)
if (srv.enabled && length(core.tunnels(srv)))
push(names, `Dawnline-${srv.ifname}`);
if (m.settings.portal_enabled)
push(names, 'Dawnline-Portal');
for (let n in names)
if (index(t, `${n}"`) < 0)
return 'not loaded';
return null;
};
const MARK_ALL = 0xffffffff;
function hx(n) {
return sprintf('0x%x', n);
}
/**
* Policy rules that send marked traffic into a table with `local default`,
* the way transparent proxies capture the router's own traffic:
* [{ pref, mark, mask, table }], one per mark and mask.
*/
export function proxy_diverts() {
let out = [], seen = {};
for (let fam in [ '-4', '-6' ])
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff".
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
if (!mm || +mm[1] >= 32766)
continue;
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
let key = `${d.mark}/${d.mask}`;
if (seen[key] || !match(sh_out(`ip ${fam} route show table ${d.table} 2>/dev/null`) ?? '', /(^|\n)local default/))
continue;
seen[key] = true;
push(out, d);
}
return out;
};
/** A divert as `ip rule` shows it, for people: "pref 1000 fwmark 0x1 → table 100". */
export function divert_str(d) {
return `pref ${d.pref} fwmark ${hx(d.mark)}${d.mask == MARK_ALL ? '' : `/${hx(d.mask)}`} → table ${d.table}`;
};
/** Ports Dawnline answers on from the outside: { tcp: [...], udp: [...] }. */
function reply_ports(m) {
let p = { tcp: [], udp: [] };
let ok = (n) => n >= 1 && n <= 65535;
if (m.settings.portal_enabled) {
push(p.tcp, +m.settings.portal_port);
if (core.portal_http(m))
push(p.tcp, +core.portal_http_port(m));
}
for (let id, srv in m.servers)
if (srv.private_key && srv.enabled)
push(p.udp, +srv.port);
return { tcp: uniq(filter(p.tcp, ok)), udp: uniq(filter(p.udp, ok)) };
}
/** The reply table for these diverts, or '' when there is nothing to keep out of them. */
function reply_script(m, diverts) {
let p = reply_ports(m);
if (!length(diverts) || !length(p.tcp) && !length(p.udp))
return '';
let t = [];
push(t, `table inet ${REPLY_TABLE} {`);
push(t, ' chain out {');
// After the proxies' own output chains (they mark at mangle, -150).
push(t, ' type route hook output priority filter + 10; policy accept;');
for (let proto in [ 'tcp', 'udp' ]) {
if (!length(p[proto]))
continue;
for (let d in diverts)
// Only the divert's bits: other marks on the packet (multi-WAN) stay.
push(t, ` ${proto} sport { ${join(', ', p[proto])} } ` + (d.mask == MARK_ALL
? `meta mark ${hx(d.mark)} meta mark set 0x0`
: `meta mark & ${hx(d.mask)} == ${hx(d.mark)} meta mark set meta mark & ${hx(~d.mask & MARK_ALL)}`));
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
function reply_loaded() {
return system(`nft list table inet ${REPLY_TABLE} >/dev/null 2>&1`) == 0;
}
/** Are the answers from our ports kept out of these diverts right now (watchdog)? */
export function reply_ok(m, diverts) {
let s = reply_script(m, diverts);
return s == '' || (s == readfile(REPLY_SIG) && reply_loaded());
};
/**
* Keep the reply table in step with our ports and the proxies' diverts (apply
* and every agent tick: a proxy may start after Dawnline). Cheap when nothing changed.
*/
export function sync_reply_routes(m) {
// Rules of older versions ("90: from all iif lo ipproto udp sport 51820 lookup main", once without "iif lo").
for (let fam in [ '-4', '-6' ])
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
let mm = match(line, /(iif lo )?ipproto (tcp|udp) sport ([0-9]+) lookup main/);
if (mm)
sh(`ip ${fam} rule del priority ${PREF_REPLY}${mm[1] ? ' iif lo' : ''} ipproto ${mm[2]} sport ${mm[3]} lookup main 2>/dev/null`);
}
let s = reply_script(m, proxy_diverts());
if (s == '') {
if (reply_loaded())
system(`nft delete table inet ${REPLY_TABLE} 2>/dev/null`);
unlink(REPLY_SIG);
return;
}
if (s == readfile(REPLY_SIG) && reply_loaded())
return;
let err = nft.load(`table inet ${REPLY_TABLE}\ndelete table inet ${REPLY_TABLE}\n${s}`);
if (err) {
unlink(REPLY_SIG);
system(`logger -t dawnline -p user.err ${q('reply table: ' + err)}`);
return;
}
write_file(REPLY_SIG, s, 0o644);
};
@@ -0,0 +1,226 @@
// Dawnline — GitHub for the updater and the Components tab: API calls with a
// short cache, releases (with each asset's sha256), the changes between two
// tags, and verified downloads.
//
// Trust: the API is only ever asked directly (TLS to api.github.com). Files
// may come through a mirror when GitHub is unreachable, but only when their
// sha256 is known from the API, and a file is kept only if it matches.
import { stat, popen, access } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
/** Prefixes that fetch github.com files when GitHub itself is unreachable. */
export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ];
function run(cmd) {
let p = popen(cmd + ' 2>&1', 'r');
if (!p)
return { code: 127, out: '' };
let out = p.read('all') ?? '';
return { code: p.close(), out };
}
function have_curl() {
return access('/usr/bin/curl', 'x');
}
/**
* GET a URL: { status, body } (status 0 when there was no answer). curl gives
* the HTTP status, so a 403 rate limit is told apart from a dead network.
*/
function get(url, timeout) {
timeout ??= 12;
if (have_curl()) {
let r = run(`curl -sSL --connect-timeout 6 --max-time ${+timeout} -H 'Accept: application/vnd.github+json' -A Dawnline -w '\\n%{http_code}' ${q(url)}`);
// The body, then the status on the last line (-w).
let i = rindex(r.out, '\n');
let code = i < 0 ? '' : substr(r.out, i + 1);
return match(code, /^[0-9][0-9][0-9]$/) ? { status: +code, body: substr(r.out, 0, i) } : { status: 0, body: '' };
}
let r = run(`uclient-fetch -q -T ${+timeout} -O - ${q(url)}`);
return { status: r.code == 0 ? 200 : 0, body: r.code == 0 ? r.out : '' };
}
/** JSON from the GitHub API, or null when GitHub did not answer; dies on a rate limit or another API error. */
function api_json(url) {
let r = get(url);
if (r.status == 0)
return null;
let j = null;
try {
j = json(r.body);
}
catch (e) {
return null;
}
if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i)))
die('GitHub API rate limit reached: try again in an hour.');
if (r.status == 404)
return null;
if (r.status >= 400)
die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`);
return j;
}
function cached(key, ttl, fn) {
let path = `${RUN_DIR}/gh-${replace(key, /[^A-Za-z0-9_.-]/g, '_')}.json`;
let c = read_json(path, null);
if (c && time() - (c.at ?? 0) < ttl)
return c.data;
let data = fn();
if (data != null) {
ensure_dir(RUN_DIR);
write_json(path, { at: time(), data });
}
return data ?? c?.data;
}
/* ---------- releases ---------- */
function slim(x) {
let digests = {};
for (let a in x.assets ?? [])
if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/))
digests[a.name] = substr(a.digest, 7);
return {
tag: x.tag_name, name: x.name ?? x.tag_name, published: x.published_at ?? null,
prerelease: !!x.prerelease, url: x.html_url ?? null, body: substr(x.body ?? '', 0, 12000),
assets: map(x.assets ?? [], (a) => a.name), digests,
};
}
/** Releases of a repository, newest first, five per page (drafts skipped). */
export function releases(rp, page) {
page = page ?? 1;
return cached(`rel-${rp}-${page}`, 600, () => {
let j = api_json(`https://api.github.com/repos/${rp}/releases?per_page=5&page=${+page}`);
return type(j) == 'array' ? map(filter(j, (x) => !x.draft), slim) : null;
}) ?? [];
};
/** One release by tag (notes, assets and their sha256), or null. */
export function release(rp, tag) {
return cached(`tag-${rp}-${tag}`, 600, () => {
let j = api_json(`https://api.github.com/repos/${rp}/releases/tags/${tag}`);
return type(j) == 'object' && j.tag_name ? slim(j) : null;
});
};
/** The sha256 GitHub publishes for a release file, or null (unknown: no mirrors for it). */
export function asset_sha256(rp, tag, name) {
try {
return release(rp, tag)?.digests?.[name] ?? null;
}
catch (e) {
return null;
}
};
/** The latest stable release; the /releases/latest redirect when the API is out of reach. */
export function latest(rp) {
let r = null;
try {
r = cached(`latest-${rp}`, 300, () => {
let j = api_json(`https://api.github.com/repos/${rp}/releases/latest`);
return type(j) == 'object' && j.tag_name ? slim(j) : null;
});
}
catch (e) {}
if (r)
return r;
if (have_curl()) {
let o = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`);
let m = match(trim(o.out), /\/releases\/tag\/([^\/?#]+)$/);
if (m)
return { tag: m[1], name: m[1], published: null, prerelease: false, url: `https://github.com/${rp}/releases/tag/${m[1]}`, body: '', assets: [], digests: {} };
}
return null;
};
/* ---------- what changed ---------- */
/**
* What changed in a commit message, as points: release commits ("Dawnline
* 0.3.1") list their changes as "- " lines in the body; other commits are
* their title. Wrapped points are joined back into one line.
*/
export function points(msg) {
let lines = split(msg ?? '', '\n');
let title = trim(lines[0] ?? '');
if (match(title, /^Merge /))
return [];
let out = [], cur = null;
for (let i = 1; i < length(lines); i++) {
let m = match(lines[i], /^\s*[-*]\s+(.*)$/);
if (m) {
if (cur != null)
push(out, cur);
cur = trim(m[1]);
}
else if (cur != null && match(lines[i], /^\s+\S/))
cur += ' ' + trim(lines[i]);
else if (cur != null) {
push(out, cur);
cur = null;
}
}
if (cur != null)
push(out, cur);
if (!length(out) && !match(title, /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) && title != '')
push(out, title);
return out;
};
/** The changes from one tag to another, newest first: commit by commit, or the release's own commit. */
export function changes(rp, base, head) {
return cached(`changes-${rp}-${base}-${head}`, 600, () => {
let out = [];
let j = base ? api_json(`https://api.github.com/repos/${rp}/compare/${base}...${head}`) : null;
if (type(j?.commits) == 'array') {
for (let i = length(j.commits) - 1; i >= 0; i--)
for (let p in points(j.commits[i]?.commit?.message))
push(out, p);
return slice(out, 0, 20);
}
let c = api_json(`https://api.github.com/repos/${rp}/commits/${head}`);
return c?.commit ? slice(points(c.commit.message), 0, 20) : null;
}) ?? [];
};
/* ---------- downloads ---------- */
export function sha256(path) {
return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1];
};
/**
* Download to a file. o: { sha256, mirrors, log }. Direct first; mirrors
* only when the sha256 is known (from the API) and mirrors are allowed. A
* file that does not match the sha256 is thrown away and the next source is
* tried. Returns the URL that worked, or null.
*/
export function download(url, dest, o) {
o ??= {};
let want = o.sha256 ? lc(o.sha256) : null;
let tries = [ url ];
if (want && o.mirrors && match(url, /^https:\/\/(github\.com|raw\.githubusercontent\.com)\//))
for (let m in MIRRORS)
push(tries, m + url);
for (let i, u in tries) {
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (i > 0)
o.log?.(`Trying mirror ${host}`);
let r = have_curl()
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
if (!want || sha256(dest) == want)
return u;
o.log?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`);
}
system(`rm -f ${q(dest)}`);
if (i == 0 && length(tries) > 1)
o.log?.('GitHub did not answer, trying mirrors');
}
return null;
};
@@ -0,0 +1,421 @@
// Dawnline — Health: what the router has and lacks (packages, listeners,
// networks), the checks shown on Diagnostics → Health, and their fixes.
import { readfile, stat, lsdir } from 'fs';
import { cursor } from 'uci';
import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as fw from 'dawnline.fw';
import * as loop from 'dawnline.loop';
import * as net from 'dawnline.net';
import * as awg from 'dawnline.awg';
import * as lookup from 'dawnline.lookup';
import * as pc from 'dawnline.portalcert';
/* ---------- what the router has ---------- */
/**
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link), awg
* (AmneziaWG: the tools with netifd's protocol script, and the kernel module). Checked by
* files, so it is cheap enough for every page load.
*/
export function needs() {
let tls = false;
for (let d in [ '/lib', '/usr/lib' ])
for (let f in lsdir(d) ?? [])
if (substr(f, 0, 16) == 'libustream-ssl.s')
tls = true;
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let kmod = (name) => stat(`/sys/module/${name}`) != null || file_exists(`/lib/modules/${kver}/${name}.ko`);
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
return {
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ kmod('veth'), 'kmod-veth' ] ]),
// amneziawg-tools ships both the awg tool and netifd's protocol script.
awg: miss([ [ file_exists('/usr/bin/awg') && file_exists('/lib/netifd/proto/amneziawg.sh'), 'amneziawg-tools' ],
[ kmod('amneziawg'), 'kmod-amneziawg' ] ]),
};
};
export function udp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
if (index(readfile(f) ?? '', hex) >= 0)
return true;
return false;
};
export function tcp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
for (let line in split(readfile(f) ?? '', '\n'))
// state 0A = LISTEN
if (index(line, hex) > 0 && match(line, / 0A /))
return true;
return false;
};
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
export function tcp_port_owners(port) {
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
let owners = [];
for (let o in split(out, '\n')) {
let name = split(o, '/')[1];
if (!name || index(owners, name) >= 0)
continue;
// Our own portal runs as a dedicated uhttpd instance.
let pid = +split(o, '/')[0];
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
continue;
push(owners, name);
}
return owners;
};
export function service_running(name, instance) {
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
if (!s)
return false;
try {
return !!json(s)?.[name]?.instances?.[instance]?.running;
}
catch (e) {
return false;
}
};
/** IPv4 networks of netifd interfaces: [{ iface, cidr }], without the given server's tunnel. */
function other_subnets(srv_id) {
let out = [];
let st = sh_out('ubus call network.interface dump 2>/dev/null');
let d = null;
try {
d = st ? json(st) : null;
}
catch (e) {
d = null;
}
let ours = {};
for (let id, s in core.load().servers)
ours[s.ifname] = id;
for (let i in d?.interface ?? []) {
if (srv_id != null && ours[i.interface] == srv_id)
continue;
if (srv_id === false && ours[i.interface] != null)
continue;
for (let a in i['ipv4-address'] ?? [])
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
}
return out;
};
/** Subnets in use on the router except the given server's (null: all of them). */
export function used_subnets(except_srv) {
return map(other_subnets(except_srv), (x) => x.cidr);
};
/** Subnets of interfaces that are not Dawnline tunnels (an imported config is checked against these). */
export function foreign_subnets() {
return used_subnets(false);
};
/* ---------- checks ---------- */
/*
* Checks are named for the healthy state ("Clock is set"); a failed one also
* gets the problem in words for notices ("Clock isn't set"). Longest names
* first; a server's name after the check name is kept.
*/
const PROBLEM = [
[ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ],
[ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ],
[ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ],
[ 'AmneziaWG port is free', 'AmneziaWG port is taken' ],
[ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ],
[ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ],
[ 'AmneziaWG running', 'AmneziaWG is down' ],
[ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ],
[ 'Portal address points here', 'Portal address doesn’t point here' ],
[ 'Portal address', 'Portal address isn’t set' ],
[ 'Portal certificate', 'Portal certificate needs attention' ],
[ 'Personal portal', 'Personal portal isn’t working' ],
[ 'Plain HTTP links', 'Portal links use plain HTTP' ],
[ 'Internet like a home device', 'Internet like a home device isn’t working' ],
[ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ],
[ 'Background agent running', 'Background agent isn’t running' ],
[ 'Access rules loaded', 'Access rules aren’t loaded' ],
[ 'Server configured', 'No server yet' ],
[ 'Public address', 'Public address needs attention' ],
[ 'Clock is set', 'Clock isn’t set' ],
];
function problem_of(title) {
for (let p in PROBLEM)
if (substr(title, 0, length(p[0])) == p[0])
return p[1] + substr(title, length(p[0]));
return title;
}
/** problem: the failed check in words, when the table's wording does not fit the case. */
function check(id, title, status, detail, fix, problem) {
let bad = status == 'warn' || status == 'error';
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null };
}
/**
* Answers from our ports and the proxies that would swallow them (fw.sync_reply_routes):
* { ok, diverts: ["pref 1000 fwmark 0x1 → table 100"] }.
*/
function replies(m) {
let d = fw.proxy_diverts();
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
}
function reply_check(id, title, proto, port, r) {
let via = join(', ', r.diverts);
return check(id, title, r.ok ? 'ok' : 'error',
!r.ok ? `Answers from ${uc(proto)} ${port} are swallowed by a proxy on the router (${via}): clients get no reply.`
: length(r.diverts) ? `Answers from ${uc(proto)} ${port} go straight out. A proxy on the router diverts its own traffic (${via}); these answers skip it.`
: `Answers from ${uc(proto)} ${port} go straight out.`,
r.ok ? null : 'apply');
}
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
function endpoint_check(id, title, srv, host, proto_note) {
if (!host)
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
let ips = lookup.resolve(host);
let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
let wc = wan ? ip2int(wan) : null;
let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0;
if (!length(ips))
return check(id, title, 'error', `${host} does not resolve.`);
if (cgnat)
return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`);
if (length(filter(ips, (a) => cloudflare_ip(a))))
return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`);
if (wan && index(ips, wan) < 0)
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`);
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`);
}
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.state();
let title = 'AmneziaWG installed';
if (length(st.missing ?? []))
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
if (!st.loaded) {
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
return check('awg', title, 'error',
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
'AmneziaWG’s kernel module doesn’t load');
}
if (!st.handler)
return check('awg', title, 'error', NO_PROTO, 'netrestart', 'The network doesn’t know AmneziaWG yet');
return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.');
}
/** Checks of a server's AmneziaWG tunnel. */
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let out = [];
let st = live.iface_status(srv.ifname);
let up = !!st?.up;
let codes = map(st?.errors ?? [], (e) => e.code);
if (!up && index(codes, 'INVALID_PROTO') >= 0)
push(out, check(`up_${id}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart'));
else
push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
if (up) {
let expected = 0;
let states = apply.states_for(m, core.load_usage());
for (let did, d in m.devices) {
let p = m.people[d.person];
if (p?.server == id && !d.disabled && states[d.person] == 'active')
expected++;
}
let actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname)
actual++;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn',
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error',
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
rule && zone ? null : 'apply'));
push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, rep));
// Port collisions with other tunnels.
let clash = [];
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
push(clash, s['.name']);
});
if (length(clash))
push(out, check(`port_${id}`, `AmneziaWG port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
let overlaps = [];
let sc = parse_cidr(srv.subnet);
for (let o in other_subnets(id)) {
let oc = parse_cidr(o.cidr);
if (sc && oc && cidr_overlaps(sc, oc))
push(overlaps, `${o.iface} (${o.cidr})`);
}
push(out, check(`subnet_${id}`, `AmneziaWG subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
return out;
}
/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */
function portal_checks(m, need, rep) {
let out = [];
let s = m.settings;
if (length(need.https))
return [ check('portal', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https') ];
let owners = tcp_port_owners(s.portal_port);
let listening = tcp_listening(s.portal_port);
if (length(owners))
push(out, check('portal', 'Personal portal', 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
else
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
if (!s.portal_host)
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
else {
let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m);
let cf = filter(ips, (x) => cloudflare_ip(x));
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
!length(ips) ? `${s.portal_host} does not resolve.` :
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
}
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, rep));
if (core.portal_http(m)) {
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
push(out, check('portal_http', 'Plain HTTP links', 'warn',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
}
if (ip2int(s.portal_host) != null) {
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
return out;
}
let cert = pc.portal_cert(s);
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
let sans = cert.self_signed ? [] : pc.cert_names(cert.cert);
let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0;
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
return out;
}
/**
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
* `fix` names an action accepted by fix(), or one the UI handles itself
* (install:<feature>, updates).
*/
export function health(m) {
m ??= core.load();
let rep = replies(m);
let out = [];
let dmp = live.dump(m);
let need = needs();
if (length(m.servers))
push(out, awg_check());
let y = localtime().year;
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
let agent = service_running('dawnline', 'agent');
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart'));
if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
return out;
}
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
nft_ok ? null : 'apply'));
let fwc = cursor();
fwc.load('firewall');
for (let id, srv in m.servers) {
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
if (!srv.enabled) {
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
continue;
}
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep));
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
if (srv.lan_like) {
let ls = loop.status();
let nh = need.home;
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
ls.active ? `The link is up but not attached to ${ls.dev}.` :
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
}
}
if (length(filter(values(m.servers), (x) => x.private_key))) {
let rt = loop.resolver_target();
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
}
if (m.settings.portal_enabled)
push(out, ...portal_checks(m, need, rep));
return out;
};
/** Run a fix named by a check. */
export function fix(id) {
if (id == 'apply')
return apply.apply();
if (id == 'sync')
return apply.sync();
if (id == 'restart')
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
// netifd learns protocol handlers (amneziawg) only when it starts. In the
// background: the answer goes out before the network blinks.
if (id == 'netrestart') {
system('( sleep 1; /etc/init.d/network restart ) >/dev/null 2>&1 </dev/null &');
return { ok: true, background: true };
}
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
if (m) {
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
};
@@ -1,4 +1,4 @@
// Dawnline — live data: peer status from `awg show all dump`, traffic
// Dawnline — live data: peer status from the tunnels (dawnline.awg), traffic
// accounting and the connection/event log.
//
// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once
@@ -7,11 +7,15 @@
import { readfile, stat, unlink } from 'fs';
import { cursor } from 'uci';
import {
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, uniq,
RUN_DIR, DATA_DIR
ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq,
iface_status as util_iface_status, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as awg from 'dawnline.awg';
export const ONLINE_WINDOW = 300;
// 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;
@@ -79,39 +83,48 @@ function trim_events(ev, pol) {
return ev;
}
/* ---------- awg dump ---------- */
/* ---------- live peers ---------- */
/* ---------- presence (the agent's watcher) ---------- */
/**
* Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
* lines always have 9.
* Written by the agent's watcher on every change: { online: { device id: bool },
* endpoint: { device id: ip }, rev, people: { person id: rev } }. `rev` moves on
* any connect, disconnect, roam or logged change; `people` per person (the portal).
*/
export function dump() {
let r = sh('awg show all dump');
let out = { ifaces: {}, peers: {} };
if (r.code != 0)
return out;
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) == 9) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
endpoint: ep,
handshake: +f[5],
rx: +f[6],
tx: +f[7],
};
}
else if (length(f) >= 5) {
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
}
}
return out;
export const PRESENCE = `${RUN_DIR}/presence.json`;
// The agent's heartbeat (dawnline.watchdog.BEAT): its presence counts while it runs.
const BEAT = `${RUN_DIR}/agent.beat`;
const BEAT_STALE = 180;
/** What the watcher sees, or null when the agent isn't running. */
export function presence() {
let beat = +(read_json(BEAT, 0) ?? 0);
if (!beat || time() - beat > BEAT_STALE)
return null;
return read_json(PRESENCE, null);
};
/**
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
* handshake, rx, tx } }, presence }. See dawnline.awg.
*/
export function dump(m) {
let d = awg.dump();
d.presence = presence();
return d;
};
/** A device is online: as the agent's watcher says, or (without the agent) by a recent handshake. */
export function online(dmp, id, peer) {
let p = dmp?.presence?.online;
if (p)
return !!(peer && p[id]);
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
};
export function endpoint_ip(ep) {
let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/);
let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
return m ? m[1] : ep;
};
@@ -122,7 +135,10 @@ function empty_usage() {
}
export function load_usage() {
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
let u = read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
// Per-app counters of earlier test builds are not kept.
delete u.clients;
return u;
};
function add(bucket, key, rx, tx) {
@@ -182,30 +198,41 @@ export function reset_usage(usage, m, scope, id) {
for (let did in m.people[id]?.devices ?? [])
wipe(usage.devices[did]);
}
else if (scope == 'device') {
else if (scope == 'device')
wipe(usage.devices[id]);
}
};
function offline(rec) {
return { online: false, handshake: rec?.handshake ?? 0, endpoint: rec?.endpoint ?? '', present: false };
}
/**
* Fold the current kernel counters into `usage`. Counters restart from zero
* when a peer is re-added or the interface restarts; a drop is treated as a
* reset. Returns the per-device live view keyed by device id.
*
* A device missing from the dump had its counters reset only when its tunnel
* was actually read: an interface the tool couldn't read says nothing, and
* forgetting the last counters there would count them again on the next good
* read. A failed read with nothing in it changes nothing at all.
*/
export function collect(m, usage, d) {
d ??= dump();
d ??= dump(m);
let ts = time();
let live = {};
let by_key = {};
for (let id, dev in m.devices)
by_key[dev.public_key] = id;
if (d.ok === false && !length(d.peers)) {
for (let id in keys(m.devices))
live[id] = offline(usage.devices[id]);
return live;
}
for (let id, dev in m.devices) {
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
let peer = d.peers[dev.public_key];
if (!peer) {
rec.raw = [ 0, 0 ];
live[id] = { online: false, handshake: rec.handshake ?? 0, endpoint: rec.endpoint ?? '', present: false };
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
if (d.ok !== false || d.ifaces[ifname] != null)
rec.raw = [ 0, 0 ];
live[id] = offline(rec);
continue;
}
let raw = rec.raw ?? [ 0, 0 ];
@@ -260,9 +287,8 @@ export function save_usage(usage, persist) {
/** Sum of [rx, tx] over the last `days` days for a usage record. */
export function recent(rec, days) {
let out = [ 0, 0 ];
let ts = time();
for (let i = 0; i < days; i++) {
let v = rec?.days?.[day_key(ts - i * 86400)];
let v = rec?.days?.[day_key_ago(i)];
if (v) {
out[0] += v[0];
out[1] += v[1];
@@ -278,9 +304,8 @@ export function month(rec) {
/** Daily series for the last `days` days: [{ day, rx, tx }]. */
export function series(recs, days) {
let out = [];
let ts = time();
for (let i = days - 1; i >= 0; i--) {
let k = day_key(ts - i * 86400);
let k = day_key_ago(i);
let rx = 0, tx = 0;
for (let r in recs) {
let v = r?.days?.[k];
@@ -409,17 +434,7 @@ export function clear_events(f) {
/* ---------- health ---------- */
export function iface_status(ifname) {
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)
return null;
try {
return json(s);
}
catch (e) {
return null;
}
return util_iface_status(ifname);
};
export function uptime() {
@@ -0,0 +1,98 @@
// Dawnline — where names point and the router's public address, for Health
// and the portal settings. Lookups are cached in RUN_DIR for a few minutes
// and made in parallel with a short timeout: rpcd answers one call at a
// time, so a slow DNS server must not hold up the whole admin UI.
import { readfile } from 'fs';
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util';
import * as live from 'dawnline.live';
import * as net from 'dawnline.net';
const CACHE = `${RUN_DIR}/resolve.json`;
// Answers are kept 5 minutes, failures 1 minute.
const TTL = 300;
const TTL_FAIL = 60;
const TIMEOUT = 2;
const MAX_NAMES = 16;
// Public resolvers first: local DNS often rewrites the router's own name to
// its LAN address (split horizon).
const SERVERS = [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ];
function valid_name(h) {
return type(h) == 'string' && length(h) <= 253 && match(h, /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/) != null;
}
/**
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not
* resolve). IP addresses map to themselves. Every uncached name is asked of
* every server at once; the first server (in SERVERS order) that answers wins.
*/
export function resolve_all(hosts) {
let out = {}, now = time(), todo = [];
let cache = read_json(CACHE, {});
for (let h in hosts) {
if (h == null || out[h] != null)
continue;
if (ip2int(h) != null) {
out[h] = [ h ];
continue;
}
let c = cache[h];
if (c && now - c.ts < (length(c.ips) ? TTL : TTL_FAIL))
out[h] = c.ips;
else if (valid_name(h) && length(todo) < MAX_NAMES) {
out[h] = [];
push(todo, h);
}
else
out[h] = [];
}
if (!length(todo))
return out;
ensure_dir(RUN_DIR);
let dir = `${RUN_DIR}/resolve.${rand_hex(4)}`;
let cmds = [];
for (let i = 0; i < length(todo); i++)
for (let j = 0; j < length(SERVERS); j++)
push(cmds, `( timeout ${TIMEOUT} nslookup ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
for (let i = 0; i < length(todo); i++) {
let ips = [];
for (let j = 0; j < length(SERVERS) && !length(ips); j++) {
let r = readfile(`${dir}/${i}.${j}`) ?? '';
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null);
}
out[todo[i]] = ips;
cache[todo[i]] = { ts: now, ips };
}
system(`rm -rf ${dir}`);
// Only what is still fresh is kept.
for (let h, c in cache)
if (now - c.ts >= TTL)
delete cache[h];
write_json(CACHE, cache, 0o644);
return out;
};
/** IPv4 addresses of one name (see resolve_all). */
export function resolve(host) {
return resolve_all([ host ])[host] ?? [];
};
/** The IPv4 address of a netifd interface (a zone name for older configs). */
export function wan_ipv4(zone) {
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
return st?.['ipv4-address']?.[0]?.address;
};
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
export function router_wan(m) {
for (let id, srv in m.servers)
if (srv.private_key) {
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
if (a)
return a;
}
return wan_ipv4('wan');
};
@@ -14,12 +14,11 @@
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
// gets from DHCP, from the LAN side, so DNS interception applies as well.
//
// Separately, people with Home-only access get a plain resolver (real
// addresses from the WAN's DNS, home names from the LAN DNS): their internet
// does not use the tunnel, so fake-IP answers would break it. While the netns
// exists the resolver runs inside it and sends its upstream queries back out
// through the transit link as forwarded traffic — not as the router's own
// traffic and not from the LAN — so tools that capture either leave it alone.
// Separately, people with Home-only access get a plain resolver
// (dawnline.resolver). While the netns exists it runs inside it and sends its
// upstream queries back out through the transit link as forwarded traffic —
// not as the router's own traffic and not from the LAN — so tools that
// capture either leave it alone. This module says where it runs.
//
// Everything is derived from the router at run time; nothing assumes a
// particular subnet or tool. If the LAN is not a bridge or setup fails, the
@@ -27,18 +26,19 @@
import { readfile, writefile, readlink, stat, unlink } from 'fs';
import { cursor } from 'uci';
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, slog, RUN_DIR } from 'dawnline.util';
import {
sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR
} from 'dawnline.util';
import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
import * as resolver from 'dawnline.resolver';
export const NS = 'dawnline';
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
const RESOLVER_PORT = 5354;
export const RESOLVER_CONF = '/var/etc/dawnline-dns.conf';
const RESOLVER_RESOLV = '/var/etc/dawnline-dns.resolv';
const RESOLVER_PID = '/var/run/dawnline-dns.pid';
export const RESOLVER_CONF = resolver.CONF;
const STATE = `${RUN_DIR}/loop.json`;
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
const WHO = 'Internet like a home device';
@@ -60,17 +60,6 @@ function exists(dev) {
return stat(`/sys/class/net/${dev}`) != null;
}
function cidr_of(a) {
let m = match(a ?? '', /^([0-9.]+)\/([0-9]+)$/);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = +m[2];
if (ip == null || prefix < 8 || prefix > 30)
return null;
let size = 1 << (32 - prefix);
return { ip, prefix, size, net: ip - ip % size };
}
/* ---------- facts about the LAN ---------- */
/** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */
@@ -160,12 +149,8 @@ function pick_transit(saved) {
push(busy, n);
let free = (base) => {
for (let b in busy) {
let c = match(b, /^([0-9.]+)(\/([0-9]+))?$/);
if (!c)
continue;
let ip = ip2int(c[1]), size = 1 << (32 - (c[3] != null ? +c[3] : 32));
let bn = ip - ip % size;
if (base < bn + size && bn < base + 4)
let c = cidr_any(b);
if (c && base < c.net + c.size && c.net < base + 4)
return false;
}
return true;
@@ -203,9 +188,14 @@ function settings() {
return c.get_all('dawnline', 'settings') ?? {};
}
/** Servers that want "like a home device" (default on). */
/** Servers that want "like a home device" (default on) and run a core. */
function wanted(m) {
return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like);
return filter(values(m.servers), (s) => length(core.tunnels(s)) && s.enabled && s.lan_like);
}
/** Every server's interface, for rules. */
function all_ifnames(m) {
return map(values(m.servers), (s) => s.ifname);
}
/**
@@ -223,7 +213,7 @@ export function plan(m) {
return { error: 'No LAN detected.' };
if (d.kind != 'bridge')
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` };
let lan = cidr_of(d.addrs[0]);
let lan = parse_cidr(d.addrs[0]);
if (!lan)
return { error: `${dev} has no IPv4 address.` };
let facts = dhcp_facts(d.logical, lan);
@@ -241,7 +231,8 @@ export function plan(m) {
let servers = [];
for (let srv in srvs) {
let sn = net.server_net(srv, snap);
push(servers, { ifname: srv.ifname, subnet: srv.subnet, direct: net.collapse([ srv.subnet, ...sn.nets ]) });
for (let t in core.tunnels(srv))
push(servers, { ifname: t.ifname, subnet: t.subnet, direct: net.collapse([ t.subnet, ...sn.nets ]) });
}
return {
dev,
@@ -332,7 +323,9 @@ function tunnel_ifnames() {
let c = cursor();
c.load('dawnline');
let out = [];
c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name']));
c.foreach('dawnline', 'server', (s) => {
push(out, s.ifname ?? s['.name']);
});
return out;
}
@@ -360,13 +353,14 @@ export function remove(ifnames) {
* last applied plan and only checks that links, bridge port and rules exist.
*/
export function ensure(m, force) {
let ifnames = map(values(m.servers), (s) => s.ifname);
let ifnames = all_ifnames(m);
let p = plan(m);
if (p.off || p.error) {
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
// Read before remove(), which deletes it: the error is logged once, not every tick.
let was = read_json(STATE, {});
if (was.plan || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
remove(ifnames);
ensure_dir(RUN_DIR);
let was = read_json(STATE, {});
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
if (p.error && p.error != was.error)
log('is off', 'error', p.error);
@@ -423,15 +417,6 @@ export function ensure(m, force) {
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
return { error: errs[0] };
}
// Keep the chosen LAN address stable across restarts.
let c = cursor();
c.load('dawnline');
if (c.get('dawnline', 'settings', 'lan_address') != p.address) {
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', 'settings', 'lan_address', p.address);
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
}
ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
@@ -441,6 +426,20 @@ export function ensure(m, force) {
return p;
};
/**
* Keep the chosen LAN address stable across restarts (settings.lan_address).
* Called by dawnline.apply once its own lock is released: the config lock is
* never taken inside it.
*/
export function remember(p) {
if (!p?.address || settings().lan_address == p.address)
return;
store.transact((c, m) => {
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', 'settings', 'lan_address', p.address);
});
};
/** Last applied state for views and health checks. */
export function status() {
let s = read_json(STATE, {});
@@ -461,33 +460,6 @@ export function client_dns() {
/* ---------- plain resolver for Home-only clients ---------- */
function wan_dns() {
let out = [];
let snap = net.snapshot();
let wan = snap.devices[snap.wan]?.logical;
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
if (!name)
continue;
try {
let st = json(sh_out(`ubus call network.interface.${name} status 2>/dev/null`) || 'null');
for (let a in st?.['dns-server'] ?? [])
if (match(a, /^[0-9.]+$/))
push(out, a);
}
catch (e) {}
}
return length(out) ? uniq(out) : FALLBACK_DNS;
}
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
function lan_domain(m) {
let c = cursor();
c.load('dhcp');
let d = null;
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
return uniq(filter([ d, m.settings.domain ], (x) => x));
}
/** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */
export function lan_dns() {
let st = status();
@@ -496,7 +468,10 @@ export function lan_dns() {
let snap = net.snapshot();
let d = snap.devices[snap.lan];
let a = d?.addrs?.[0];
return a ? (dhcp_facts(d.logical, cidr_of(a))?.dns ?? split(a, '/')[0]) : null;
if (!a)
return null;
let lan = parse_cidr(a);
return (lan ? dhcp_facts(d.logical, lan).dns : null) ?? split(a, '/')[0];
};
/**
@@ -505,62 +480,17 @@ export function lan_dns() {
*/
export function resolver_target() {
let st = status();
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT };
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: resolver.PORT };
};
/**
* Write the resolver config; returns true when it changed (the running
* instance is then restarted by procd's respawn after a kill). The first line
* tells /usr/libexec/dawnline/resolver where to run it.
*/
/** Write the resolver config where it should run now; true when it changed (see dawnline.resolver). */
export function sync_resolver(m) {
ensure_dir('/var/etc');
let ifs = map(filter(values(m.servers), (s) => s.private_key), (s) => s.ifname);
let target = resolver_target();
let lan = lan_dns();
let lines = [
`# mode=${target.mode}`,
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
`port=${target.port}`,
'no-hosts',
'bogus-priv',
'cache-size=1000',
`pid-file=${RESOLVER_PID}`,
'user=dnsmasq',
'group=dnsmasq',
];
if (target.mode == 'ns') {
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
// Upstream from the transit address: forwarded through the router to the WAN.
for (let a in wan_dns())
push(lines, `server=${a}@${target.address}`);
}
else {
push(lines, 'bind-dynamic', ...map(ifs, (i) => `interface=${i}`), `resolv-file=${RESOLVER_RESOLV}`);
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
if ((readfile(RESOLVER_RESOLV) ?? '') != resolv) {
writefile(RESOLVER_RESOLV, resolv);
system(`chmod 644 ${RESOLVER_RESOLV}`);
}
}
if (lan)
for (let d in lan_domain(m))
push(lines, `server=/${d}/${lan}`);
let conf = join('\n', lines) + '\n';
if ((readfile(RESOLVER_CONF) ?? '') == conf)
return false;
writefile(RESOLVER_CONF, conf);
system(`chmod 644 ${RESOLVER_CONF}`);
let pid = trim(readfile(RESOLVER_PID) ?? '');
if (match(pid, /^[0-9]+$/))
system(`kill ${pid} 2>/dev/null`);
return true;
return resolver.sync(m, resolver_target(), lan_dns());
};
/** True when the resolver process is alive. */
export function resolver_running() {
let pid = trim(readfile(RESOLVER_PID) ?? '');
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
return resolver.running();
};
export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF };
export const RESOLVER = { port: resolver.PORT, conf: resolver.CONF };
@@ -0,0 +1,64 @@
// Dawnline — one-time steps for routers set up by older versions. Each one
// checks first and writes nothing when there is nothing to do; dawnline.apply
// runs them before it takes its own lock (changes to /etc/config/dawnline go
// through dawnline.store and its config lock).
import { cursor } from 'uci';
import { stat, unlink } from 'fs';
import { q, slog } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
function word_codes() {
let old = (s) => s.code != null && !match(s.code, core.WORD_CODE);
let c = cursor();
c.load('dawnline');
let any = false;
c.foreach('dawnline', 'person', (s) => {
if (old(s))
any = true;
});
if (!any)
return;
store.transact((w, m) => {
w.foreach('dawnline', 'person', (s) => {
if (old(s)) {
w.set('dawnline', s['.name'], 'code', core.new_code());
w.delete('dawnline', s['.name'], 'words');
}
});
});
slog('dawnline', 'info', 'moved to word codes', null, 'Personal links');
}
/*
* Older versions answered on 443 at home through LuCI's web server (its error
* page ran the portal CGI). The portal now keeps its own port: remove that.
*/
export function uhttpd() {
let c = cursor();
c.load('uhttpd');
if (c.get('uhttpd', 'main', 'error_page') == LAN_CGI_URL) {
c.delete('uhttpd', 'main', 'error_page');
c.commit('uhttpd');
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
system(`logger -t dawnline ${q('portal removed from the LuCI web server')}`);
}
if (stat(LAN_CGI))
unlink(LAN_CGI);
// The old setting itself.
let d = cursor();
d.load('dawnline');
if (d.get('dawnline', 'settings', 'portal_443') != null)
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
};
/** All of them, in order. */
export function run() {
word_codes();
uhttpd();
};
@@ -14,12 +14,17 @@
import { readfile, readlink, lsdir, stat } from 'fs';
import { cursor } from 'uci';
import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util';
import { sh_out, ip2int, int2ip, cidr_any, uniq } from 'dawnline.util';
const SYS = '/sys/class/net';
/** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */
export const INTERNAL = { transit: 'dlx0', lan: 'dll0' };
const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ];
const VPN_NAMES = /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/;
// Never the WAN while another default route exists: VPN clients. (PPTP and
// L2TP stay eligible: some ISPs connect the WAN with them.)
const NOT_WAN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc' ];
const NOT_WAN_NAMES = /^(wg|awg|tun|tap|ovpn)/;
// Kernel placeholder devices that never carry a network on their own.
const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/;
const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ];
@@ -48,16 +53,8 @@ function ubus_json(path, method) {
/** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */
function net_of(s) {
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
if (ip == null || prefix < 1 || prefix > 32)
return null;
let size = 1 << (32 - prefix);
if (prefix == 1)
size = 2147483648;
return { net: ip - ip % size, prefix, size };
let c = cidr_any(s);
return c && c.prefix >= 1 ? c : null;
}
function net_str(n) {
@@ -107,12 +104,12 @@ export function snapshot(fresh) {
return cache;
// Networks reachable through each device (main table, IPv4).
let routes = {}, wan_dev = null;
let routes = {}, defaults = [];
for (let r in ip_json('-4 route show table main')) {
if (!r.dev)
continue;
if (r.dst == 'default') {
wan_dev ??= r.dev;
push(defaults, r);
continue;
}
push(routes[r.dev] ??= [], r.dst);
@@ -130,6 +127,19 @@ export function snapshot(fresh) {
if (dev && !logical[dev])
logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
}
// The WAN: the default route with the lowest metric that does not go into
// a VPN client (its default route is not where the tunnels listen); only
// VPN routes: the lowest of them.
let vpn = (dev) => index(NOT_WAN_PROTOS, logical[dev]?.proto) >= 0 || match(dev, NOT_WAN_NAMES) != null;
let wan_dev = null, wan_metric = null, wan_vpn = true;
for (let r in defaults) {
let v = vpn(r.dev), metric = r.metric ?? 0;
if (wan_dev == null || (wan_vpn && !v) || (wan_vpn == v && metric < wan_metric)) {
wan_dev = r.dev;
wan_metric = metric;
wan_vpn = v;
}
}
let zone_by_net = {}, zone_by_dev = {}, zones = [];
let fc = cursor();
fc.load('firewall');
@@ -163,7 +173,7 @@ export function snapshot(fresh) {
let cat;
if (wifi)
cat = 'wifi';
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/))
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, VPN_NAMES))
cat = 'vpn';
else if (kind == 1 || bridge)
cat = 'ethernet';
@@ -238,7 +248,9 @@ export function server_net(srv, snap) {
if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master)
continue;
let d = devs[dev];
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? null, missing: !d };
// The detected LAN missing for a moment (bridge recreated) keeps its zone,
// so its forwardings are not removed meanwhile.
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? (p[1] ? srv.lan_zone : null), missing: !d };
push(home, h);
push(nets, ...h.nets);
if (h.zone)
@@ -0,0 +1,125 @@
// Dawnline — netifd: one AmneziaWG interface per server, named after its
// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created
// are changed or removed: a name already used by another interface (`lan`, a
// tunnel of your own, one from an imported config) is left alone and the
// server is reported instead.
import { cursor } from 'uci';
import { stat, unlink, writefile } from 'fs';
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
// Set while AmneziaWG is missing and that was logged (once until it is back).
const NO_AWG = `${RUN_DIR}/netifd-no-awg`;
function log(who, msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, who);
}
/** The server id that owns network.<ifname>: null when the section is free, '' when someone else's. */
export function owner(ifname, c) {
if (!c) {
c = cursor();
c.load('network');
}
if (c.get('network', ifname) == null)
return null;
return c.get('network', ifname, '_dawnline') ?? '';
};
/** Bring network config in line with the servers; true when it changed. */
export function sync(m) {
let c = cursor();
c.load('network');
let changed = false, touched = [], want = {};
// Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts.
let was = read_json(core.BLOCKED, {}), blocked = {};
let block = (srv, msg, detail) => {
blocked[srv.id] = msg;
// The rest of this apply works from the same model: no tunnel for it there either.
srv.blocked = msg;
if (was[srv.id] != msg)
log(srv.name, msg, 'error', detail);
};
// Without amneziawg-tools there is no protocol script: changing or bringing
// up an interface would only stop a tunnel that is still running.
let tools = awg.state().tools;
if (tools && stat(NO_AWG))
unlink(NO_AWG);
else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) {
log('AmneziaWG', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.');
ensure_dir(RUN_DIR);
writefile(NO_AWG, `${time()}`);
}
for (let id, srv in m.servers) {
if (!srv.private_key)
continue;
let ifn = srv.ifname;
if (!core.valid_ifname(ifn)) {
block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.');
continue;
}
let own = owner(ifn, c);
if (own != null && own != id) {
block(srv, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`,
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue;
}
delete srv.blocked;
want[ifn] = true;
if (!tools)
continue;
// Per server: with several, each changed one has to be brought up again.
let mine = uci_section(c, 'network', ifn, 'interface');
let set = (opt, val) => {
if (uci_put(c, 'network', ifn, opt, val))
mine = true;
};
for (let k, v in awg.netifd_options(srv))
set(k, v);
set('disabled', srv.enabled ? null : '1');
set('auto', srv.enabled ? null : '0');
set('_dawnline', id);
// For the log once the server is gone.
set('_dawnline_name', srv.name);
if (mine) {
changed = true;
push(touched, ifn);
// The hotplug log says why the tunnel goes down (not a failure).
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
}
}
if (sprintf('%J', blocked) != sprintf('%J', was)) {
ensure_dir(RUN_DIR);
write_json(core.BLOCKED, blocked, 0o644);
}
// Remove interfaces Dawnline created for servers that no longer exist.
let stale = [];
c.foreach('network', 'interface', (s) => {
if (s._dawnline && !want[s['.name']])
push(stale, s['.name']);
});
for (let ifn in stale) {
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
system(`ifdown ${q(ifn)} 2>/dev/null`);
c.delete('network', ifn);
changed = true;
}
if (changed) {
c.commit('network');
ack_config([ 'network' ]);
system('ubus call network reload');
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
system(`ifup ${q(ifn)}`);
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
}
return changed;
};
@@ -0,0 +1,225 @@
// Dawnline — the nft table `inet dawnline`: each person's access, enforced
// on the tunnel interfaces before anything else on the router sees the
// traffic, and where tunnel DNS goes. Its shape follows the servers and their
// home networks (rebuild); who is in which set follows people's state and
// changes often (update, one atomic transaction).
import { unlink } from 'fs';
import { sh, ensure_dir, write_file, rand_hex, ip2int, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
/** The sets whose members change at run time (update replaces them together). */
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
function ip4(a) {
return ip2int(a ?? '') != null;
}
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
// lan_ok: home access (the router itself, the mesh); lan_all: every home
// network; lan_part: device . network for people limited to some networks;
// mesh_pairs: device . device within a circle (or one person's own devices);
// svc_ok: device . service . port; svc_host: device . service with no ports (all of them).
let sets = {};
for (let k in SETS)
sets[k] = [];
let snap = net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
// Off: paused, ended, over quota or out of hours. Addresses go into nft as they are: IPv4 only.
if (!p || d.disabled || !ip4(d.address) || states[p.id] != 'active')
continue;
// Home names: the plain resolver (their internet does not use the tunnel).
if (p.access == 'lan' && p.dns_mode == 'home')
push(sets.dns_real, d.address);
if (p.access == 'internet' || p.access == 'both')
push(sets.inet_ok, d.address);
if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) {
push(sets.lan_ok, d.address);
let srv = m.servers[p.server];
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
if (h.all)
push(sets.lan_all, d.address);
else
for (let n in h.nets)
push(sets.lan_part, `${d.address} . ${n}`);
// Who this device may reach directly: its circle, or at least its owner's devices.
if (srv?.mesh == 'circles') {
let ci = core.person_circle(m, p);
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
}
}
else if (p.access == 'lan')
for (let sid in p.services) {
let s = m.services[sid];
if (!s || !ip4(s.address))
continue;
if (!length(s.ports))
push(sets.svc_host, `${d.address} . ${s.address}`);
for (let port in s.ports)
if (match(port, /^[0-9]+$/))
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
}
}
for (let g, addrs in groups)
for (let a in addrs)
for (let b in addrs)
if (a != b)
push(sets.mesh_pairs, `${a} . ${b}`);
return sets;
};
function set_elems(arr) {
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
function table(m, sets) {
let ifs = [], lan = [], tun = [];
let dns_addr = loop.client_dns();
if (!ip4(dns_addr))
dns_addr = null;
let rt = loop.resolver_target();
let snap = net.snapshot();
for (let id, srv in m.servers) {
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
let tns = core.tunnels(srv);
for (let t in tns) {
push(ifs, `"${t.ifname}"`);
push(tun, t.subnet);
}
if (length(tns))
push(lan, ...net.server_net(srv, snap).nets);
}
lan = net.collapse(lan);
tun = net.collapse(tun);
let t = [];
push(t, 'table inet dawnline {');
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
// Tunnel subnets are never "home", even inside a wider route to the LAN.
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
push(t, ` set svc_host { type ipv4_addr . ipv4_addr; ${set_elems(sets.svc_host)} }`);
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
push(t, ' chain pre {');
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
push(t, ' type filter hook prerouting priority -160; policy accept;');
if (length(ifs))
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
push(t, ' }');
push(t, ' chain guard {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct state established,related accept');
push(t, ' icmp type echo-request fib daddr type local accept');
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
push(t, ' fib daddr type local ip saddr @lan_ok accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
push(t, ' ip daddr @lan_nets ip daddr != @tun_nets ip saddr @lan_all accept');
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
// firewall has no forwarding between different servers' zones.
for (let id, srv in m.servers)
for (let tn in core.tunnels(srv))
if (srv.mesh == 'all')
push(t, ` iifname "${tn.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
else if (srv.mesh == 'circles')
push(t, ` iifname "${tn.ifname}" ip saddr . ip daddr @mesh_pairs accept`);
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
push(t, ' ip saddr . ip daddr @svc_host accept');
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
push(t, ' ip saddr @inet_ok accept');
push(t, ' counter drop');
push(t, ' }');
// The other way: fw4 lets the server's home zones reach the tunnel; here
// only connections from its home networks to people with home access pass
// (paused, ended and internet-only people are not reachable). The admin's
// own port forwards (DNAT) stay with fw4.
push(t, ' chain inbound {');
push(t, ' type filter hook forward priority filter - 5; policy accept;');
if (length(ifs))
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
push(t, ' }');
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
push(t, ' ip saddr @lan_nets ip saddr != @tun_nets ip daddr @lan_all accept');
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
push(t, ' counter reject with icmpx admin-prohibited');
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
let lan_dns = loop.lan_dns();
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
if (length(ifs))
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
for (let id, srv in m.servers)
for (let tn in core.tunnels(srv)) {
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
push(t, ` iifname "${tn.ifname}" ip daddr ${tn.address} meta l4proto { tcp, udp } th dport 53 ${target}`);
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
export function load(script) {
ensure_dir(RUN_DIR);
// A file of its own: two writers must never load each other's script.
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
if (!write_file(f, script))
return `couldn't write ${f}`;
let r = sh(`nft -f ${f}`);
unlink(f);
if (r.code == 0)
return null;
// Without the random file name, so the same failure reads the same every time.
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
};
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
export function rebuild(m, sets) {
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
};
/**
* Replace the members of every runtime set at once; null or the error. Fails
* as a whole when the table or one of its sets is missing (not loaded yet,
* or an older shape): the caller then rebuilds.
*/
export function update(sets) {
let s = '';
for (let name in SETS) {
s += `flush set inet dawnline ${name}\n`;
if (length(sets[name]))
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
}
return load(s);
};
/** Is the table loaded (watchdog). */
export function present() {
return system('nft list table inet dawnline >/dev/null 2>&1') == 0;
};
export function remove() {
system('nft delete table inet dawnline 2>/dev/null');
};
@@ -1,690 +0,0 @@
// Dawnline — operations: health checks (with fixes), backups, export/import.
import { readfile, writefile, stat, unlink, lsdir } from 'fs';
import { cursor } from 'uci';
import {
q, sh, sh_out, ensure_dir, read_json, write_json, write_file, parse_cidr, cidr_overlaps, cidr_str,
ip2int, in_cidr, file_exists, valid_host, cloudflare_ip, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop';
import * as net from 'dawnline.net';
const BACKUP_DIR = `${DATA_DIR}/backups`;
const KEEP_BACKUPS = 10;
/**
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link). Checked by
* files, so it is cheap enough for every page load.
*/
export function needs() {
let tls = false;
for (let d in [ '/lib', '/usr/lib' ])
for (let f in lsdir(d) ?? [])
if (substr(f, 0, 16) == 'libustream-ssl.s')
tls = true;
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let veth = stat('/sys/module/veth') != null || file_exists(`/lib/modules/${kver}/veth.ko`);
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
return {
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]),
bonjour: miss([ [ file_exists('/usr/sbin/umdns'), 'umdns' ] ]),
};
};
/** True while OpenWrt's mDNS daemon answers on ubus. */
export function mdns_running() {
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
};
/**
* Services announced on the home networks (Bonjour), from umdns:
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
*/
export function mdns_services() {
if (!mdns_running())
return [];
let r = {};
try {
r = json(sh_out(`ubus call umdns browse '{"address":true}' 2>/dev/null`) || '{}') ?? {};
}
catch (e) {
r = {};
}
let out = [];
for (let t, insts in r)
for (let name, i in insts) {
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
if (addr)
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
}
return out;
};
/** ACME certificates on the router and the names each covers. */
function acme_certs() {
let out = [];
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
let m = match(f, /^(.+)\.fullchain\.crt$/);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
if (!file_exists(k))
continue;
let sans = sh_out(`openssl x509 -in ${q(c)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
push(out, { cert: c, key: k, names: filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '') });
}
return out;
}
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
function acme_cert_for(host) {
for (let a in acme_certs())
for (let n in a.names)
if (n == host || (substr(n, 0, 2) == '*.' && index(host, '.') > 0 && substr(host, index(host, '.')) == substr(n, 1)))
return a;
return null;
}
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
export function portal_cert(s) {
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
if (s.portal_host) {
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
let c = `${base}.fullchain.crt`, k = `${base}.key`;
if (file_exists(c) && file_exists(k))
return { cert: c, key: k, self_signed: false };
}
// An ACME certificate issued for several names, the portal's among them.
let a = acme_cert_for(s.portal_host);
if (a)
return { cert: a.cert, key: a.key, self_signed: false };
}
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
if (!file_exists(c) || !file_exists(k)) {
ensure_dir(DATA_DIR, 0o700);
let cn = s.portal_host || 'dawnline';
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
system(`chmod 600 ${k}`);
}
return { cert: c, key: k, self_signed: true };
};
/* ---------- health ---------- */
function check(id, title, status, detail, fix) {
return { id, title, status, detail: detail ?? '', fix: fix ?? null };
}
export function udp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
if (index(readfile(f) ?? '', hex) >= 0)
return true;
return false;
};
export function tcp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
for (let line in split(readfile(f) ?? '', '\n'))
// state 0A = LISTEN
if (index(line, hex) > 0 && match(line, / 0A /))
return true;
return false;
};
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
export function tcp_port_owners(port) {
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
let owners = [];
for (let o in split(out, '\n')) {
let name = split(o, '/')[1];
if (!name || index(owners, name) >= 0)
continue;
// Our own portal runs as a dedicated uhttpd instance.
let pid = +split(o, '/')[0];
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
continue;
push(owners, name);
}
return owners;
};
function resolve(host) {
if (ip2int(host) != null)
return [ host ];
// Public resolvers first: local DNS often rewrites the router's own name
// to its LAN address (split horizon).
for (let srv in [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]) {
let out = sh_out(`timeout 5 nslookup ${q(host)} ${srv} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}'`);
let ips = out ? filter(split(out, '\n'), (x) => ip2int(x) != null) : [];
if (length(ips))
return ips;
}
return [];
}
function wan_ipv4(zone) {
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
return st?.['ipv4-address']?.[0]?.address;
}
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
function router_wan(m) {
for (let id, srv in m.servers)
if (srv.private_key) {
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
if (a)
return a;
}
return wan_ipv4('wan');
}
/*
* Addresses the portal could use in links, found on the router: names in ACME
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
* Each says where it points and whether a certificate covers it.
*/
export function portal_candidates(m) {
let wan = router_wan(m);
let names = [];
let add = (h) => {
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
push(names, h);
};
for (let a in acme_certs())
for (let n in a.names)
add(n);
for (let id, srv in m.servers)
add(srv.endpoint);
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (sv) => {
if (sv.enabled != '0') {
add(sv.lookup_host);
add(sv.domain);
}
});
for (let h in core.portal_hosts(m))
add(h);
let out = [];
for (let h in names) {
let ips = resolve(h);
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: acme_cert_for(h) != null });
}
if (wan)
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
for (let ph in core.portal_hosts(m))
if (ip2int(ph) != null && ph != wan)
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
// Best first: here with a certificate, then here, then the rest.
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
return sort(out, (a, b) => score(b) - score(a));
};
export function service_running(name, instance) {
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
if (!s)
return false;
try {
let j = json(s);
let inst = j?.[name]?.instances?.[instance];
return !!inst?.running;
}
catch (e) {
return false;
}
};
function other_subnets(srv_id) {
let out = [];
let st = sh_out('ubus call network.interface dump 2>/dev/null');
let d = st ? json(st) : null;
let ours = {};
let m = core.load();
for (let id, s in m.servers)
ours[s.ifname] = id;
for (let i in d?.interface ?? []) {
if (srv_id != null && ours[i.interface] == srv_id)
continue;
for (let a in i['ipv4-address'] ?? [])
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
}
return out;
}
export function used_subnets(except_srv) {
return map(other_subnets(except_srv), (x) => x.cidr);
};
/**
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
* `fix` names an action accepted by fix().
*/
/*
* Policy rules that send the router's own (marked) traffic into a local table,
* the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100".
*/
function proxy_diverts() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/);
if (!mm || +mm[1] >= 32766)
continue;
if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/))
push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`);
}
return out;
}
/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */
function reply_rule(proto, port) {
return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0;
}
function reply_check(id, title, proto, port, diverts) {
let ok = reply_rule(proto, port);
let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : '';
return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'),
ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}`
: length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.`
: `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`,
ok ? null : 'apply');
}
export function health(m) {
let diverts = proxy_diverts();
m ??= core.load();
let out = [];
let dmp = live.dump();
let kmod = file_exists('/sys/module/amneziawg');
let tools = file_exists('/usr/bin/awg');
push(out, check('awg', 'AmneziaWG installed', kmod && tools ? 'ok' : 'error',
kmod && tools ? 'Kernel module and awg tool present.' :
(!tools ? 'amneziawg-tools is missing.' : 'The kmod-amneziawg module is not loaded.'), kmod && tools ? null : 'updates'));
let y = localtime().year;
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
push(out, check('agent', 'Background agent running', service_running('dawnline', 'agent') ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', service_running('dawnline', 'agent') ? null : 'restart'));
if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
return out;
}
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
nft_ok ? null : 'apply'));
let fwc = cursor();
fwc.load('firewall');
for (let id, srv in m.servers) {
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
if (!srv.enabled) {
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
continue;
}
let st = live.iface_status(srv.ifname);
let up = !!st?.up;
push(out, check(`up_${id}`, `Tunnel interface up${label}`, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
(st ? `${srv.ifname} is down${st.errors ? ': ' + join(', ', map(st.errors, (e) => e.code)) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
if (up) {
let expected = 0;
let states = apply.states_for(m, core.load_usage());
for (let did, d in m.devices)
if (m.people[d.person]?.server == id && !d.disabled && states[d.person] == 'active')
expected++;
let actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname)
actual++;
push(out, check(`peers_${id}`, `Devices loaded${label}`, expected == actual ? 'ok' : 'warn',
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `Firewall${label}`, rule && zone ? 'ok' : 'error',
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
rule && zone ? null : 'apply'));
push(out, reply_check(`reply_${id}`, `Answers reach clients${label}`, 'udp', srv.port, diverts));
// Port collisions with other tunnels.
let clash = [];
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
push(clash, s['.name']);
});
if (length(clash))
push(out, check(`port_${id}`, `Port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
let overlaps = [];
let sc = parse_cidr(srv.subnet);
for (let o in other_subnets(id)) {
let oc = parse_cidr(o.cidr);
if (sc && oc && cidr_overlaps(sc, oc))
push(overlaps, `${o.iface} (${o.cidr})`);
}
push(out, check(`subnet_${id}`, `Subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
let host = core.endpoint_host(m, srv);
if (!host)
push(out, check(`ep_${id}`, `Public address${label}`, 'error', 'No endpoint hostname: clients will not know where to connect.'));
else {
let ips = resolve(host);
let wan = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
let wc = wan ? ip2int(wan) : null;
let cgnat = wc != null && (in_cidr(wc, parse_cidr('100.64.0.0/10')) || in_cidr(wc, parse_cidr('10.0.0.0/8')) ||
in_cidr(wc, parse_cidr('172.16.0.0/12')) || in_cidr(wc, parse_cidr('192.168.0.0/16')));
let stv = 'ok', det;
if (!length(ips)) {
stv = 'error';
det = `${host} does not resolve.`;
}
else if (cgnat) {
stv = 'warn';
det = `WAN address ${wan} is private: forward UDP ${srv.port} on the upstream router, or clients cannot connect.`;
}
else if (length(filter(ips, (a) => cloudflare_ip(a))))
det = `${host} → ${join(', ', ips)} (Cloudflare). The tunnel is UDP: it reaches the router only if this name is DNS-only there.`;
else if (wan && index(ips, wan) < 0) {
stv = 'warn';
det = `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`;
}
else
det = `${host} → ${join(', ', ips)}`;
push(out, check(`ep_${id}`, `Public address${label}`, stv, det));
}
if (srv.lan_like) {
let ls = loop.status();
let nh = needs().home;
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
ls.active ? `The link is up but not attached to ${ls.dev}.` :
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
}
}
if (length(filter(values(m.servers), (x) => x.private_key))) {
let rt = loop.resolver_target();
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
}
let s = m.settings;
let need = needs();
if (s.portal_enabled && length(need.https))
push(out, check('portal', 'Personal portal', 'error',
`HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https'));
else if (s.portal_enabled) {
let owners = tcp_port_owners(s.portal_port);
let listening = tcp_listening(s.portal_port);
if (length(owners))
push(out, check('portal', 'Personal portal', 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
else
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
if (!s.portal_host)
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
else {
let ips = resolve(s.portal_host), wan = router_wan(m);
let cf = filter(ips, (x) => cloudflare_ip(x));
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
!length(ips) ? `${s.portal_host} does not resolve.` :
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
}
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts));
if (core.portal_http(m)) {
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
push(out, check('portal_http', 'Plain HTTP links', 'warn',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
}
// Links on 443: forwarded from outside, and the same link at home through LuCI's web server.
let pub = core.portal_public_port(m);
if (s.portal_port != 443) {
if (!s.portal_443)
push(out, check('portal_443', 'Links without a port', 'skip',
`Off: links use port ${s.portal_port}. Mobile networks often drop HTTPS on ports other than 443.`));
else if (pub != 443)
push(out, check('portal_443', 'Links without a port', 'warn',
`TCP 443 is already forwarded to another device, so links use port ${s.portal_port}.`));
else {
let fw = system(`nft list ruleset 2>/dev/null | grep -q 'Dawnline-Portal-443'`) == 0;
push(out, check('portal_443', 'Links without a port', fw ? 'ok' : 'error',
fw ? `From the internet TCP 443 reaches the portal only (LuCI stays closed there).` : 'The 443 forward to the portal is missing.',
fw ? null : 'apply'));
let uc_ = cursor();
uc_.load('uhttpd');
let ep = uc_.get('uhttpd', 'main', 'error_page');
let mine = ep == '/cgi-bin/dawnline-portal' && stat('/www/cgi-bin/dawnline-portal') != null;
push(out, check('portal_lan', 'Same link at home', mine ? 'ok' : ep ? 'warn' : 'error',
mine ? 'At home the link opens through LuCI\'s web server, which hands unknown paths to the portal.'
: ep ? `LuCI's web server already uses ${ep} for unknown paths, so at home links need :${s.portal_port}.`
: 'LuCI\'s web server does not hand portal links to the portal: at home they show Not found.',
mine || ep ? null : 'apply'));
}
}
let cert = portal_cert(s);
if (ip2int(s.portal_host) != null)
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
else {
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
let sans = cert.self_signed ? [] : split(replace(sh_out(`openssl x509 -in ${q(cert.cert)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '', /DNS:/g, ''), /[ \t\r\n]+/);
let covers = !s.portal_host || cert.self_signed || index(sans, s.portal_host) >= 0 ||
length(filter(sans, (n) => substr(n, 0, 2) == '*.' && substr(s.portal_host, index(s.portal_host, '.')) == substr(n, 1)));
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
}
}
return out;
};
export function fix(id) {
if (id == 'apply')
return apply.apply();
if (id == 'sync')
return apply.sync();
if (id == 'restart')
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
if (m) {
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
};
/* ---------- backups ---------- */
function backup_files() {
let out = [ '/etc/config/dawnline' ];
for (let f in [ 'usage.json', 'events.json' ])
if (file_exists(`${DATA_DIR}/${f}`))
push(out, `${DATA_DIR}/${f}`);
return out;
}
export function backup_list() {
let out = [];
for (let f in lsdir(BACKUP_DIR) ?? []) {
let mm = match(f, /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/);
if (!mm)
continue;
let st = stat(`${BACKUP_DIR}/${f}`);
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
}
return sort(out, (a, b) => b.created - a.created);
};
export function backup_create(reason) {
// Flush live counters first so the backup has current usage.
let u = read_json(`${RUN_DIR}/usage.json`, null);
if (u)
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
live.persist_events();
ensure_dir(BACKUP_DIR, 0o700);
let t = localtime();
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
let files = join(' ', map(backup_files(), (f) => q(substr(f, 1))));
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
if (r.code != 0)
die(`Backup failed: ${trim(r.out)}`);
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let all = backup_list();
for (let i = KEEP_BACKUPS; i < length(all); i++)
unlink(`${BACKUP_DIR}/${all[i].name}`);
return name;
};
function backup_path(name) {
if (!match(name ?? '', /^dawnline-[0-9]{8}-[0-9]{6}(-[a-z0-9-]+)?\.tar\.gz$/))
die('Invalid backup name.');
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
return p;
}
/** Validate an archive: only Dawnline's own files may be inside. */
function check_archive(path) {
let r = sh(`tar -tzf ${q(path)}`);
if (r.code != 0)
die('Not a valid backup archive.');
let allowed = { 'etc/config/dawnline': true };
let has_config = false;
for (let f in split(trim(r.out), '\n')) {
f = replace(f, /^\.?\//, '');
// The config plus Dawnline's own data files (older versions had more of them).
if (!allowed[f] && !match(f, /^etc\/dawnline\/[a-z0-9_-]+\.json$/))
die(`Unexpected file in backup: ${f}`);
if (f == 'etc/config/dawnline')
has_config = true;
}
if (!has_config)
die('Backup does not contain /etc/config/dawnline.');
}
export function backup_restore(name, path) {
path ??= backup_path(name);
check_archive(path);
backup_create('pre-restore');
let r = sh(`tar -xzf ${q(path)} -C /`);
if (r.code != 0)
die(`Restore failed: ${trim(r.out)}`);
system('chmod 600 /etc/config/dawnline');
// Live counters must follow the restored file.
unlink(`${RUN_DIR}/usage.json`);
unlink(`${RUN_DIR}/events.json`);
return apply.apply();
};
export function backup_delete(name) {
unlink(backup_path(name));
return true;
};
export function backup_read(name) {
return b64enc(readfile(backup_path(name)));
};
export function backup_upload(data_b64) {
let data = b64dec(data_b64 ?? '');
if (!data || length(data) > 4 * 1024 * 1024)
die('Upload is empty or too large.');
ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data);
let res;
try {
res = backup_restore(null, tmp);
}
catch (e) {
unlink(tmp);
die(e.message);
}
unlink(tmp);
return res;
};
/* ---------- export / import (JSON) ---------- */
export function export_json() {
let c = cursor();
c.load('dawnline');
let sections = [];
c.foreach('dawnline', null, (s) => {
let o = { '.type': s['.type'], '.name': s['.name'] };
for (let k, v in s)
if (substr(k, 0, 1) != '.')
o[k] = v;
push(sections, o);
});
return { format: 'dawnline', version: VERSION, exported: time(), sections };
};
export function import_json(data) {
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
die('Not a Dawnline export.');
let types = { settings: true, server: true, person: true, device: true, service: true };
for (let s in data.sections) {
if (!types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
die(`Invalid section ${s['.name']}.`);
for (let k, v in s)
if (substr(k, 0, 1) != '.' && (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')))
die(`Invalid option ${k}.`);
}
backup_create('pre-import');
let lines = [];
for (let s in data.sections) {
push(lines, `config ${s['.type']} '${s['.name']}'`);
for (let k, v in s) {
if (substr(k, 0, 1) == '.')
continue;
let esc = (x) => replace(`${x}`, "'", "'\\''");
if (type(v) == 'array')
for (let x in v)
push(lines, `\tlist ${k} '${esc(x)}'`);
else
push(lines, `\toption ${k} '${esc(v)}'`);
}
push(lines, '');
}
write_file('/etc/config/dawnline', join('\n', lines), 0o600);
return apply.apply();
};
@@ -0,0 +1,120 @@
// Dawnline — one interface over the router's package manager: opkg on
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
// callback, which gets their output line by line.
import { access, popen } from 'fs';
import { q } from 'dawnline.util';
function run(cmd) {
let p = popen(cmd + ' 2>&1', 'r');
if (!p)
return { code: 127, out: '' };
let out = p.read('all') ?? '';
return { code: p.close(), out };
}
function logged(cmd, log) {
let r = run(cmd);
for (let line in split(trim(r.out), '\n'))
if (length(trim(line)))
log?.(` ${line}`);
return r;
}
export function is_apk() {
return access('/usr/bin/apk', 'x');
};
export function ext() {
return is_apk() ? 'apk' : 'ipk';
};
/** The installed version of a package, or null. */
export function version(name) {
let esc = replace(name, /[.+]/g, '\\$&');
if (is_apk()) {
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
return m ? m[1] : null;
}
// Libraries carry their ABI in the name (libustream-openssl20201210).
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
for (let line in split(run('opkg list-installed').out, '\n')) {
let m = match(trim(line), re);
if (m && (found == null || m[1] == null))
found = m;
}
return found ? trim(found[2]) : null;
};
/** The version inside a package file, or null. */
export function file_version(path) {
if (match(path, /\.ipk$/)) {
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
}
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
};
/**
* Compare two package versions the way the package manager does (so -r10 is
* newer than -r9 and ~rc before the release): -1, 0 or 1; null when unknown.
*/
export function cmp(a, b) {
if (a == null || b == null)
return null;
if (a == b)
return 0;
if (is_apk()) {
let r = trim(run(`apk version -t ${q(a)} ${q(b)}`).out);
return r == '<' ? -1 : r == '>' ? 1 : r == '=' ? 0 : null;
}
if (run(`opkg compare-versions ${q(a)} '<<' ${q(b)}`).code == 0)
return -1;
if (run(`opkg compare-versions ${q(a)} '>>' ${q(b)}`).code == 0)
return 1;
return 0;
};
export function refresh(log) {
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
};
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
export function install_files(files, force, log) {
let args = join(' ', map(files, q));
return logged(is_apk()
? `apk add --allow-untrusted ${args}`
: `opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
};
/** Packages by name from the feeds. */
export function add(names, log) {
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
};
export function upgrade(names, log) {
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
};
export function remove(names, log) {
return logged(is_apk() ? `apk del ${join(' ', map(names, q))}` : `opkg remove ${join(' ', map(names, q))}`, log).code == 0;
};
/** Installed packages with a newer version in the feeds: { name: latest }. */
export function upgradable() {
let up = {};
if (is_apk()) {
for (let line in split(run('apk version -l "<"').out, '\n')) {
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
if (m)
up[m[1]] = m[3];
}
}
else
for (let line in split(run('opkg list-upgradable').out, '\n')) {
let m = match(line, /^(\S+) - (\S+) - (\S+)/);
if (m)
up[m[1]] = m[3];
}
return up;
};
@@ -0,0 +1,463 @@
// Dawnline — the personal portal.
//
// GET /<code> the app shell
// GET /<code>/assets/<file> its script, styles and fonts
// GET /<code>/api/state
// POST /<code>/api/devices { name, kind, public_key? }
// GET /<code>/api/devices/<id>/config
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
//
// The personal link is the key: every request carries its code, there are
// no sessions. Without a valid code every path answers the same bare 404 —
// the root, a person's link, the API and the assets alike — so nothing tells
// a scanner there is a portal here. Wrong codes are rate-limited per client
// (blocked clients get the same 404 even with the right code): per IPv4
// address or IPv6 /64; behind Cloudflare per visitor (CF-Connecting-IP), with
// a higher ceiling for all Cloudflare visitors together.
// Regenerating the code in LuCI locks the old link out at once. POST bodies
// must be JSON from the same origin; Referrer-Policy keeps the code out of
// other sites' logs. The portal can only manage the person's own devices
// within their limits, and not those the admin turned off (dawnline.devices).
//
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
// CGI script (www/cgi-bin/portal) is its wrapper.
import { stat, readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as schema from 'dawnline.schema';
import * as devices from 'dawnline.devices';
const RATE = `${RUN_DIR}/portal-rate.json`;
const ASSETS = '/usr/share/dawnline/portal/assets';
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2', png: 'image/png' };
const FAIL_LIMIT = 8;
const FAIL_WINDOW = 900;
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
const SHARED_LIMIT = FAIL_LIMIT * 25;
const SHARED_KEY = 'cloudflare';
// Clients remembered at most (the oldest go first).
const RATE_MAX = 2000;
const BODY_MAX = 8192;
// The early end of a request (a response was written).
const DONE = '__dawnline_done__';
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'X-Frame-Options': 'DENY',
'Cache-Control': 'no-store',
};
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
/* ---------- answering ---------- */
function headers(r, status, extra) {
let h = `Status: ${status}\r\n`;
let all = { ...SECURITY_HEADERS, ...(extra ?? {}) };
// HSTS pins the whole name: only when the visitor is on the standard port.
if (r.hsts)
all['Strict-Transport-Security'] = 'max-age=31536000';
for (let k, v in all)
h += `${k}: ${v}\r\n`;
r.io.write(h + '\r\n');
}
function finish() {
die(DONE);
}
function send_json(r, status, obj) {
headers(r, status, { 'Content-Type': 'application/json' });
r.io.write(sprintf('%J', obj));
finish();
}
function fail(r, status, msg) {
send_json(r, status, { error: msg });
}
/**
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
* Files always get the 404: a missing asset must not turn into someone's website.
*/
function not_found(r) {
let redirect = r.m.settings.portal_redirect;
let parts = split(r.path, '/');
let file = match(r.path, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
if (redirect && !file) {
headers(r, '302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
r.io.write('Moved\n');
}
else {
headers(r, '404 Not Found', { 'Content-Type': 'text/plain' });
r.io.write('Not found\n');
}
finish();
}
/** The JSON object a POST carries ({} without a body). */
function body(r) {
let len = +(r.env.CONTENT_LENGTH ?? 0);
if (len <= 0)
return {};
if (len > BODY_MAX)
fail(r, '413 Payload Too Large', 'Request too large.');
let raw = '';
while (length(raw) < len) {
let chunk = r.io.read(len - length(raw));
if (chunk == null || chunk == '')
break;
raw += chunk;
}
try {
let j = json(raw);
return type(j) == 'object' ? j : {};
}
catch (e) {
fail(r, '400 Bad Request', 'Invalid JSON.');
}
}
/** Run a change; what it refuses becomes a 400 with its message. */
function guard(r, fn) {
try {
return fn();
}
catch (e) {
if (e.message == DONE)
die(DONE);
fail(r, '400 Bad Request', e.message);
}
}
/* ---------- rate limiting ---------- */
/** The rate-limit key of an address: an IPv4 address, or the /64 of an IPv6 one. */
function addr_key(a) {
if (schema.ipv4(a))
return a;
let g = schema.ipv6_groups(a);
if (!g)
return null;
// An IPv4 address seen through an IPv6 socket.
if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff)
return sprintf('%d.%d.%d.%d', g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255);
return sprintf('%x:%x:%x:%x::/64', g[0], g[1], g[2], g[3]);
}
/**
* The buckets a request counts against, [{ key, limit }]: its client, and
* behind Cloudflare (the only proxy whose CF-Connecting-IP is believed) also
* the bucket all Cloudflare visitors share.
*/
function buckets(env) {
let peer = env.REMOTE_ADDR ?? '';
if (!cloudflare_ip(peer))
return [ { key: addr_key(peer) ?? peer, limit: FAIL_LIMIT } ];
let out = [ { key: SHARED_KEY, limit: SHARED_LIMIT } ];
let visitor = addr_key(trim(env.HTTP_CF_CONNECTING_IP ?? ''));
if (visitor && !cloudflare_ip(visitor))
unshift(out, { key: visitor, limit: FAIL_LIMIT });
return out;
}
function rate_state() {
let st = read_json(RATE, {});
let now = time();
for (let k, v in st)
if (type(v) != 'object' || now - v.first > FAIL_WINDOW)
delete st[k];
return st;
}
function rate_blocked(r) {
let st = rate_state();
return length(filter(r.buckets, (b) => (st[b.key]?.count ?? 0) >= b.limit)) > 0;
}
function rate_fail(r) {
let l = lock('portal-rate');
let st = rate_state();
let now = time();
let hit = [];
for (let b in r.buckets) {
let v = st[b.key] ?? { first: now, count: 0 };
v.count++;
st[b.key] = v;
if (v.count == b.limit)
push(hit, b.key);
}
// Bounded: an attacker with many addresses cannot grow the file without end.
let all = keys(st);
if (length(all) > RATE_MAX) {
all = sort(all, (a, b) => st[a].first - st[b].first);
for (let i = 0; i < length(all) - RATE_MAX; i++)
delete st[all[i]];
}
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
for (let k in hit)
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
}
/* ---------- pages ---------- */
/** The app shell; it reads the code from its own URL and sends it along. */
function shell(r) {
// The build's time joins the version so every update busts the hour-long asset cache.
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
let base = r.base, title = r.title;
headers(r, '200 OK', {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
});
r.io.write(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<meta name="robots" content="noindex, nofollow">
<title>${html_escape(title)}</title>
<link rel="icon" href="${base}/assets/icon.svg${v}" type="image/svg+xml">
<link rel="stylesheet" href="${base}/assets/portal.css${v}">
</head>
<body>
<div id="app" data-base="${html_escape(base)}" data-title="${html_escape(title)}"></div>
<script src="${base}/assets/portal.js${v}" defer></script>
</body>
</html>
`);
finish();
}
/** Script, styles, icon and fonts (kept outside the web root). */
function asset(r, name) {
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
if (data == null)
not_found(r);
headers(r, '200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
r.io.write(data);
finish();
}
/* ---------- the API ---------- */
/** The model again after a change. */
function reload(r) {
r.m = core.load();
r.person = r.m.people[r.person.id];
if (!r.person)
not_found(r);
}
/** Everything the page shows. */
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel.
let here = null;
for (let id, d in m.devices)
if (d.person == person.id && d.address == r.peer)
here = id;
return {
title: r.title,
person: v,
here,
server: {
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
},
can_add: length(person.devices) < person.device_limit,
kinds: core.KINDS,
// The router's day: access ends and usage days follow its clock, not the browser's.
today: today(),
version: VERSION,
};
}
/** One of the person's own devices, or a 404. */
function own_device(r, id) {
let d = r.m.devices[id];
if (!d || d.person != r.person.id)
fail(r, '404 Not Found', 'Device not found.');
return d;
}
function api_state(r) {
send_json(r, '200 OK', state(r));
}
function api_add(r) {
let b = body(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
}
function api_config(r, id) {
let d = own_device(r, id);
awg.mark_issued(r.m, d.id);
send_json(r, '200 OK', awg.client_config(r.m, d));
}
/** POST /devices/<id> { action }: what each action does; the answer carries the new state. */
const ACTIONS = {
rename: (r, d, b) => {
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
return {};
},
rotate: (r, d, b) => {
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config };
},
'delete': (r, d, b) => {
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
return {};
},
};
function api_device(r, id) {
let d = own_device(r, id);
let b = body(r);
let act = ACTIONS[b.action];
if (!act)
fail(r, '400 Bad Request', 'Unknown action.');
let res = act(r, d, b);
reload(r);
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
}
/** API routes: method, path under /<code>/api ('*' matches one segment, passed to run). */
const API = [
{ method: 'GET', path: [ 'state' ], run: api_state },
{ method: 'POST', path: [ 'devices' ], run: api_add },
{ method: 'GET', path: [ 'devices', '*', 'config' ], run: api_config },
{ method: 'POST', path: [ 'devices', '*' ], run: api_device },
];
/** The route for a request: { run, args } or null (routes take at most one '*'). */
function route(table, method, segs) {
for (let rt in table) {
if (rt.method != method || length(rt.path) != length(segs))
continue;
let args = [], ok = true;
for (let i = 0; i < length(segs) && ok; i++)
if (rt.path[i] == '*')
push(args, segs[i]);
else if (rt.path[i] != segs[i])
ok = false;
if (ok)
return { run: rt.run, args };
}
return null;
}
/* ---------- one request ---------- */
export function handle(io) {
let env = io.env ?? {};
// Header names arrive lower-case from uhttpd; CGI has only HTTP_* variables.
let hdr = {};
for (let k, v in io.headers ?? {})
hdr[lc(k)] = v;
let header = (name) => hdr[name] ?? env[`HTTP_${uc(replace(name, /-/g, '_'))}`];
let uri = env.REQUEST_URI ?? '/';
let qpos = index(uri, '?');
let path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
let https = env.HTTPS == 'on';
let host = header('host') ?? '';
let m = core.load();
let r = {
io, env, m, path, https,
method: env.REQUEST_METHOD ?? 'GET',
peer: env.REMOTE_ADDR ?? '',
buckets: buckets(env),
title: m.settings.portal_title || 'Dawnline',
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null,
base: '',
};
let segs = filter(split(path, '/'), (s) => s != '');
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
// for it); names stay HTTPS-only.
if (!https) {
let h = match(host, /^\[/) ? host : split(host, ':')[0];
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
not_found(r);
}
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
not_found(r);
let code = segs[0];
for (let id, p in m.people)
if (p.code == code)
r.person = p;
// A wrong code or a blocked client: indistinguishable from a path that does
// not exist. Only well-formed guesses count towards the limit.
if (rate_blocked(r))
not_found(r);
if (r.person == null) {
rate_fail(r);
not_found(r);
}
r.base = `/${code}`;
let rest = slice(segs, 1);
if (length(rest) == 0 && r.method == 'GET')
shell(r);
if (rest[0] == 'assets' && length(rest) == 2 && r.method == 'GET')
asset(r, rest[1]);
if (rest[0] != 'api')
not_found(r);
// CSRF: only same-origin JSON requests (a cross-site page cannot send
// application/json without CORS, and it would need the code anyway).
if (r.method == 'POST') {
let origin = header('origin');
if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) ||
(origin != null && origin != `${https ? 'https' : 'http'}://${host}`))
fail(r, '403 Forbidden', 'Cross-site request refused.');
}
else if (r.method != 'GET')
fail(r, '405 Method Not Allowed', 'Method not allowed.');
let rt = route(API, r.method, slice(rest, 1));
if (!rt)
fail(r, '404 Not Found', 'Not found.');
rt.run(r, rt.args[0]);
fail(r, '404 Not Found', 'Not found.');
};
/** Run handle() and swallow its early end. */
export function serve(io) {
try {
handle(io);
}
catch (e) {
if (e.message != DONE)
io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`);
}
};
@@ -0,0 +1,116 @@
// Dawnline — the portal's certificate (configured, ACME or self-signed) and
// the addresses its links could use.
import { lsdir } from 'fs';
import { cursor } from 'uci';
import { q, sh, sh_out, ensure_dir, file_exists, valid_host, ip2int, cloudflare_ip, DATA_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as lookup from 'dawnline.lookup';
/** The DNS names a certificate file covers. */
export function cert_names(path) {
let sans = sh_out(`openssl x509 -in ${q(path)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
return filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '');
};
/** A certificate name covers host: the same name, or a wildcard one level up. */
export function name_covers(name, host) {
if (name == host)
return true;
let dot = index(host ?? '', '.');
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
};
/** ACME certificates on the router and the names each covers. */
export function acme_certs() {
let out = [];
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
let m = match(f, /^(.+)\.fullchain\.crt$/);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
if (file_exists(k))
push(out, { cert: c, key: k, names: cert_names(c) });
}
return out;
};
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
export function acme_cert_for(host) {
for (let a in acme_certs())
for (let n in a.names)
if (name_covers(n, host))
return a;
return null;
};
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
export function portal_cert(s) {
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
if (s.portal_host) {
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
let c = `${base}.fullchain.crt`, k = `${base}.key`;
if (file_exists(c) && file_exists(k))
return { cert: c, key: k, self_signed: false };
}
// An ACME certificate issued for several names, the portal's among them.
let a = acme_cert_for(s.portal_host);
if (a)
return { cert: a.cert, key: a.key, self_signed: false };
}
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
if (!file_exists(c) || !file_exists(k)) {
ensure_dir(DATA_DIR, 0o700);
let cn = s.portal_host || 'dawnline';
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
system(`chmod 600 ${k}`);
}
return { cert: c, key: k, self_signed: true };
};
/*
* Addresses the portal could use in links, found on the router: names in ACME
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
* Each says where it points and whether a certificate covers it.
*/
export function portal_candidates(m) {
let wan = lookup.router_wan(m);
let names = [];
let add = (h) => {
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
push(names, h);
};
let certs = acme_certs();
for (let a in certs)
for (let n in a.names)
add(n);
for (let id, srv in m.servers)
add(srv.endpoint);
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (sv) => {
if (sv.enabled != '0') {
add(sv.lookup_host);
add(sv.domain);
}
});
for (let h in core.portal_hosts(m))
add(h);
let found = lookup.resolve_all(names);
let covered = (h) => length(filter(certs, (a) => length(filter(a.names, (n) => name_covers(n, h))) > 0)) > 0;
let out = [];
for (let h in names) {
let ips = found[h] ?? [];
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: covered(h) });
}
if (wan)
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
for (let ph in core.portal_hosts(m))
if (ip2int(ph) != null && ph != wan)
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
// Best first: here with a certificate, then here, then the rest.
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
return sort(out, (a, b) => score(b) - score(a));
};
@@ -0,0 +1,99 @@
// Dawnline — the plain resolver for people with Home-only access: real
// addresses from the WAN's DNS, home names from the LAN DNS. Their internet
// does not use the tunnel, so fake-IP answers would break it. dawnline.loop
// says where it runs (inside the netns while it exists, otherwise on the
// tunnel interfaces); procd runs dnsmasq through /usr/libexec/dawnline/resolver.
import { readfile, writefile, stat } from 'fs';
import { cursor } from 'uci';
import { ensure_dir, iface_status, uniq } from 'dawnline.util';
import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
/** Port on the tunnel addresses while it runs on the router itself. */
export const PORT = 5354;
export const CONF = '/var/etc/dawnline-dns.conf';
const RESOLV = '/var/etc/dawnline-dns.resolv';
const PID = '/var/run/dawnline-dns.pid';
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
function wan_dns() {
let out = [];
let snap = net.snapshot();
let wan = snap.devices[snap.wan]?.logical;
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
if (!name)
continue;
for (let a in iface_status(name)?.['dns-server'] ?? [])
if (match(a, /^[0-9.]+$/))
push(out, a);
}
return length(out) ? uniq(out) : FALLBACK_DNS;
}
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
function lan_domain(m) {
let c = cursor();
c.load('dhcp');
let d = null;
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
return uniq(filter([ d, m.settings.domain ], (x) => x));
}
/** True when the resolver process is alive. */
export function running() {
let pid = trim(readfile(PID) ?? '');
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
};
/**
* Write the config for `target` (dawnline.loop resolver_target) with home
* names from `lan` (the LAN's DNS); returns true when it changed (the running
* instance is then restarted by procd's respawn after a kill). The first line
* tells /usr/libexec/dawnline/resolver where to run it.
*/
export function sync(m, target, lan) {
ensure_dir('/var/etc');
let ifs = [];
for (let id, s in m.servers)
for (let t in core.tunnels(s))
push(ifs, t.ifname);
let lines = [
`# mode=${target.mode}`,
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
`port=${target.port}`,
'no-hosts',
'bogus-priv',
'cache-size=1000',
`pid-file=${PID}`,
'user=dnsmasq',
'group=dnsmasq',
];
if (target.mode == 'ns') {
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
// Upstream from the transit address: forwarded through the router to the WAN.
for (let a in wan_dns())
push(lines, `server=${a}@${target.address}`);
}
else {
// No tunnel yet: loopback only (without any interface= line dnsmasq would answer everywhere).
push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`);
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
if ((readfile(RESOLV) ?? '') != resolv) {
writefile(RESOLV, resolv);
system(`chmod 644 ${RESOLV}`);
}
}
if (lan)
for (let d in lan_domain(m))
push(lines, `server=/${d}/${lan}`);
let conf = join('\n', lines) + '\n';
if ((readfile(CONF) ?? '') == conf)
return false;
writefile(CONF, conf);
system(`chmod 644 ${CONF}`);
let pid = trim(readfile(PID) ?? '');
if (match(pid, /^[0-9]+$/))
system(`kill ${pid} 2>/dev/null`);
return true;
};
@@ -0,0 +1,83 @@
// Dawnline — what the rpcd method modules (dawnline.rpc.*) share: the call
// wrapper, argument helpers, the disguise check and the portal port check.
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as health from 'dawnline.health';
import * as schema from 'dawnline.schema';
/**
* An rpcd handler from fn(args): an object result is passed on, anything else
* is wrapped as { result }, and a failure becomes { error } (the UI shows it).
*/
export function wrap(fn) {
return function(req) {
try {
let r = fn(req.args ?? {});
return type(r) == 'object' ? r : { result: r };
}
catch (e) {
return { error: e.message ?? `${e}` };
}
};
};
/** An argument as a trimmed string ('' for null). */
export function str(v) {
return v == null ? '' : trim(`${v}`);
};
/** Days of history a caller may ask for: 1–400, default 30. */
export function clamp_days(v) {
let n = +(v ?? 30);
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
};
export const METHODS = [ 'off', 'standard', 'strong', 'max' ];
/** A disguise method the installed AmneziaWG can run. */
export function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
if (name == 'max' && !awg.caps().v3)
die(awg.installed()
? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.');
return name;
};
/**
* The portal's ports in the final configuration `m` (compared with `was`,
* before the change) are acceptable: its HTTPS port and, when links on IP
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
*/
export function check_portal(m, was) {
let s = m.settings;
if (!s.portal_enabled)
return;
let port = s.portal_port;
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).');
let ports = [ port ];
if (core.portal_http(m)) {
let hp = core.portal_http_port(m);
if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0)
die(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`);
push(ports, hp);
}
// Only ports the portal does not hold already: our own uhttpd is not an owner anyway.
let held = [];
if (was?.settings?.portal_enabled) {
push(held, was.settings.portal_port);
if (core.portal_http(was))
push(held, core.portal_http_port(was));
}
for (let p in ports) {
if (index(held, p) >= 0)
continue;
let owners = health.tcp_port_owners(p);
if (length(owners))
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`);
}
};
@@ -0,0 +1,214 @@
// Dawnline rpcd methods: what people reach at home — services (home
// devices and ports), circles (who reaches whom), the devices found at home,
// and "Check access".
import { readfile } from 'fs';
import { cursor } from 'uci';
import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as access from 'dawnline.access';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import { wrap, str } from 'dawnline.rpc.common';
/* ---------- services ---------- */
/** A new id from make() that no section has yet. */
function new_id(m, make) {
for (let i = 0; i < 20; i++) {
let id = make();
if (!store.id_taken(m, id))
return id;
}
die('Could not find a free id, try again.');
}
function service_set(a) {
let name = str(a.name);
if (name == '' || length(name) > 48)
die('Enter a service name.');
let address = str(a.address);
if (!schema.ipv4(address))
die('Address must be an IPv4 address.');
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != '');
for (let pt in ports)
if (!schema.valid_port(pt))
die(`Invalid port ${pt}.`);
let id = store.transact((c, m) => {
let id = str(a.id);
if (id == '')
id = new_id(m, () => `svc_${rand_int(100000, 999999)}`);
else if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
die('Invalid service id.');
// Never turn a person, device, server, circle or the settings into a service.
else if (!m.services[id] && store.id_taken(m, id))
die('That id is taken.');
c.set(core.CONFIG, id, 'service');
c.set(core.CONFIG, id, 'name', name);
c.set(core.CONFIG, id, 'address', address);
if (length(ports))
c.set(core.CONFIG, id, 'port', ports);
else
c.delete(core.CONFIG, id, 'port');
return id;
});
apply.sync();
return { id };
}
function service_delete(a) {
store.transact((c, m) => {
if (!m.services[a.id])
die('Unknown service.');
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (index(p.services, a.id) >= 0) {
let rest = filter(p.services, (x) => x != a.id);
if (length(rest))
c.set(core.CONFIG, pid, 'service', rest);
else
c.delete(core.CONFIG, pid, 'service');
}
});
apply.sync();
return { ok: true };
}
/* ---------- circles ---------- */
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
function circle_set(a) {
let name = str(a.name);
if (name == '' || length(name) > 32)
die('Enter a circle name (up to 32 characters).');
let res = store.transact((c, m) => {
let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci)
die('Unknown circle.');
let server = ci?.server ?? a.server;
if (!m.servers[server])
die('Unknown server.');
for (let id, o in m.circles)
if (id != a.id && o.server == server && lc(o.name) == lc(name))
die(`${name} already exists.`);
let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`);
let n = core.CIRCLE_COLORS;
c.set(core.CONFIG, id, 'circle');
c.set(core.CONFIG, id, 'server', server);
c.set(core.CONFIG, id, 'name', name);
c.set(core.CONFIG, id, 'color', `${((int(a.color) || 0) % n + n) % n}`);
if (type(a.members) == 'array') {
let want = {};
for (let pid in a.members)
if (m.people[pid]?.server == server)
want[pid] = true;
for (let pid, p in m.people)
if (want[pid])
c.set(core.CONFIG, pid, 'circle', id);
else if (p.circle == id)
c.delete(core.CONFIG, pid, 'circle');
}
return { id, edit: !!ci, server: m.servers[server].name };
});
apply.sync();
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
return { id: res.id, circles: values(core.load().circles) };
}
function circle_delete(a) {
let res = store.transact((c, m) => {
let ci = m.circles[a.id];
if (!ci)
die('Unknown circle.');
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (p.circle == a.id)
c.delete(core.CONFIG, pid, 'circle');
return { name: ci.name, server: m.servers[ci.server]?.name };
});
apply.sync();
admin_log('awg', 'removed', 'circle', res.name, res.server);
return { circles: values(core.load().circles) };
}
/* ---------- devices at home ---------- */
/** True while OpenWrt's mDNS daemon answers on ubus. */
function mdns_running() {
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
}
/**
* Services announced on the home networks (Bonjour), from umdns:
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
*/
function mdns_services() {
if (!mdns_running())
return [];
let r = {};
try {
r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {};
}
catch (e) {
r = {};
}
let out = [];
for (let t, insts in r)
for (let name, i in insts) {
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
if (addr)
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
}
return out;
}
/**
* Devices at home for the Home services picker: DHCP leases and static hosts
* in the server's home networks, with the services they announce (Bonjour,
* when umdns runs).
*/
function home_hosts(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
let nets = [];
for (let cidr in net.server_net(srv).nets) {
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
if (x && ip2int(x[1]) != null)
push(nets, [ ip2int(x[1]), 1 << (32 - +x[2]) ]);
}
let inside = (ip) => {
let n = ip2int(ip);
return n != null && length(filter(nets, (r) => n >= r[0] && n < r[0] + r[1])) > 0;
};
let hosts = {};
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
let f = split(line, ' ');
if (length(f) >= 4 && inside(f[2]))
hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] };
}
let c = cursor();
if (c.load('dhcp'))
c.foreach('dhcp', 'host', (h) => {
if (h.ip && inside(h.ip))
hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] };
});
for (let s in mdns_services())
if (hosts[s.address])
push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port });
else if (inside(s.address))
hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] };
return { hosts: sort(values(hosts), (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: mdns_running() };
}
export const methods = {
service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) },
service_delete: { args: { id: '' }, call: wrap(service_delete) },
circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) },
circle_delete: { args: { id: '' }, call: wrap(circle_delete) },
home_hosts: { args: { id: '' }, call: wrap(home_hosts) },
access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) },
};
@@ -0,0 +1,89 @@
// Dawnline rpcd methods: Diagnostics (Health, the service log), backups,
// export / import, and removing Dawnline.
import { slog_clear, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
import * as watchdog from 'dawnline.watchdog';
import * as upd from 'dawnline.updates';
import * as store from 'dawnline.store';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import { wrap } from 'dawnline.rpc.common';
function health_view(extra) {
return { ...(extra ?? {}), checks: health.health(), ...watchdog.view(core.load()) };
}
function service_log_clear(a) {
let removed = slog_clear(+a.older_days || 0);
if (removed)
admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`);
return { removed };
}
function backup_restore(a) {
let r = backup.backup_restore(a.name);
admin_log('dawnline', 'restored', 'backup', a.name);
return r;
}
function backup_upload(a) {
let r = backup.backup_upload(a.data);
admin_log('dawnline', 'restored', 'backup', 'from a file');
return r;
}
function export_all(a) {
let r = backup.export_json();
admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys');
return r;
}
function import_all(a) {
let r = backup.import_json(a.data);
admin_log('dawnline', 'imported', null, 'settings from a file');
return r;
}
/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */
function uninstall(a) {
if (a.confirm != 'remove')
die('Type "remove" to confirm.');
// Not in the middle of an update (opkg/apk may be installing Dawnline itself).
if (upd.busy())
die('An update is running: wait for it to finish, then remove Dawnline.');
backup.backup_create('pre-remove');
// Stop first: the agent would put back what teardown removes, and could start an automatic update.
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
apply.teardown();
store.transact((c, m) => {
let rm = [];
c.foreach(core.CONFIG, null, (s) => {
if (s['.type'] != 'settings')
push(rm, s['.name']);
});
for (let n in rm)
c.delete(core.CONFIG, n);
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, 'settings', 'portal_enabled', '0');
});
return { ok: true };
}
export const methods = {
apply: { call: wrap((a) => apply.apply()) },
health: { call: wrap((a) => health_view()) },
health_fix: { args: { id: '' }, call: wrap((a) => health_view({ result: health.fix(a.id) })) },
service_log: { call: wrap((a) => watchdog.view(core.load())) },
service_log_clear: { args: { older_days: '' }, call: wrap(service_log_clear) },
backup_list: { call: wrap((a) => ({ backups: backup.backup_list() })) },
backup_create: { call: wrap((a) => ({ name: backup.backup_create(null) })) },
backup_restore: { args: { name: '' }, call: wrap(backup_restore) },
backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: backup.backup_delete(a.name) })) },
backup_read: { args: { name: '' }, call: wrap((a) => ({ data: backup.backup_read(a.name) })) },
backup_upload: { args: { data: '' }, call: wrap(backup_upload) },
'export': { call: wrap(export_all) },
'import': { args: { data: {} }, call: wrap(import_all) },
uninstall: { args: { confirm: '' }, call: wrap(uninstall) },
};
@@ -0,0 +1,164 @@
// Dawnline rpcd methods: people (adding, editing, pausing, their personal
// links and traffic) and their devices.
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
'bonus_gb', 'hours', 'note', 'dns_mode' ];
/* ---------- people ---------- */
function person_create(a) {
let id = store.transact((c, m) => core.create_person(c, m, {
name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access,
device_limit: str(a.device_limit), expires: str(a.expires), quota_gb: str(a.quota_gb), quota_period: a.quota_period,
}));
let m = core.load();
live.add_event({ type: 'person_added', person: id, detail: m.people[id].name, by: 'admin' });
return { id, link: core.portal_url(m, m.people[id]) };
}
/** Immediate edits from the person's page; returns the person as the page shows them. */
function person_update(a) {
let fields = {};
for (let k in PERSON_FIELDS)
if (a[k] != null)
fields[k] = a[k];
if (a.paused != null)
fields.paused = a.paused;
if (type(a.services) == 'array')
fields.services = a.services;
if (a.circle != null)
fields.circle = a.circle;
if (type(a.home_nets) == 'array')
fields.home_nets = a.home_nets;
let before = store.transact((c, m) => {
let p = m.people[a.id];
core.update_person(c, m, a.id, fields);
return p;
});
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
// Access changes affect the nft sets and client AllowedIPs.
apply.sync();
let m = core.load();
let u = core.load_usage();
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access };
}
function person_pause(a) {
store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
if (a.paused)
c.set(core.CONFIG, a.id, 'paused', '1');
else
c.delete(core.CONFIG, a.id, 'paused');
});
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' });
return apply.sync();
}
/** A new personal link: the old one stops working at once (every portal request carries the code). */
function person_regen(a) {
store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
c.set(core.CONFIG, a.id, 'code', core.new_code());
});
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
let m = core.load();
return { link: core.portal_url(m, m.people[a.id]) };
}
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
function person_links(a) {
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
}
function person_delete(a) {
let name = store.transact((c, m) => {
let name = m.people[a.id]?.name;
core.delete_person(c, m, a.id);
return name;
});
live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' });
return apply.sync();
}
function person_usage(a) {
let usage = core.load_usage();
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
let days = clamp_days(a.days);
let devs = {};
for (let d in p.devices)
devs[d] = live.series([ usage.devices?.[d] ], days);
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
}
function pause_all(a) {
store.transact((c, m) => {
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, 'settings', 'paused_all', a.paused ? '1' : '0');
});
live.add_event({ type: a.paused ? 'paused_all' : 'resumed_all', by: 'admin' });
return apply.sync();
}
/* ---------- devices ---------- */
function device_create(a) {
devices.need_awg();
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
}
function device_config(a) {
let m = core.load();
let d = m.devices[a.id];
if (!d)
die('Unknown device.');
awg.mark_issued(m, d.id);
return awg.client_config(m, d);
}
function device_update(a) {
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
}
export const methods = {
person_create: {
args: { name: '', slug: '', server: '', access: '', device_limit: '', expires: '', quota_gb: '', quota_period: '' },
call: wrap(person_create),
},
person_update: {
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
call: wrap(person_update),
},
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
person_regen: { args: { id: '' }, call: wrap(person_regen) },
person_links: { args: { id: '' }, call: wrap(person_links) },
person_delete: { args: { id: '' }, call: wrap(person_delete) },
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
pause_all: { args: { paused: false }, call: wrap(pause_all) },
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
device_config: { args: { id: '' }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) },
};
@@ -0,0 +1,531 @@
// Dawnline rpcd methods: setting up a server, its General / Network /
// Interfaces settings, its disguise, and removing it.
import { cursor } from 'uci';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices';
import { wrap, str, check_method, check_portal } from 'dawnline.rpc.common';
/** Server ids that would shadow a portal path. */
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' };
/* ---------- free names, ports and subnets ---------- */
function free_port(m) {
let used = {};
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s.listen_port)
used[+s.listen_port] = true;
});
for (let id, srv in m.servers)
used[srv.port] = true;
for (let i = 0; i < 50; i++) {
let p = rand_int(40000, 60000);
if (!used[p])
return p;
}
return 51830;
}
function free_subnet(taken) {
for (let i = 0; i < 200; i++) {
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)));
let bad = false;
for (let t in taken) {
let tc = parse_cidr(t);
if (tc && cidr_overlaps(cand, tc)) {
bad = true;
break;
}
}
if (!bad)
return cidr_str(cand);
}
return '10.77.0.0/24';
}
function free_portal_port(cur) {
for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
if (!length(health.tcp_port_owners(p)) && !length(health.tcp_port_owners(p + 1)))
return p;
return 9443;
}
/** A network section name nothing uses: not the router's, not Dawnline's own links, not another server's. */
function ifname_free(m, nc, n) {
if (nc.get('network', n) != null || index(values(net.INTERNAL), n) >= 0)
return false;
for (let id, s in m.servers)
if (s.ifname == n)
return false;
return true;
}
function free_ifname(m) {
let nc = cursor();
nc.load('network');
for (let i = 0; i < 10; i++)
if (ifname_free(m, nc, `dawn${i}`))
return `dawn${i}`;
return 'dawnx';
}
function id_free(m, id) {
return !store.id_taken(m, id) && index(PORTAL_PATHS, id) < 0;
}
/** A free server id: home, then server2, server3, … (never an id anything else has). */
function free_server_id(m) {
if (id_free(m, 'home'))
return 'home';
for (let n = 2; ; n++)
if (id_free(m, `server${n}`))
return `server${n}`;
}
/** Subnets a new server must not overlap: the router's networks and the other servers. */
function taken_subnets(m) {
let taken = health.used_subnets(null);
for (let id, s in m.servers)
push(taken, s.subnet);
return taken;
}
/* ---------- setup ---------- */
function setup_defaults(a) {
let m = core.load();
let taken = taken_subnets(m);
let zones = [];
let fc = cursor();
fc.load('firewall');
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
let host = m.settings.portal_host;
if (!host) {
// Prefer a DDNS name, then an ACME certificate's, then the WAN address.
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (s) => {
if (!host && s.lookup_host && s.enabled == '1')
host = s.lookup_host;
});
if (!host)
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
if (!host)
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
}
return {
id: free_server_id(m),
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
ifname: free_ifname(m),
port: free_port(m),
subnet: free_subnet(taken),
endpoint: host,
mtu: 1380,
zones,
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1],
portal_port: free_portal_port(m.settings.portal_port),
awg: awg.caps(),
awg_state: awg.state(),
taken,
};
}
/** AmneziaWG can run a server: installed, and its kernel module loads. */
function need_awg_loaded() {
devices.need_awg();
if (awg.state().loaded)
return;
system('modprobe amneziawg >/dev/null 2>&1');
if (!awg.state().loaded)
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components.");
}
/** An MTU as typed: '' (the default) or 1280-1500. */
function check_mtu(v) {
let s = str(v);
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
die('MTU must be 1280-1500.');
return s;
}
function server_create(a) {
need_awg_loaded();
let snap = net.snapshot(true);
let router_subnets = health.used_subnets(null);
let id = store.transact((c, m) => {
let id = str(a.id) || 'home';
// A UCI section name: a dash would make uci drop it silently.
if (!match(id, /^[a-z][a-z0-9_]{0,23}$/))
die('Server ID may use lowercase letters, digits and underscores.');
if (!id_free(m, id))
die(`"${id}" is already taken.`);
let nc = cursor();
nc.load('network');
let ifname = str(a.ifname) || free_ifname(m);
if (!ifname_free(m, nc, ifname))
die(`Network interface ${ifname} already exists.`);
let port = free_port(m);
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
if (!schema.valid_port(a.port))
die('UDP port must be 1-65535.');
port = +str(a.port);
}
for (let sid, o in m.servers)
if (o.port == port)
die(`UDP ${port} is used by ${o.name}.`);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu) || '1380';
let preset = str(a.preset) || 'standard';
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
let pc = parse_cidr(srv.subnet);
if (pc)
srv.subnet = cidr_str(pc);
let taken = [ ...router_subnets ];
for (let sid, o in m.servers)
push(taken, o.subnet);
let errs = core.server_errors(m, srv, taken);
push(errs, ...awg.obf_errors(srv.obf));
if (length(errs))
die(join(' ', errs));
let set = (k, v) => c.set(core.CONFIG, id, k, v);
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server');
set('name', str(a.name) || 'Home');
set('ifname', ifname);
set('port', `${port}`);
set('subnet', srv.subnet);
if (srv.endpoint)
set('endpoint', srv.endpoint);
set('mtu', mtu);
set('keepalive', '25');
let kp = awg.server_keys();
set('private_key', kp.private_key);
set('public_key', kp.public_key);
set('preset', preset);
for (let ok, ov in srv.obf)
set(ok, ov);
set('lan_zone', str(a.lan_zone) || 'lan');
set('wan_zone', str(a.wan_zone) || 'wan');
set('auto_wan', '1');
set('auto_lan', '1');
if (snap.wan)
set('detected_wan', snap.wan);
if (snap.lan)
set('detected_lan', snap.lan);
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
set('enabled', '1');
if (a.portal_enabled != null) {
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0');
if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') {
if (!schema.valid_port(a.portal_port))
die('Portal port must be 1-65535.');
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
}
}
if (srv.endpoint && !c.get(core.CONFIG, 'settings', 'portal_host') && valid_host(srv.endpoint))
c.set(core.CONFIG, 'settings', 'portal_host', srv.endpoint);
// The portal as it will be, whatever this call changed.
check_portal(core.load(c), m);
return id;
});
let r = apply.apply();
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
let made = core.load().servers[id];
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
sh_bg('/etc/init.d/dawnline restart');
return { id, applied: r };
}
/* ---------- interfaces ---------- */
/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */
function interfaces_view(m, srv, snap) {
let sn = net.server_net(srv, snap);
let home = {};
for (let h in sn.home)
home[h.dev] = h;
let devs = [];
for (let dev, d in snap.devices)
push(devs, {
...d,
own: dev == srv.ifname,
home: !!home[dev],
auto: !!home[dev]?.auto,
});
// Saved names that no longer exist still show, so they can be removed.
for (let h in sn.home)
if (h.missing)
push(devs, { name: h.dev, category: 'other', kind: 'other', missing: true, nets: [], addrs: [], members: [], home: true, auto: h.auto });
let lan_only = 0;
for (let id, p in m.people)
if (p.server == srv.id && p.access == 'lan')
lan_only++;
return {
server: srv.id,
ifname: srv.ifname,
detected: { wan: snap.wan, lan: snap.lan },
saved: { wan: srv.detected_wan, lan: srv.detected_lan },
config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like,
device_mesh: srv.device_mesh, mesh: srv.mesh },
like_home: loop.status(),
needs: health.needs().home,
effective: sn,
zones: snap.zones,
devices: devs,
lan_only,
};
}
function interfaces_get(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
return interfaces_view(m, srv, net.snapshot(true));
}
function server_interfaces(a) {
let snap = net.snapshot(true);
let auto_wan = a.auto_wan != false && a.auto_wan != '0';
let auto_lan = a.auto_lan != false && a.auto_lan != '0';
let wan_dev = str(a.wan_device);
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
if (!auto_wan) {
if (!snap.devices[wan_dev])
die('Choose the interface that leads to the internet.');
if (!snap.devices[wan_dev].zone)
die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`);
}
let lans = [];
for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) {
d = str(d);
// Unknown names are kept only if they were saved before (interface down right now).
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
continue;
if (snap.devices[d]?.master)
die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`);
if (d == (auto_wan ? snap.wan : wan_dev))
die(`${d} is the WAN.`);
push(lans, d);
}
lans = uniq(lans);
let id = srv.id;
if (a.lan_like != null)
c.set(core.CONFIG, id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh
: a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all');
c.set(core.CONFIG, id, 'mesh', mesh);
c.delete(core.CONFIG, id, 'device_mesh');
c.set(core.CONFIG, id, 'auto_wan', auto_wan ? '1' : '0');
c.set(core.CONFIG, id, 'auto_lan', auto_lan ? '1' : '0');
if (auto_wan || wan_dev == '')
c.delete(core.CONFIG, id, 'wan_device');
else
c.set(core.CONFIG, id, 'wan_device', wan_dev);
if (length(lans))
c.set(core.CONFIG, id, 'lan_device', lans);
else
c.delete(core.CONFIG, id, 'lan_device');
// Remember what was detected, as the fallback while an interface is down.
if (snap.wan)
c.set(core.CONFIG, id, 'detected_wan', snap.wan);
if (snap.lan)
c.set(core.CONFIG, id, 'detected_lan', snap.lan);
// Keep the legacy zone options in step (older code paths, health checks).
let now = core.load(c).servers[id];
let sn = net.server_net(now, snap);
if (sn.wan.zone)
c.set(core.CONFIG, id, 'wan_zone', sn.wan.zone);
if (length(sn.zones))
c.set(core.CONFIG, id, 'lan_zone', sn.zones[0]);
return { was: srv, now: core.load(c).servers[id], mesh };
});
let srv = res.was;
// What the admin changed here: the networks, and/or whether devices reach each other.
let sig = (x) => {
let sn = net.server_net(x, snap);
return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`;
};
let what = [];
if (sig(res.now) != sig(srv))
push(what, 'home network and internet path');
if (res.mesh != srv.mesh)
push(what, MESH_WORDS[res.mesh]);
if (length(what))
admin_log('awg', 'changed', 'server', srv.name, join(', ', what));
let before = join(',', net.server_net(srv, snap).nets);
apply.apply();
let m = core.load();
let v = interfaces_view(m, m.servers[srv.id], net.snapshot(true));
v.nets_changed = before != join(',', v.effective.nets);
return v;
}
/* ---------- settings ---------- */
/** A list of DNS servers as typed (array or "a, b"): each an IPv4 or IPv6 address. */
function dns_list(v) {
let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != '');
for (let d in list)
if (!schema.ip(d))
die(`${d} is not an IP address.`);
return list;
}
/** Server settings from the General and Network tabs; applied at once. */
function server_update(a) {
let v = a.values ?? {};
if (v.device_mesh != null && v.mesh == null)
v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off';
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
if (v.name != null) {
if (str(v.name) == '')
die('Name cannot be empty.');
set('name', str(v.name));
}
if (v.endpoint != null) {
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint)))
die('Public address must be a hostname or IP address.');
set('endpoint', str(v.endpoint));
}
if (v.port != null) {
if (!schema.valid_port(v.port))
die('UDP port must be 1-65535.');
let n = +str(v.port);
for (let id, o in m.servers)
if (id != srv.id && o.port == n)
die(`UDP ${n} is used by ${o.name}.`);
set('port', `${n}`);
}
if (v.enabled != null)
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
if (v.mesh != null) {
if (index(core.MESH, v.mesh) < 0)
die('Unknown choice for devices reaching each other.');
set('mesh', v.mesh);
set('device_mesh', null);
}
if (v.mtu != null)
set('mtu', check_mtu(v.mtu));
if (v.keepalive != null) {
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600))
die('Keep-alive must be 0-600 seconds.');
set('keepalive', str(v.keepalive));
}
if (v.dns != null) {
let list = dns_list(v.dns);
if (length(list))
c.set(core.CONFIG, srv.id, 'dns', list);
else
c.delete(core.CONFIG, srv.id, 'dns');
}
return srv;
});
// For the log: what changed, in words. Turning on or off is its own line.
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
let what = [];
for (let k, label in labels) {
if (v[k] == null)
continue;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`;
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
if (trim(was) != trim(now))
push(what, label);
}
let turned = v.enabled == null ? null : (v.enabled === true || v.enabled == '1');
let name = v.name != null ? str(v.name) : srv.name;
let r = apply.apply();
if (turned != null && turned != srv.enabled)
admin_log('dawnline', turned ? 'turned on' : 'turned off', 'server', name);
if (length(what))
admin_log('dawnline', 'changed', 'server', name, join(', ', what));
if (v.mesh != null && v.mesh != srv.mesh)
admin_log('dawnline', 'changed', 'server', name, MESH_WORDS[v.mesh]);
return r;
}
function server_obfuscation(a) {
let preset = str(a.preset) || 'standard';
let o = awg.obf_preset(check_method(preset));
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
for (let k in core.OBF_KEYS)
c.delete(core.CONFIG, srv.id, k);
for (let k, v in o)
c.set(core.CONFIG, srv.id, k, v);
c.set(core.CONFIG, srv.id, 'preset', preset);
return srv;
});
let r = apply.apply();
admin_log('awg', 'changed', 'server', srv.name, `disguise: ${preset}`);
return r;
}
/** Remove a server with its people, their devices and its circles (a backup is made first). */
function server_delete(a) {
if (!core.load().servers[a.id])
die('Unknown server.');
backup.backup_create('pre-delete');
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
let gone = 0;
for (let pid, p in m.people)
if (p.server == srv.id) {
core.delete_person(c, m, pid);
gone++;
}
for (let cid, ci in m.circles)
if (ci.server == srv.id)
c.delete(core.CONFIG, cid);
c.delete(core.CONFIG, srv.id);
return { name: srv.name, gone };
});
let r = apply.apply();
admin_log('awg', 'removed', 'server', res.name, res.gone ? `with ${res.gone} ${res.gone == 1 ? 'person' : 'people'}` : null);
return r;
}
export const methods = {
setup_defaults: { call: wrap(setup_defaults) },
server_create: {
args: { id: '', name: '', ifname: '', port: 0, subnet: '', endpoint: '', mtu: 0, preset: '', lan_zone: '', wan_zone: '',
lan_like: true, portal_enabled: false, portal_port: 0 },
call: wrap(server_create),
},
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
server_interfaces: {
args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true, mesh: '' },
call: wrap(server_interfaces),
},
server_delete: { args: { id: '' }, call: wrap(server_delete) },
};
@@ -0,0 +1,150 @@
// Dawnline rpcd methods: the Settings page (the portal, defaults, logs and
// history, updates). What may be saved is dawnline.schema's.
import { stat } from 'fs';
import { q, sh_out, admin_log, RUN_DIR, DATA_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as geo from 'dawnline.geo';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as pc from 'dawnline.portalcert';
import { wrap, check_portal } from 'dawnline.rpc.common';
/** The portal's own checks from Health, shown next to its settings. */
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
function file_size(path) {
return stat(path)?.size ?? 0;
}
/** What the log and traffic history hold right now (Settings → Logs & history). */
function logs_info(m) {
let ev = live.load_events();
let by = {};
for (let cat in live.CATEGORIES)
by[cat] = 0;
for (let e in ev)
by[live.category_of(e.type)]++;
let usage = core.load_usage();
let days = {};
for (let grp in [ usage?.devices ?? {}, usage?.people ?? {} ])
for (let id, rec in grp)
for (let k in keys(rec.days ?? {}))
days[k] = true;
let dk = sort(keys(days));
return {
policy: live.policy(m.settings.retention),
events: length(ev),
oldest: length(ev) ? ev[0].ts : 0,
by_category: by,
log_ram: file_size(`${RUN_DIR}/events.json`),
log_flash: file_size(`${DATA_DIR}/events.json`),
usage_flash: file_size(`${DATA_DIR}/usage.json`),
usage_since: length(dk) ? dk[0] : '',
usage_days: length(dk),
geo_flash: file_size(`${DATA_DIR}/geo.json`),
};
}
function settings_get(a) {
let c = core.open_cursor();
let raw = c.get_all(core.CONFIG, 'settings') ?? {};
let m = core.load(c);
let out = {};
for (let k in keys(schema.SETTINGS))
out[k] = raw[k] ?? '';
out.log_category = live.policy(m.settings.retention).categories;
let cert = m.settings.portal_enabled ? pc.portal_cert(m.settings) : null;
return {
settings: out,
needs: health.needs(),
effective: m.settings,
services: values(m.services),
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null,
port_owners: m.settings.portal_enabled ? [] : health.tcp_port_owners(m.settings.portal_port),
portal_public_port: core.portal_public_port(m),
geo_cached: length(keys(geo.load().ips)),
logs: logs_info(m),
};
}
/*
* The slow part of the portal settings (DNS lookups and the Health checks),
* fetched after the page shows.
*/
function portal_info(a) {
let m = core.load();
return {
candidates: pc.portal_candidates(m),
checks: filter(health.health(m), (x) => index(PORTAL_CHECKS, x.id) >= 0),
};
}
function same(a, b) {
return (type(a) == 'array' ? join('\n', a) : a ?? '') == (type(b) == 'array' ? join('\n', b) : b ?? '');
}
/** Save settings (`values`: key → value, '' back to the default); the portal is checked as it will be. */
function settings_update(a) {
let v = a.values ?? {};
if (type(v) != 'object')
die('Nothing to save.');
let res = store.transact((c, m) => {
let restart = false;
c.set(core.CONFIG, 'settings', 'settings');
for (let k, val in v) {
if (k == 'log_category') {
let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0);
c.set(core.CONFIG, 'settings', 'log_category', length(lst) ? lst : [ '' ]);
// Superseded by the category list.
c.delete(core.CONFIG, 'settings', 'log_connections');
continue;
}
let nv = schema.validate(k, val);
if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k)))
restart = true;
if (nv == null)
c.delete(core.CONFIG, 'settings', k);
else
c.set(core.CONFIG, 'settings', k, nv);
}
check_portal(core.load(c), m);
return { restart, was: m.settings };
});
if (res.restart)
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
else
apply.sync();
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
let now = core.load().settings, was = res.was;
if (now.portal_enabled != was.portal_enabled)
admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null);
else if (now.portal_enabled) {
let what = [];
if (now.portal_port != was.portal_port)
push(what, `port ${now.portal_port}`);
if (now.portal_host != was.portal_host)
push(what, `address ${now.portal_host}`);
if (join(' ', now.portal_alt) != join(' ', was.portal_alt))
push(what, 'other addresses');
if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key)
push(what, 'certificate');
if (now.portal_redirect != was.portal_redirect)
push(what, 'redirect');
if (length(what))
admin_log('portal', 'changed', null, 'the personal portal', join(', ', what));
}
if (now.watchdog != was.watchdog)
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
return settings_get({});
}
export const methods = {
settings_get: { call: wrap(settings_get) },
portal_info: { call: wrap(portal_info) },
settings_update: { args: { values: {} }, call: wrap(settings_update) },
};
@@ -0,0 +1,239 @@
// Dawnline rpcd methods: the live revision, the Overview status (servers,
// people, totals, map, recent activity), the activity log and traffic history.
import { readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as geo from 'dawnline.geo';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import { wrap, clamp_days } from 'dawnline.rpc.common';
/** Router location plus one point per (device, recent client address). */
function geo_view(m, usage, dmp) {
if (!m.settings.geo_enabled)
return { enabled: false, home: null, points: [] };
let cache = geo.load();
let points = [];
let now = time();
for (let id, d in m.devices) {
let rec = usage.devices?.[id];
let peer = dmp.peers[d.public_key];
let cur = live.endpoint_ip(peer?.endpoint);
let online = live.online(dmp, id, peer);
for (let ip, ts in rec?.ips ?? {}) {
// Local (LAN / CGNAT) client addresses are not shown on the map.
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
if (!pl)
continue;
push(points, {
person: d.person, device: id, ip, ts,
online: online && ip == cur,
lat: pl.lat, lon: pl.lon, city: pl.city, country: pl.country, cc: pl.cc,
asn: pl.asn ?? 0, org: pl.org ?? '',
});
}
}
let h = cache.home;
return {
enabled: true,
provider: m.settings.geo_provider,
cached: length(keys(cache.ips)),
home: (h && h.lat != null) ? { lat: h.lat, lon: h.lon, city: h.city, country: h.country, cc: h.cc, asn: h.asn ?? 0, org: h.org ?? '' } : null,
points,
};
}
/** Older connections from home get the DHCP name their address has now. */
function with_hosts(ev) {
let names = null;
for (let e in ev)
if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) {
let h = net.event_hosts(e, names ??= net.lan_names());
if (h)
e.hosts = h;
}
return ev;
}
function server_view(m, srv, usage, dmp, rates, days) {
let online = 0, peers = 0;
let links = map(core.tunnels(srv), (t) => t.ifname);
let ids = {};
for (let id, d in m.devices)
ids[d.public_key] = id;
for (let k, p in dmp.peers)
if (index(links, p.ifname) >= 0) {
peers++;
if (live.online(dmp, ids[k], p))
online++;
}
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
return {
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
blocked: srv.blocked ?? null,
// Home networks (interfaces) for the per-person picker.
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
peers, online, obf: srv.obf,
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
rate: rates[srv.id] ?? [],
// Daily traffic of the people on this server (its Overview chart).
series: live.series(map(filter(keys(m.people), (pid) => m.people[pid].server == srv.id), (pid) => usage.people?.[pid]), days),
};
}
/*
* Everything the pages show at once. Readable by read-only users: no personal
* codes or links here (person_links has them).
*/
function status(a) {
let m = core.load();
let usage = core.load_usage();
let dmp = live.dump(m);
let states = view.states(m, usage);
let days = clamp_days(a.days);
let servers = [];
let rates = read_json(`${RUN_DIR}/rate.json`, {});
let prates = read_json(`${RUN_DIR}/rate_people.json`, {});
for (let id, srv in m.servers)
push(servers, server_view(m, srv, usage, dmp, rates, days));
let people = [];
for (let id, p in m.people) {
let pv = view.person_view(m, p, usage, dmp, states, { admin: true });
pv.rate = type(prates[p.id]?.[0]) == 'array' ? prates[p.id] : [];
push(people, pv);
}
people = sort(people, (a, b) => (b.online - a.online) || (b.last_seen - a.last_seen) || (a.name < b.name ? -1 : 1));
let totals = { people: length(people), devices: 0, online: 0, active: 0 };
for (let p in people) {
totals.devices += length(p.devices);
totals.online += p.online;
if (p.state == 'active')
totals.active++;
}
let recs = values(usage.people ?? {});
let day = live.series(recs, 1)[0];
totals.today = [ day.rx, day.tx ];
let mon = [ 0, 0 ];
for (let r in recs) {
let v = live.month(r);
mon[0] += v[0];
mon[1] += v[1];
}
totals.month = mon;
let events = live.load_events();
let s = m.settings;
return {
geo: geo_view(m, usage, dmp),
version: VERSION,
now: time(),
hostname: trim(readfile('/proc/sys/kernel/hostname') ?? ''),
settings: {
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
portal_public_port: core.portal_public_port(m),
paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain,
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
},
servers,
people,
services: values(m.services),
circles: values(m.circles),
totals,
series: live.series(recs, days),
events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)),
like_home: loop.status(),
awg: awg.caps(),
awg_state: awg.state(),
};
}
function events_list(a) {
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up');
let n = +a.limit || 300;
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
}
/** Remove activity by person, device, category and/or age; nothing given clears it all. */
function logs_clear(a) {
let m = core.load();
let f = {};
if (a.person) {
if (!m.people[a.person])
die('Unknown person.');
f.person = a.person;
}
if (a.device)
f.device = a.device;
if (a.category) {
if (index(live.CATEGORIES, a.category) < 0)
die('Unknown category.');
f.category = a.category;
}
if (a.older_days) {
if (!match(a.older_days, /^[1-9][0-9]{0,3}$/))
die('Older than must be a number of days.');
f.before = time() - +a.older_days * 86400;
}
let removed = live.clear_events(f);
if (removed)
admin_log('dawnline', 'cleared', null, 'the activity log',
join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null,
a.older_days ? `older than ${a.older_days} days` : null ], (x) => x)));
return { ok: true, removed };
}
/**
* Reset traffic history (all | person | device). The agent owns the live
* counters, so it gets a marker; the tmpfs copy is edited too so the UI
* shows the result straight away.
*/
function usage_clear(a) {
let m = core.load();
if (index([ 'all', 'person', 'device' ], a.scope) < 0)
die('Unknown scope.');
if (a.scope == 'person' && !m.people[a.id])
die('Unknown person.');
if (a.scope == 'device' && !m.devices[a.id])
die('Unknown device.');
let req = { scope: a.scope, id: a.id, ts: time() };
ensure_dir(RUN_DIR);
let l = lock('usage-reset');
let pending = read_json(`${RUN_DIR}/usage.reset`, []);
push(pending, req);
write_json(`${RUN_DIR}/usage.reset`, pending, 0o600);
unlock(l);
let usage = core.load_usage();
if (usage) {
live.reset_usage(usage, m, a.scope, a.id);
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
}
admin_log('dawnline', 'reset traffic history', null,
a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`);
return { ok: true };
}
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
function rev() {
return { rev: +(live.presence()?.rev ?? 0) };
}
export const methods = {
rev: { call: wrap(rev) },
status: { args: { days: 30 }, call: wrap(status) },
events: { args: { limit: 300 }, call: wrap(events_list) },
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
};
@@ -0,0 +1,139 @@
// Dawnline rpcd methods for the Components tab: status, starting update jobs
// (the updater does the work in the background), releases, release notes
// and the changes between two releases. luci.dawnline merges `methods`.
import { readfile } from 'fs';
import { cursor } from 'uci';
import { read_json, ensure_dir, VERSION, REPO, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as health from 'dawnline.health';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as builds from 'dawnline.awg_builds';
import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs';
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback]
// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages)
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
function wrap(fn) {
return function(req) {
try {
let r = fn(req.args ?? {});
return type(r) == 'object' ? r : { result: r };
}
catch (e) {
return { error: e.message ?? `${e}` };
}
};
}
/** AmneziaWG interfaces by name: switching builds restarts them. */
function awg_tunnels() {
let out = [];
let c = cursor();
c.load('network');
c.foreach('network', 'interface', (s) => {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(out, s._dawnline_name ?? s['.name']);
});
return out;
}
function status(a) {
let m = core.load();
let rel = {};
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
if (x)
rel[lc(x[1])] = x[2];
}
return {
version: VERSION,
firmware: { version: rel.release ?? '', target: rel.target ?? '', arch: rel.arch ?? '' },
portal: m.settings.portal_enabled,
home: length(filter(values(m.servers), (x) => x.lan_like)) > 0,
needs: health.needs(),
check: read_json(upd.CHECK_FILE, null),
job: upd.job(),
now: time(),
repo: REPO,
policy: m.settings.updates,
auto: upd.auto_state(),
kept: upd.kept_all(builds.firmware()?.postfix),
history: slice(upd.history(), 0, 12),
tunnels: awg_tunnels(),
};
}
/** Releases for the Versions list (Dawnline), five per page. */
function releases(a) {
let page = +(a.page ?? 1);
if (page != int(page) || page < 1 || page > 50)
die('Unknown page.');
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
}
/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */
function notes(a) {
let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO;
let tag = a.tag ?? '';
if (!rp || !match(tag, TAG))
die('Unknown release.');
let r = gh.release(rp, tag);
if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v')
r = gh.release(rp, `v${tag}`);
if (!r)
die(`No release ${tag} in ${rp}.`);
return { ...r, digests: null, repo: rp };
}
/** What changed between the installed Dawnline and a release (points for the Components tab). */
function changes(a) {
let to = a.to ?? '', from = a.from ?? '';
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
die('Unknown release.');
// The installed version as a tag when it was released (a build ahead of the releases has none).
let base = null;
for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : []))
if (!base && gh.release(REPO, t))
base = t;
return { items: gh.changes(REPO, base, to) };
}
/**
* Start an update job. Returns the new job once its worker has written it,
* else null (the caller follows updates_status); never an older job.
*/
function run(a) {
let what = a.what ?? 'check';
if (length(what) > 400 || !match(what, TARGET))
die('Unknown update target.');
// Checked here too, so a wrong name never becomes a failed job in the history.
if (substr(what, 0, 5) == 'pkgs:')
for (let n in split(substr(what, 5), ','))
if (index(PKG_NAMES, n) < 0)
die(n == '' ? 'Unknown update target.' : `${n} is not a package Dawnline manages.`);
if (upd.busy())
die('Another component action is already running.');
ensure_dir(RUN_DIR);
let t0 = time();
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
for (let i = 0; i < 20; i++) {
let j = read_json(upd.JOB_FILE, null);
if (j?.state == 'running' && j.started >= t0)
return { started: true, job: j };
system('usleep 100000 2>/dev/null || sleep 1');
}
return { started: true, job: null };
}
export const methods = {
updates_status: { call: wrap(status) },
updates_run: { args: { what: '' }, call: wrap(run) },
updates_releases: { args: { page: 1 }, call: wrap(releases) },
updates_notes: { args: { component: '', tag: '', build: '' }, call: wrap(notes) },
updates_changes: { args: { from: '', to: '' }, call: wrap(changes) },
};
@@ -0,0 +1,254 @@
// Dawnline — what the settings section may hold: one entry per option with
// its type, default and range, used to validate what the admin saves and to
// parse what is stored. Also the address checks the rest of the code shares.
//
// Booleans are stored as '1' / '0' only, and parsed the way the init script's
// config_get_bool does, so the service and the code never disagree.
import { stat } from 'fs';
import { ip2int, valid_host } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates';
/* ---------- addresses ---------- */
/** An IPv4 address in dotted form. */
export function ipv4(s) {
return type(s) == 'string' && ip2int(s) != null;
};
/**
* An IPv6 address → its eight 16-bit groups, or null. Accepts '::' and an
* embedded IPv4 at the end (::ffff:192.0.2.1); no zone ids or prefixes.
*/
export function ipv6_groups(s) {
if (type(s) != 'string' || length(s) < 2 || length(s) > 45 || !match(s, /^[0-9A-Fa-f:.]+$/))
return null;
let tail = [];
let v4 = match(s, /^(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/);
if (v4) {
let n = ip2int(v4[2]);
if (n == null)
return null;
tail = [ (n >> 16) & 0xffff, n & 0xffff ];
s = substr(v4[1], -2) == '::' ? v4[1] : substr(v4[1], 0, length(v4[1]) - 1);
}
else if (index(s, '.') >= 0)
return null;
let halves = split(s, '::');
if (length(halves) > 2)
return null;
let groups = (part) => {
let out = [];
if (part == '')
return out;
for (let g in split(part, ':')) {
if (!match(g, /^[0-9A-Fa-f]{1,4}$/))
return null;
push(out, hex(g));
}
return out;
};
let head = groups(halves[0]);
let rest = length(halves) == 2 ? groups(halves[1]) : [];
if (head == null || rest == null)
return null;
if (length(halves) == 1) {
push(head, ...tail);
return length(head) == 8 ? head : null;
}
push(rest, ...tail);
let gap = 8 - length(head) - length(rest);
if (gap < 1)
return null;
let out = [ ...head ];
for (let i = 0; i < gap; i++)
push(out, 0);
push(out, ...rest);
return out;
};
/** An IPv6 address (any valid notation). */
export function ipv6(s) {
return ipv6_groups(s) != null;
};
/** An IPv4 or IPv6 address. */
export function ip(s) {
return ipv4(s) || ipv6(s);
};
/** A TCP/UDP port as typed: 1-5 digits, 1-65535. */
export function valid_port(v) {
let s = trim(`${v ?? ''}`);
return match(s, /^[0-9]{1,5}$/) != null && +s >= 1 && +s <= 65535;
};
/* ---------- parsing stored values ---------- */
/** A stored boolean, as the init script's config_get_bool reads it. */
export function bool(v, dflt) {
v = lc(trim(`${v ?? ''}`));
if (index([ '1', 'on', 'true', 'yes', 'enabled' ], v) >= 0)
return true;
if (index([ '0', 'off', 'false', 'no', 'disabled' ], v) >= 0)
return false;
return dflt;
};
/** A stored whole number within [min, max], else the default. */
export function to_int(v, dflt, lo, hi) {
let s = trim(`${v ?? ''}`);
if (!match(s, /^-?[0-9]{1,9}$/))
return dflt;
let n = +s;
return (lo != null && n < lo) || (hi != null && n > hi) ? dflt : n;
};
/* ---------- the settings section ---------- */
/*
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
* min/max: ints and text length; values: enums; msg: the error for a bad value.
*/
export const SETTINGS = {
portal_enabled: { type: 'bool', dflt: false, restart: true },
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
portal_alt: { type: 'hosts', dflt: [], restart: true },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
portal_cert: { type: 'file', dflt: '', restart: true },
portal_key: { type: 'file', dflt: '', restart: true },
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' },
hostnames: { type: 'bool', dflt: true },
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
geo_enabled: { type: 'bool', dflt: true },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
log_connections: { type: 'bool', dflt: true },
watchdog: { type: 'bool', dflt: true },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, msg: 'Keep activity for 0 (no age limit) to 9999 days.' },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' },
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' },
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' },
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' },
// Empty means "no fallback" (stored as 'none'); unset means the default.
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' },
update_check: { type: 'bool', dflt: true },
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS), msg: 'Check every 6h, 12h, 1d or 7d.' },
update_auto: { type: 'bool', dflt: true },
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' },
update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' },
update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] },
update_keep: { type: 'bool', dflt: false },
update_mirrors: { type: 'bool', dflt: true },
};
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */
export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
function bad(spec, key) {
die(spec.msg ?? `Invalid value for ${key}.`);
}
/**
* Check a value the admin saves for setting `key`. Returns what to store: a
* string, a list, or null to remove the option (back to the default). Dies
* with a message for the admin when the value is not acceptable.
*/
export function validate(key, val) {
let spec = SETTINGS[key];
if (!spec)
die(`Unknown setting ${key}.`);
let t = spec.type;
if (t == 'hosts') {
let lst = [];
for (let x in (type(val) == 'array' ? val : []))
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0)
push(lst, trim(x));
return length(lst) ? lst : null;
}
if (t == 'targets') {
let lst = [];
for (let x in (type(val) == 'array' ? val : []))
if (index(TARGETS, x) >= 0 && index(lst, x) < 0)
push(lst, x);
// An empty list is a choice too ("none"), unlike a missing option (the default).
return length(lst) ? lst : [ 'none' ];
}
if (type(val) == 'bool')
val = val ? '1' : '0';
val = trim(`${val ?? ''}`);
if (t == 'ipv4' && val == '')
return 'none';
if (val == '')
return null;
if (t == 'bool') {
if (val != '0' && val != '1')
die(`${key} is 0 or 1.`);
}
else if (t == 'int') {
if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max)
bad(spec, key);
val = `${+val}`;
}
else if (t == 'enum') {
if (index(spec.values, val) < 0)
bad(spec, key);
}
else if (t == 'host') {
if (!valid_host(val))
bad(spec, key);
}
else if (t == 'url') {
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
bad(spec, key);
}
else if (t == 'file') {
if (substr(val, 0, 1) != '/' || !stat(val))
die(`${val} does not exist.`);
}
else if (t == 'domain') {
if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
bad(spec, key);
}
else if (t == 'ipv4') {
if (!ipv4(val))
bad(spec, key);
}
else if (t == 'time') {
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
bad(spec, key);
}
else if (t == 'text') {
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
bad(spec, key);
}
return val;
};
/**
* A stored setting parsed by its schema entry: the typed value, or the default
* when it is missing or invalid. For dawnline.core's load().
*/
export function get(raw, key) {
let spec = SETTINGS[key];
let v = raw?.[key];
if (!spec)
return v;
let t = spec.type;
if (t == 'bool')
return bool(v, spec.dflt);
if (t == 'int')
return to_int(v, spec.dflt, spec.min, spec.max);
if (t == 'hosts' || t == 'targets')
return v == null ? spec.dflt : filter(type(v) == 'array' ? v : [ v ], (x) => x != '');
if (v == null || v == '')
return spec.dflt;
if (t == 'enum')
return index(spec.values, v) >= 0 ? v : spec.dflt;
if (t == 'ipv4')
return v == 'none' ? '' : (ipv4(v) ? v : spec.dflt);
return v;
};
@@ -0,0 +1,43 @@
// Dawnline — changes to /etc/config/dawnline, the one way: under the config
// lock, against a model loaded inside that lock, committed with the file kept
// private. rpcd, the portal, the CLI and the agent all go through here, so
// no change is made on a stale model and none is lost to another writer.
import { lock, unlock } from 'dawnline.util';
import * as core from 'dawnline.core';
/** Section names that are never ids of people, devices, servers, services or circles. */
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
/** Commit the dawnline config and keep it readable by root only. */
export function commit(c) {
c.commit(core.CONFIG);
system('chmod 600 /etc/config/dawnline');
};
/**
* Run fn(c, m) with the config lock held, on a fresh cursor and model; commit
* when fn returns (the return value is passed on). Anything fn throws aborts
* without committing and is rethrown with the same message.
*/
export function transact(fn) {
let l = lock('config');
try {
let c = core.open_cursor();
let m = core.load(c);
let r = fn(c, m);
commit(c);
unlock(l);
return r;
}
catch (e) {
unlock(l);
die(e.message ?? `${e}`);
}
};
/** Is `id` used by anything in the model (any kind of section), or reserved? */
export function id_taken(m, id) {
return index(RESERVED_IDS, id) >= 0 || m.servers?.[id] != null || m.people?.[id] != null || m.devices?.[id] != null ||
m.services?.[id] != null || m.circles?.[id] != null;
};
@@ -0,0 +1,135 @@
// Dawnline updater: Dawnline itself — check the latest release, install a
// release (latest, a tag, the same one again) or the kept previous version.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { readfile } from 'fs';
import { VERSION, REPO } from 'dawnline.util';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg';
function status(installed, latest) {
let c = upd.version_cmp(installed, latest);
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
}
export function check(ctx) {
let r = gh.latest(REPO);
if (!r)
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` };
let latest = replace(r.tag, /^v/, '');
let st = status(VERSION, latest);
ctx.log(st == 'outdated' ? `Dawnline update is available: ${VERSION} → ${latest}`
: st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}`
: `Dawnline is up to date (${VERSION})`);
return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st };
};
/**
* The sha256 a release publishes for a file: GitHub's own (API), else the
* release's sha256sums.txt fetched straight from github.com (never a mirror).
*/
function want_sha(ctx, tag, asset, dir) {
let want = gh.asset_sha256(REPO, tag, asset);
if (want)
return want;
let sums = `${dir}/sha256sums-${replace(tag, /[^A-Za-z0-9.-]/g, '_')}.txt`;
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/sha256sums.txt`, sums, { mirrors: false, log: ctx.log }))
return null;
for (let line in split(readfile(sums) ?? '', '\n')) {
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
if (m && m[2] == asset)
return m[1];
}
return null;
}
/** Download a release's package, verified against its sha256. */
function fetch(ctx, tag, dir) {
let ver = replace(tag, /^v/, '');
let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`;
ctx.phase(`Downloading ${asset}`);
let want = want_sha(ctx, tag, asset, dir);
if (!want)
die(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`);
let f = `${dir}/${asset}`;
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }))
die(`Download failed: ${asset}`);
ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`);
return f;
}
/** The release tag of a version: tags may or may not carry the v. */
function tag_of(ver) {
for (let t in [ `v${ver}`, ver ]) {
try {
if (gh.release(REPO, t))
return t;
}
catch (e) {}
}
return `v${ver}`;
}
function backup(ctx) {
ctx.phase('Backing up configuration');
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
}
/** arg: null (latest) | @<tag> | reinstall | rollback */
export function install(ctx, arg) {
let out = { from: VERSION, to: null };
if (arg == 'rollback') {
let k = upd.kept('app');
if (!k)
die('No previous Dawnline version is kept on the router');
out.to = k.version;
ctx.versions(VERSION, k.version);
backup(ctx);
ctx.phase(`Rolling back to ${k.version}`);
if (!pkg.install_files(k.files, true, ctx.log))
die('Installation failed');
upd.forget('app');
ctx.after('app');
return out;
}
let tag, force = false;
if (arg == 'reinstall') {
tag = tag_of(VERSION);
force = true;
}
else if (arg && substr(arg, 0, 1) == '@') {
tag = substr(arg, 1);
force = upd.version_cmp(replace(tag, /^v/, ''), VERSION) <= 0;
}
else {
let c = check(ctx);
if (!c.latest)
die(c.note);
if (!c.update) {
out.to = VERSION;
return out;
}
tag = c.tag;
}
out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps no package files).
if (ctx.pol.keep && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
try {
system(`mkdir -p '${ctx.work}/keep'`);
upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]);
}
catch (e) {
ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`);
}
}
backup(ctx);
ctx.phase('Installing package');
if (!pkg.install_files([ f ], force, ctx.log))
die('Installation failed');
ctx.after('app');
return out;
};
@@ -0,0 +1,231 @@
// Dawnline updater: AmneziaWG — the builds published for this firmware by
// each source, installing or switching a build (verified against GitHub's
// sha256), the Russian LuCI translation, and rolling back to a kept build.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { stat } from 'fs';
import { cursor } from 'uci';
import { iface_intent } from 'dawnline.util';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
function sh(cmd) {
return system(`${cmd} >/dev/null 2>&1`);
}
/**
* Download one package of a build to dir, verified when GitHub publishes its
* sha256 (then mirrors may serve it); without a sha256 only github.com itself.
* Returns the path or null.
*/
function fetch(ctx, fw, name, src, dir) {
let file = builds.asset(fw, name);
let dest = `${dir}/${src}_${file}`;
let want = gh.asset_sha256(builds.SOURCES[src].repo, fw.tag, file);
let url = `https://github.com/${builds.SOURCES[src].repo}/releases/download/${fw.tag}/${file}`;
return gh.download(url, dest, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }) ? dest : null;
}
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
function newer_series_tag(rp, tag) {
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
let best = null;
try {
for (let x in gh.releases(rp, 1)) {
let t = x.tag;
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && pkg.cmp(substr(t, 1), substr(tag, 1)) > 0 &&
(!best || pkg.cmp(substr(t, 1), substr(best, 1)) > 0))
best = t;
}
}
catch (e) {}
return best;
}
export function check(ctx) {
let installed = builds.installed();
let ru = pkg.version(builds.RU) != null;
let cur = installed['amneziawg-tools'];
let fw = builds.firmware();
if (!fw)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'Cannot detect the firmware target' };
let dir = `${ctx.work}/check`;
system(`mkdir -p '${dir}'`);
let sources = {};
for (let id in builds.ORDER) {
let src = builds.SOURCES[id];
ctx.log(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`);
let f = fetch(ctx, fw, 'amneziawg-tools', id, dir);
let v = f ? pkg.file_version(f) : null;
let date = null;
try {
date = f ? gh.release(src.repo, fw.tag)?.published : null;
}
catch (e) {}
let s = { label: src.label, repo: src.repo, tag: fw.tag, version: v, gen: builds.gen(v), date };
// A newer firmware may already get 3.1 from this source.
if (s.gen != '3.1') {
let nt = newer_series_tag(src.repo, fw.tag);
if (nt) {
let nf = fetch(ctx, builds.for_tag(fw, nt), 'amneziawg-tools', id, dir);
if (builds.gen(nf ? pkg.file_version(nf) : null) == '3.1')
s.newer = { tag: nt, gen: '3.1' };
}
}
sources[id] = s;
}
// The installed build: the source whose package matches. Unknown stays unknown
// (an automatic update never switches a build it could not identify).
let current = null;
for (let id, x in sources)
if (!current && cur && x.version == cur)
current = id;
let mine = current ? sources[current] : null;
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
ctx.log(cur == null ? 'AmneziaWG is not installed'
: !current ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more`
: st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}`
: `AmneziaWG is up to date (${cur})`);
return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources,
latest: mine?.version ?? null, status: st,
update: cur == null || st == 'outdated',
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null };
};
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
function reload_module(ctx, before, after) {
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
return;
let ifaces = [];
let c = cursor();
c.load('network');
c.foreach('network', 'interface', (s) => {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']);
});
ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
for (let i in ifaces) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`);
}
sh('rmmod amneziawg');
ctx.run('modprobe amneziawg');
for (let i in ifaces)
sh(`ifup '${i}'`);
}
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
ctx.phase('Loading the kernel module');
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
die("AmneziaWG is installed, but its kernel module doesn't load on this firmware");
}
else
reload_module(ctx, before, after);
// netifd reads its protocol handlers when it starts.
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
ctx.phase('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)');
ctx.run('/etc/init.d/network restart');
}
ctx.after('apply');
}
/** The first source that publishes every package for this firmware. */
function pick(fw) {
for (let id in builds.ORDER) {
let r = null;
try {
r = gh.release(builds.SOURCES[id].repo, fw.tag);
}
catch (e) {}
if (r && length(filter(builds.PKGS, (p) => index(r.assets, builds.asset(fw, p)) >= 0)) == length(builds.PKGS))
return id;
}
return null;
}
/** arg: [auto|slava|grey][:ru] | rollback */
export function install(ctx, arg) {
let before = builds.installed();
let out = { from: before['amneziawg-tools'], to: null, before };
let fw = builds.firmware();
if (!fw)
die('Cannot detect the firmware target');
if (arg == 'rollback') {
let k = upd.kept('amneziawg');
if (!k)
die('No previous AmneziaWG build is kept on the router');
if (k.firmware && k.firmware != fw.postfix)
die('The kept AmneziaWG build was made for another firmware: it would not load on this one');
out.to = k.version;
out.build = k.build;
ctx.versions(out.from, out.to);
ctx.phase(`Rolling back to ${k.version}`);
if (!pkg.install_files(k.files, true, ctx.log))
die('Package installation failed');
upd.forget('amneziawg');
out.after = builds.installed();
settle(ctx, before, out.after);
return out;
}
let parts = split(arg ?? '', ':');
let id = parts[0] || 'auto';
let want_ru = parts[1] == 'ru';
if (id == 'auto') {
id = pick(fw);
if (!id)
die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`);
}
let src = builds.SOURCES[id];
if (!src)
die(`Unknown AmneziaWG build ${id}`);
out.build = id;
let files = [];
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
ctx.phase(`Downloading ${p} from ${src.repo}`);
let f = fetch(ctx, fw, p, id, ctx.work);
if (!f)
die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`);
push(files, f);
}
out.to = pkg.file_version(files[1]);
ctx.versions(out.from, out.to);
// The build being replaced, for Roll back: from another source that still publishes it.
if (ctx.pol.keep && out.from && out.to != out.from) {
let dir = `${ctx.work}/keep`;
system(`mkdir -p '${dir}'`);
let kept = null;
for (let sid in builds.ORDER) {
if (sid == id || kept)
continue;
let f = fetch(ctx, fw, 'amneziawg-tools', sid, dir);
if (f && pkg.file_version(f) == out.from)
kept = sid;
}
if (kept) {
ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`);
let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x);
if (length(keepf) == length(builds.PKGS))
upd.keep('amneziawg', out.from, keepf, kept, fw.postfix);
}
else
ctx.log('Warning: the installed build is no longer published, nothing to keep for rollback');
}
ctx.phase('Refreshing package lists');
pkg.refresh(ctx.log);
ctx.phase(`Installing the ${src.label} build`);
if (!pkg.install_files(files, true, ctx.log))
die('Package installation failed');
if (!want_ru && pkg.version(builds.RU))
pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed();
settle(ctx, before, out.after);
return out;
};
@@ -0,0 +1,92 @@
// Dawnline updater: the OpenWrt packages Dawnline adds — the home-like link
// (ip-full, kmod-veth) and HTTPS plus certificates for the personal portal —
// checked against and updated from the OpenWrt feeds.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import * as pkg from 'dawnline.pkg';
/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */
export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
// half old and half new.
const FAMILY = [
[ /^ip-full$/, /^ip-/ ],
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
[ /^(acme|luci-app-acme$)/, /^acme/ ],
];
function family(p) {
for (let f in FAMILY)
if (match(p, f[0]))
return f[1];
return null;
}
/** The packages to update for these names: each one plus its upgradable family. */
function with_family(names, up) {
let set = {};
for (let n in names) {
if (up[n])
set[n] = true;
let f = family(n);
if (f)
for (let u in keys(up))
if (match(u, f))
set[u] = true;
}
return sort(keys(set));
}
/** refresh: update the package lists first (a check by hand or on schedule). */
export function check(ctx, refresh) {
if (refresh ?? true) {
ctx.phase('Refreshing package lists');
pkg.refresh();
}
let up = pkg.upgradable();
let res = {}, all = {};
for (let p in NAMES) {
let v = pkg.version(p);
let set = v ? with_family([ p ], up) : [];
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
for (let x in set)
all[x] = true;
}
let n = length(keys(all));
ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date');
return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' };
};
/** arg: name,name,… (only names Dawnline manages): missing ones are installed, present ones updated with their family. */
export function install(ctx, arg) {
let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names)
if (index(NAMES, n) < 0)
die(`${n} is not a package Dawnline manages`);
if (!length(names))
die('Nothing to install');
ctx.phase('Refreshing package lists');
pkg.refresh(ctx.log);
let missing = filter(names, (n) => pkg.version(n) == null);
let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable());
if (length(have)) {
ctx.phase(`Updating ${join(', ', have)}`);
if (!pkg.upgrade(have, ctx.log))
die('Update failed');
}
if (length(missing)) {
ctx.phase(`Installing ${join(', ', missing)}`);
if (!pkg.add(missing, ctx.log))
die('Installation failed');
}
// The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start.
let touched = [ ...missing, ...have ];
if (length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/)))) {
ctx.after('apply');
ctx.after('uhttpd');
}
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
ctx.after('uhttpd');
return { updated: have, installed: missing, check: check(ctx, false) };
};
@@ -0,0 +1,228 @@
// Dawnline — what the Components tab, the updater and the agent share: the
// update policy (Settings → Updates), when an automatic run is due, the one
// update job at a time (a kernel lock), the history for Activity, and the
// versions kept for rollback. GitHub and the package manager live in
// dawnline.github and dawnline.pkg.
import { open, stat } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util';
export const JOB_FILE = `${RUN_DIR}/update-job.json`;
export const CHECK_FILE = `${RUN_DIR}/update-check.json`;
/** Held (flock) by the updater for the whole job: busy() and stale jobs come from it, not from pids. */
export const LOCK_FILE = `${RUN_DIR}/update.lock`;
/** Automatic runs: when the last check and the last scheduled install happened. */
export const AUTO_FILE = `${DATA_DIR}/update-auto.json`;
/** What happened: updates (by hand or automatic), failures, checks that found something. */
export const HISTORY_FILE = `${DATA_DIR}/update-history.json`;
/** The version each component had before its last update (Keep the previous version). */
export const KEEP_DIR = `${DATA_DIR}/keep`;
export const INTERVALS = { '6h': 6 * 3600, '12h': 12 * 3600, '1d': 86400, '7d': 7 * 86400 };
export const TARGETS = [ 'app', 'amneziawg', 'packages' ];
function on(v, dflt) {
if (v == null || v == '')
return dflt;
return v == '1' || v == 'true' || v == 'on' || v == 'yes';
}
/** The update policy from raw UCI settings (core.load puts it in m.settings.updates). */
export function policy(s) {
s ??= {};
let t = type(s.update_targets) == 'array' ? s.update_targets : s.update_targets ? [ s.update_targets ] : null;
let time_ok = match(s.update_time ?? '', /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/);
return {
check: on(s.update_check, true),
interval: INTERVALS[s.update_interval] ? s.update_interval : '1d',
auto: on(s.update_auto, true),
mode: s.update_mode == 'immediate' ? 'immediate' : 'scheduled',
time: time_ok ? s.update_time : '04:00',
// AmneziaWG is left out by default: a new kernel module restarts every tunnel.
targets: t ? filter(t, (x) => index(TARGETS, x) >= 0) : [ 'app', 'packages' ],
keep: on(s.update_keep, false),
mirrors: on(s.update_mirrors, true),
};
};
/* ---------- schedule ---------- */
/** The scheduled time on the day of `ts` (router local time), in seconds since the epoch. */
function scheduled_on(pol, ts) {
let t = localtime(ts);
let hm = split(pol.time, ':');
return ts - (t.hour * 3600 + t.min * 60 + t.sec) + int(hm[0]) * 3600 + int(hm[1]) * 60;
}
function day_of(ts) {
let t = localtime(ts);
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
}
/** The scheduled slot `now` is in (up to an hour after the set time, also across midnight), or null. */
function slot(pol, now) {
for (let at in [ scheduled_on(pol, now), scheduled_on(pol, now - 86400) ])
if (now >= at && now - at < 3600)
return at;
return null;
}
/**
* What an automatic run should do now: 'install' (the scheduled window, at
* most an hour after the set time, once per slot), 'check' (the interval has
* passed), or null.
*/
export function due(pol, st, now) {
now ??= time();
st ??= {};
if (pol.auto && pol.mode == 'scheduled' && length(pol.targets)) {
let at = slot(pol, now);
if (at != null && st.install_day != day_of(at))
return 'install';
}
if (pol.check && now - (st.check ?? 0) >= INTERVALS[pol.interval])
return 'check';
return null;
};
export function auto_state() {
return read_json(AUTO_FILE, {});
};
export function auto_save(st) {
ensure_dir(DATA_DIR);
write_json(AUTO_FILE, st, 0o600);
};
/** Record that the scheduled slot `now` is in has run (the slot's own day, not today's after midnight). */
export function mark_day(pol, st, now) {
now ??= time();
st.install_day = day_of(slot(pol, now) ?? now);
return st;
};
/* ---------- one job at a time ---------- */
/**
* Take the update lock without waiting: the open file (keep it for the whole
* job; the kernel releases it when the process ends), or null when another
* job holds it.
*/
export function try_lock() {
ensure_dir(RUN_DIR);
let f = open(LOCK_FILE, 'a');
if (f && f.lock('xn'))
return f;
f?.close();
return null;
};
/** A job is running: someone holds the update lock. */
export function busy() {
let f = try_lock();
if (!f)
return true;
f.close();
return false;
};
/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */
export function job() {
let j = read_json(JOB_FILE, null);
if (j?.state == 'running' && !busy()) {
j.state = 'failed';
j.error = 'The update stopped unexpectedly.';
j.finished = j.finished ?? time();
}
return j;
};
/* ---------- history (Components → Activity) ---------- */
export function history() {
let h = read_json(HISTORY_FILE, []);
return type(h) == 'array' ? h : [];
};
/** Newest first, the last 30 kept on flash. */
export function history_add(e) {
let h = history();
unshift(h, { ts: time(), ...e });
ensure_dir(DATA_DIR);
write_json(HISTORY_FILE, slice(h, 0, 30), 0o600);
};
/* ---------- Dawnline versions ---------- */
/**
* Compare Dawnline release versions (0.3.2, v0.4.0-rc1): -1, 0 or 1. Numbers
* compare as numbers; a pre-release (-rc1, -beta) comes before its release.
*/
export function version_cmp(a, b) {
let parse = (v) => {
let m = match(replace(`${v}`, /^v/, ''), /^([0-9.]+)([-~]([0-9A-Za-z.]+))?/);
return m ? { nums: map(split(m[1], '.'), (x) => int(x)), pre: m[3] } : { nums: [ 0 ], pre: `${v}` };
};
let x = parse(a), y = parse(b);
for (let i = 0; i < length(x.nums) || i < length(y.nums); i++) {
let p = x.nums[i] ?? 0, r = y.nums[i] ?? 0;
if (p != r)
return p < r ? -1 : 1;
}
if (x.pre == y.pre)
return 0;
if (x.pre == null)
return 1;
if (y.pre == null)
return -1;
// rc1 < rc2 < rc10: compare the number runs as numbers.
let px = match(x.pre, /^([^0-9]*)([0-9]*)/), py = match(y.pre, /^([^0-9]*)([0-9]*)/);
if (px[1] != py[1])
return px[1] < py[1] ? -1 : 1;
return int(px[2] || 0) < int(py[2] || 0) ? -1 : int(px[2] || 0) > int(py[2] || 0) ? 1 : 0;
};
/* ---------- kept previous versions ---------- */
/** { version, build?, firmware?, files: [paths], saved } of the kept version, or null. */
export function kept(component) {
let k = read_json(`${KEEP_DIR}/${component}/meta.json`, null);
if (!k?.version || !length(k.files ?? []))
return null;
for (let f in k.files)
if (!stat(f))
return null;
return k;
};
/** What the Components tab shows; firmware: the current one (a kept AmneziaWG build is for one firmware only). */
export function kept_all(firmware) {
let out = {};
for (let c in [ 'app', 'amneziawg' ]) {
let k = kept(c);
if (k && c == 'amneziawg' && k.firmware && firmware && k.firmware != firmware)
k = null;
out[c] = k ? { version: k.version, build: k.build ?? null, saved: k.saved ?? null } : null;
}
return out;
};
/** Replace the kept version of a component with these files (copied in). */
export function keep(component, version, files, build, firmware) {
let dir = `${KEEP_DIR}/${component}`;
system(`rm -rf ${q(dir)}; mkdir -p ${q(dir)}; chmod 700 ${q(KEEP_DIR)} ${q(dir)}`);
let saved = [];
for (let f in files) {
let to = `${dir}/${replace(f, /^.*\//, '')}`;
if (system(`cp ${q(f)} ${q(to)}`) == 0)
push(saved, to);
}
if (length(saved) == length(files))
write_json(`${dir}/meta.json`, { version, build, firmware, files: saved, saved: time() }, 0o600);
else
system(`rm -rf ${q(dir)}`);
};
export function forget(component) {
system(`rm -rf ${q(KEEP_DIR + '/' + component)}`);
};
@@ -1,9 +1,10 @@
// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and
// the portal CGI. Nothing in here touches configuration.
// the portal CGI. Nothing in here loads or commits configuration (the uci
// helpers work on a cursor the caller owns).
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.3.0';
export const VERSION = '0.4.2';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -91,15 +92,27 @@ export function read_json(path, fallback) {
}
};
/** Atomic write (temp file + rename). `mode` defaults to 0600. */
/**
* Atomic write (temp file + rename). `mode` defaults to 0600. A short write
* (flash full) leaves the old file in place and returns false.
*/
export function write_file(path, data, mode) {
let tmp = `${path}.tmp${rand_hex(3)}`;
let f = open(tmp, 'w', mode ?? 0o600);
if (!f)
return false;
f.write(data);
f.close();
return rename(tmp, path);
data = `${data ?? ''}`;
let n = length(data) ? f.write(data) : 0;
let closed = f.close();
if (n != length(data) || !closed) {
unlink(tmp);
return false;
}
if (!rename(tmp, path)) {
unlink(tmp);
return false;
}
return true;
};
export function write_json(path, data, mode) {
@@ -126,6 +139,92 @@ export function unlock(f) {
}
};
// Locks this process holds through with_lock (flock does not nest: a second
// open of the same lock file in one process would wait for itself).
let held = {};
/**
* Run fn() holding the named lock and return what it returns. Nested calls
* for the same name in one process run fn() directly. Anything fn throws
* releases the lock and is rethrown with the same message.
*/
export function with_lock(name, fn) {
if (held[name])
return fn();
let l = lock(name);
held[name] = true;
try {
let r = fn();
delete held[name];
unlock(l);
return r;
}
catch (e) {
delete held[name];
unlock(l);
die(e.message ?? `${e}`);
}
};
/* ---------- uci (on the caller's cursor) ---------- */
/** Set an option only when it differs (null, '' or [] delete it); true if something changed. */
export function uci_put(c, conf, sec, opt, val) {
let cur = c.get(conf, sec, opt);
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
if (cur != null) {
c.delete(conf, sec, opt);
return true;
}
return false;
}
if (type(val) == 'array') {
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
return false;
}
else if (cur == `${val}`)
return false;
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
return true;
};
/** Make `sec` a section of type `stype` (recreated when its type differs); true if it changed. */
export function uci_section(c, conf, sec, stype) {
if (c.get(conf, sec) == stype)
return false;
if (c.get(conf, sec) != null)
c.delete(conf, sec);
c.set(conf, sec, stype);
return true;
};
/**
* After committing a config ourselves (and applying it), record its new
* checksum so a later `reload_config` does not treat it as changed and
* restart unrelated services that reload on any network change.
*/
export function ack_config(confs) {
let md5f = '/var/run/config.md5';
if (!stat(md5f))
return;
let lines = split(trim(readfile(md5f) ?? ''), '\n');
for (let conf in confs) {
let path = `/var/run/config.check/${conf}`;
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
if (!sum)
continue;
let found = false;
for (let i = 0; i < length(lines); i++)
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
lines[i] = `${sum} ${path}`;
found = true;
}
if (!found)
push(lines, `${sum} ${path}`);
}
writefile(md5f, join('\n', lines) + '\n');
};
/* ---------- service log ---------- */
/*
@@ -271,6 +370,35 @@ export function int2ip(n) {
return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255);
};
/**
* "a.b.c.d[/len]" with any prefix 0-32 (a bare address is a /32) →
* { net, prefix, size, ip }; null for anything else. Routes, rules and
* allowed networks use this; parse_cidr is the stricter one for subnets.
*/
export function cidr_any(s) {
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
if (ip == null || prefix > 32)
return null;
let size = 1 << (32 - prefix);
return { net: ip - ip % size, prefix, size, ip };
};
/** The first of `nets` (CIDR strings, any prefix) that holds `ip` (a string or an int), or null. */
export function in_nets(ip, nets) {
let n = type(ip) == 'int' ? ip : ip2int(ip);
if (n == null)
return null;
for (let s in nets) {
let c = cidr_any(s);
if (c && n >= c.net && n < c.net + c.size)
return s;
}
return null;
};
// Cloudflare's published ranges (https://www.cloudflare.com/ips/).
const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
'108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17',
@@ -286,13 +414,7 @@ export function cloudflare_ip(a) {
return true;
return false;
}
for (let c in CF_V4) {
let m = match(c, /^([0-9.]+)\/([0-9]+)$/);
let size = 1 << (32 - +m[2]), net = ip2int(m[1]);
if (n >= net && n < net + size)
return true;
}
return false;
return in_nets(n, CF_V4) != null;
};
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
@@ -378,6 +500,16 @@ export function day_key(ts) {
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
};
/**
* The day key `days` days before `ts` (default now). Counted from local noon,
* so a 23- or 25-hour day around a DST change neither skips nor repeats a day.
*/
export function day_key_ago(days, ts) {
let t = localtime(ts ?? time());
let noon = timelocal({ year: t.year, mon: t.mon, mday: t.mday, hour: 12, min: 0, sec: 0 });
return day_key(noon - (days ?? 0) * 86400);
};
export function uniq(arr) {
let seen = {}, out = [];
for (let v in arr)
@@ -399,3 +531,18 @@ export function remove(path) {
export function now() {
return time();
};
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
export function iface_status(ifname) {
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)
return null;
try {
return json(s);
}
catch (e) {
return null;
}
};
@@ -3,22 +3,24 @@
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import { day_key, month_key } from 'dawnline.util';
import * as awg from 'dawnline.awg';
import { day_key_ago, month_key } from 'dawnline.util';
/** Daily totals (rx+tx) for the last `n` days, oldest first. */
export function spark(rec, n) {
let out = [], ts = time();
let out = [];
for (let i = n - 1; i >= 0; i--) {
let v = rec?.days?.[day_key(ts - i * 86400)];
let v = rec?.days?.[day_key_ago(i)];
push(out, v ? v[0] + v[1] : 0);
}
return out;
};
/** The device holds an older configuration than the one it would get now. */
function config_stale(m, d) {
m._issued ??= core.issued();
m._issued ??= awg.issued();
let was = m._issued[d.id];
return was != null && was != core.config_fingerprint(m, d);
return was != null && was != awg.config_fingerprint(m, d);
}
export function device_view(m, d, usage, dmp) {
@@ -27,7 +29,7 @@ export function device_view(m, d, usage, dmp) {
let ts = time();
let hs = peer?.handshake || u?.handshake || 0;
let p = m.people[d.person];
return {
let v = {
id: d.id,
name: d.name,
kind: d.kind,
@@ -35,7 +37,7 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled,
created: d.created,
created_by: d.created_by,
online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW),
online: live.online(dmp, d.id, peer),
handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer,
@@ -47,6 +49,7 @@ export function device_view(m, d, usage, dmp) {
// Its configuration changed since it was last shown or downloaded.
config_stale: config_stale(m, d),
};
return v;
};
export function person_view(m, p, usage, dmp, states, opts) {
@@ -85,9 +88,9 @@ export function person_view(m, p, usage, dmp, states, opts) {
if (d.handshake > v.last_seen)
v.last_seen = d.handshake;
if (opts.admin) {
v.code = p.code;
v.link = core.portal_url(m, p);
v.links = core.portal_urls(m, p);
// The code and links themselves are person_links' (admins only): the
// code opens the person's portal and their devices' configurations.
v.has_link = core.portal_url(m, p) != null;
v.note = p.note;
v.services = p.services;
v.home_nets = p.home_nets;
@@ -6,11 +6,12 @@
import { stat } from 'fs';
import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop';
import * as ops from 'dawnline.ops';
import * as health from 'dawnline.health';
import * as awg from 'dawnline.awg';
import * as nft from 'dawnline.nft';
import * as netifd from 'dawnline.netifd';
export const STATE = `${RUN_DIR}/watchdog.json`;
/** The agent writes the time here on every tick. */
@@ -18,13 +19,9 @@ export const BEAT = `${RUN_DIR}/agent.beat`;
// Seconds before the next repair, by the number of repairs so far.
const WAIT = [ 0, 120, 600, 1800, 3600 ];
/** Why a tunnel is down, from netifd and the last related syslog lines. */
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
export function iface_errors(ifname) {
let s = live.iface_status(ifname);
let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : ''));
// Only what explains a failure, not the ordinary "is now up/down" lines.
let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`);
return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x));
return awg.iface_errors(ifname);
};
function restart_services() {
@@ -38,30 +35,11 @@ function restart_services() {
*/
function probes(m) {
let out = [];
// The kernel module first: without it no tunnel can run (they come back on the next pass).
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key)) && stat('/usr/bin/awg'))
push(out, {
id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', ok: stat('/sys/module/amneziawg') != null,
problem: "kernel module isn't loaded", back: 'kernel module is loaded again',
detail: () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4"),
repair: { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') },
});
for (let id, srv in m.servers) {
if (!srv.enabled || !srv.private_key)
continue;
let s = live.iface_status(srv.ifname);
let up = !!s?.up;
push(out, {
id: `up_${id}`, src: 'awg', name: srv.name, who: srv.name, ok: up && ops.udp_listening(srv.port),
problem: !s ? 'is missing from the router' : !up ? "isn't running" : `isn't accepting connections on port ${srv.port}`,
back: `is running again · accepting connections on port ${srv.port}`,
detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: () => apply.apply() },
});
}
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
if (length(m.servers))
push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: system('nft list table inet dawnline >/dev/null 2>&1') == 0,
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: nft.present(),
problem: 'are missing', back: 'are loaded again',
repair: { what: 'loading them again', run: () => apply.apply() },
});
@@ -79,15 +57,9 @@ function probes(m) {
}
let s = m.settings;
if (s.portal_enabled && core.portal_public_port(m) == 443 && s.portal_port != 443)
if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port)))
push(out, {
id: 'portal_lan', src: 'portal', name: 'Portal at home', who: 'Personal portal', ok: !apply.uhttpd_drift(m),
problem: "links don't open at home (LuCI's web server lost the setting)", back: 'links open at home again',
repair: { what: 'restoring it', run: () => apply.apply() },
});
if (s.portal_enabled && !length(ops.needs().https) && !length(ops.tcp_port_owners(s.portal_port)))
push(out, {
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: ops.tcp_listening(s.portal_port),
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: health.tcp_listening(s.portal_port),
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again',
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
repair: { what: 'restarting it', run: restart_services },
+30
View File
@@ -0,0 +1,30 @@
# Backend (ucode on the router)
Read with `code-standards.md`. Everything here runs on a small router (2 × Cortex-A53 on the reference Cudy WR3000P): cost is part of correctness.
## Layers
- `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater).
- Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic.
- The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`.
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.ONLINE_WINDOW`): traffic silence is no signal, a phone asleep is silent too.
## ucode
- `'use strict'` in entry points; modules `import { … } from 'fs'` / `'dawnline.x'`. Subdirectories map to dots (`dawnline.rpc.status` → `dawnline/rpc/status.uc`).
- Exported functions end with `};` (the compiler requires it). No destructuring. Regexes are POSIX (no `(?:)`, `\s\S` classes, lazy quantifiers); anchor them.
- Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script.
- Doc comments (`/** … */`) on every export: what it returns, including the null/empty case.
- Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked.
- nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table).
## Cost on the router
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action.
- **rpcd keeps the admin backend loaded:** LuCI RPC calls are cheap, so the admin UI may poll small methods often (`rev`), and the heavy ones (`status`) only on change or rarely.
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show all dump` (about 4 ms with process start), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
- Measure before and after on the router (a loop of 20–200 calls, `/proc/self/stat` CPU ticks, system busy from `/proc/stat`) when adding anything periodic.
## 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`.
+36
View File
@@ -0,0 +1,36 @@
# Code standards
How code in our own projects (Dawnline first, the same spirit for Tachyon, liminal and the rest) is written. This file holds what applies everywhere; per area:
- `backend.md` — ucode on the router: layers, conventions, what things cost there.
- `frontend.md` — TypeScript admin UI and portal: layout, live data.
- `shell.md` — install, uninstall, init and CI scripts.
- `ui-design.md` — how anything visible looks and how it gets approved.
Match the code around you: its naming, comment density and idiom win over personal taste.
## Decomposition
- **One module, one job, named after it.** A file you cannot describe in one sentence is two files. Starting points: ~300–400 lines for a ucode/TS module, ~60 lines for a function. Past that, split by responsibility, not by line count.
- **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it).
- **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`.
- **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks.
## Logic and state
- **Validate at the boundary, trust inside.** RPC, portal, CLI and file input are checked once (types, ranges, ids, regexes anchored with `^…$`, length caps); inner code assumes valid data. Never build a shell command from unchecked input — quote with `q()` and prefer argument whitelists.
- **One writer per resource, under a lock.** Config changes go through `store.transact()` (load the model inside the lock, change, commit, chmod 600). Router state changes go through `apply` under the `apply` lock. Long jobs (updates) hold a `flock`; "is it running" comes from the lock, never from a pid file. Do not nest locks.
- **Reconcile, don't patch.** Derive router state from config and converge (idempotent: running twice changes nothing). Touch only objects you own (tagged/named `dawnline`), never foreign interfaces, zones or rules.
- **Fail closed.** If a filter or nft load fails, access stays blocked, not open. A missing dependency (no AmneziaWG, no curl, no openssl) is a reported state with a fix, never a crash: check capabilities (`awg.state()`, `health.needs()`) and gate the feature in the backend *and* the UI.
- **Atomic files.** Write JSON/state to a temp file and rename; keep runtime counters in tmpfs (`RUN_DIR`) and flush to flash (`DATA_DIR`) rarely.
- **Trust and downloads.** APIs only directly over TLS; files may come from mirrors only when their sha256 is known from the API, and every attempt is verified. No hash → direct only, or refuse.
- **Side effects at the end.** Collect restarts (network, uhttpd, re-apply) and run them once after the job, so a failure halfway never leaves half-restarted services.
- **Errors say what to do.** `die()` / thrown messages are shown to the admin: a full sentence with the cause and, where possible, the fix. Never swallow an error silently; a `catch` either handles it or logs why it is ignored.
- **Time and dates come from the router** (`localtime`, `util.today()`), not from the browser.
## Comments, names, commits
- Comments explain why and the contract, not what the next line does. English in code and UI copy.
- Names say what the thing is in the product's words (people, devices, servers, circles), not implementation words.
- Commits are reviewable pieces (one area or concern each), message says what changed and why; no push without the user's go-ahead.
+19
View File
@@ -0,0 +1,19 @@
# Frontend (TypeScript: admin UI and portal)
Read with `code-standards.md` and, for anything visible, `ui-design.md`.
## Code
- Strict TS, no `any` without a comment; types for RPC answers live in `shared/types.ts` / `admin/api.ts` and mirror the backend's shapes.
- Layout of `web/src/admin`: `ui/` generic components (button, menu, modal, drawer, tooltip, toast, controls), `widgets/` composite house widgets, `state/` polling and scoping, `events/` the activity vocabulary (model without DOM, render separate), `updater/` the Components data layer, `cores/` per-protocol bits, `pages/<page>/` one folder per page split by section, `styles/*.css` one file per feature joined in `styles/index.ts`. Shared with the portal: `src/shared/`.
- Pages build from `ui/` and `widgets/`; a page never defines a generic component. Logic that does not touch the DOM (formatting, models, CSV, sorting) lives outside the render code and gets tests.
## Live data
- Admin pages use `createPoller` (`state/poller.ts`): newest answer wins, no repaint of a region that holds focus, every RPC failure shows a toast or an inline error, never a blank section.
- Changes reach open pages through the revision (`state/live.ts`): one small `rev` call every 2 s while the page is visible; pollers that opt in (`live: true`) refresh when it moves. Their own `every` stays as a slow fallback.
- The portal does not poll (each request is a CGI process on the router, see `backend.md`): it loads once, after the visitor's own changes, and while it waits for a new device's first connection.
## Checks
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build`; the rebuilt bundles under `package/` are committed (CI fails otherwise).
+7
View File
@@ -0,0 +1,7 @@
# Shell (install, uninstall, init, CI)
Read with `code-standards.md`. Anything run on the router by hand follows the workspace's `../rules/router-shell.md` (a literal stdin heredoc over SSH).
- POSIX `sh` (BusyBox ash), `set -eu` where the script allows; quote every expansion; `shellcheck -S warning` clean (CI runs it).
- Every mutating script has a `--dry-run` that prints what it would do; uninstall removes everything install created (cron, nft, firewall, routing, packages it added, files) and nothing else — including what older versions created (e.g. the priority-90 reply rules up to 0.4.0).
- BusyBox lacks GNU options (`ls -e`, `pkill`, `time` on shell functions): check on the router before relying on a flag.
+32
View File
@@ -0,0 +1,32 @@
# UI design (Dawnline admin, portal and other panels)
The bar is a modern product UI (Linear / Vercel / Raycast level), not a "native" LuCI form. A plain label + input row, a bare radio list, three columns of check marks or a text dump is a first draft, never the result.
## Approach
- **Mock first.** Any visible change beyond a one-line fix: show a mockup (2–4 genuinely different options when the direction is open) with a recommendation, then build the chosen one. Do not start coding a layout the user has not seen.
- **Think past the obvious.** When an option is rejected as "not it", propose new concepts, not variations of the same layout.
- **Structure over text.** Tiles, segmented controls, pills, round icon buttons, inline status, folded "Advanced" sections. Summaries first ("All 6 checks passed"), details on demand.
- **No duplication.** One place per fact (usage, device count, links). Remove what is repeated elsewhere on the page.
- **Reuse the house patterns** before inventing new ones: `dl-params` folded details with a rotating chevron, `dl-tile2` tiles, round icon buttons with tooltips, `⋯` menus (destructive and Pause inside, Pause in warn colour, "Delete" without an ellipsis), bottom toasts instead of LuCI banners, the same tiles on server and person pages.
- **Alignment and spacing are part of the design.** Shared margins and edges, equal heights in a row, controls pinned consistently (top, not centred, when the user says so), nothing clipped or overflowing, single-line labels where they fit.
- **No ellipsis on buttons or menu items** ("Remove", not "Remove…"), even when they open a dialog. "…" only for progress ("Loading…") and truncated values.
- **Colour means something:** ok = green, warn/pause = orange, danger = red, accent = blue. Icons for states instead of words where obvious.
- **Honest warnings** belong in the UI (e.g. plain HTTP, Cloudflare throttling), shown where the choice is made.
## Mocks look like the real product
A mock is judged against the page it will live on, so it must already look like it. Hand-drawn look-alikes with invented styles get rejected ("выбивается из дизайна").
- **Study the existing pages first** (the section being changed and its neighbours) and build only from their components: `dl-setsec` cards with `dl-setsec-foot`, `dl-setrow` rows with a `dl-need-ic` icon tile and `dl-switch`, `dl-seg` (`sm`, `wide`), `dl-chip` / `dl-chipbtn`, `dl-list` + `dl-row`, `dl-table`, `dl-checks` (the Health check list), `dl-tile2` tiles, `dl-panel`. A new class only when nothing fits, and then in the same tokens (`--dl-*`).
- **Buttons are `cbi-button`**: actions like Edit, Change, Rescan are `neutral` pills (as "Edit in Settings", "+ Add device"); Save and Install are `positive`. No blue text links for actions.
- **Show only what changes.** Do not add existing, unrelated controls (e.g. Devices or Access ends tiles) to a mock; say in the caption that the rest of the page stays.
- **Build it from the real code and CSS**, not from a copy:
- theme: `scp root@outline.lan:/www/luci-static/outline/{main.css,geist-*.woff2}` into the mock folder, strip `/luci-static/outline/` from the font URLs, `<html data-darkmode="true">`;
- Dawnline CSS: the files in `web/src/admin/styles/*.css` concatenated in the order of `styles/index.ts` into `dl.css`;
- markup: a small `mock.ts` that imports the real `admin/e`, `shared/icons`, `admin/ui/*` and `admin/widgets/*` (stub the LuCI globals `window.E`, `dom.content`, `L.url`), bundled with `web/node_modules/.bin/esbuild --bundle --format=iife`.
- Keep mocks outside the product repo, serve them with `python3 -m http.server` started from Bash (the preview server cannot read `~/Documents` on macOS), open them in the built-in browser, and delete the folder when the feature ships.
## Done means seen
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow.
+5 -3
View File
@@ -16,9 +16,11 @@ ssh "$HOST" sh <<'REMOTE'
rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz
cd /tmp/dlc
rc=0
for f in usr/share/ucode/dawnline/*.uc; do
n=$(basename "$f" .uc)
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from 'dawnline.$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
# Modules by their import name: dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc dawnline.rpc.x.
for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do
[ -f "$f" ] || continue
n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g')
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
[ -f "$f" ] || continue
+1
View File
@@ -24,6 +24,7 @@ SHOTS = {
'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
+92 -12
View File
@@ -3,35 +3,56 @@
ucode resolves names where they are used: calling a function that is declared
further down the same file fails at runtime ("access to undeclared variable").
Also: calls and named imports must match what a Dawnline module exports, and
the rpcd methods (dawnline.rpc.*) must match the plugin and its ACL.
Run: scripts/lint-ucode.py [package root]
"""
import glob
import json
import os
import re
import sys
root = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '..', 'package', 'luci-app-dawnline', 'root')
files = glob.glob(f"{root}/usr/share/ucode/dawnline/*.uc") + [
f"{root}/usr/share/rpcd/ucode/luci.dawnline",
MODDIR = f"{root}/usr/share/ucode/dawnline"
PLUGIN = f"{root}/usr/share/rpcd/ucode/luci.dawnline"
ACL = f"{root}/usr/share/rpcd/acl.d/luci-app-dawnline.json"
modules = sorted(glob.glob(f"{MODDIR}/*.uc") + glob.glob(f"{MODDIR}/rpc/*.uc"))
files = modules + [
PLUGIN,
f"{root}/usr/libexec/dawnline/agent",
f"{root}/usr/libexec/dawnline/updater",
f"{root}/usr/libexec/dawnline/resolver",
f"{root}/usr/bin/dawnline",
f"{root}/usr/share/dawnline/portal/www/cgi-bin/portal",
]
files = [f for f in files if os.path.exists(f)]
bad = 0
checked = 0
def problem(msg):
global bad
print(msg)
bad = 1
def strip_comments(text):
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
def modname(path):
"""dawnline/rpc/people.uc → 'rpc.people' (as in import … from 'dawnline.rpc.people')."""
rel = os.path.relpath(path, MODDIR)[:-3]
return rel.replace(os.sep, '.')
for f in files:
if not os.path.exists(f):
continue
checked += 1
code = re.sub(r'//[^\n]*|/\*.*?\*/', '', open(f, encoding='utf-8').read(), flags=re.S)
code = strip_comments(open(f, encoding='utf-8').read())
defs = {m.group(1): m.start() for m in re.finditer(r'^(?:export )?function (\w+)\(', code, re.M)}
for name, pos in defs.items():
for m in re.finditer(r'(?<![\w.\'"`])' + name + r'\(', code[:pos]):
line = code[: m.start()].count('\n') + 1
print(f"{f}:{line}: {name}() is used before its definition")
bad = 1
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')
@@ -41,8 +62,67 @@ for f in files:
inside = n
elif inside is not None and re.match(r'^}', text):
if not text.startswith('};'):
print(f"{f}:{n}: exported function from line {inside} must end with '}};'")
bad = 1
problem(f"{f}:{n}: exported function from line {inside} must end with '}};'")
inside = None
print(f"lint-ucode: {checked} files checked" + (", problems found" if bad else ", ok"))
# ucode regexes are POSIX: a (?: group fails when the line runs ("Repetition
# 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")
if re.match(r'\s*(let|const)\s*[\[{]', text):
problem(f"{f}:{n}: ucode has no destructuring")
# Calls into another Dawnline module (alias.fn(...)) and named imports must name
# something it exports: one removed from a module but still used elsewhere only
# fails at runtime.
exports = {}
for f in modules:
text = open(f, encoding='utf-8').read()
exports[modname(f)] = set(re.findall(r'^export (?:function|const|let) (\w+)', text, re.M))
for f in files:
code = strip_comments(open(f, encoding='utf-8').read())
for alias, mod in re.findall(r"import \* as (\w+) from 'dawnline\.([\w.]+)'", code):
if mod not in exports:
problem(f"{f}: imports dawnline.{mod}, which does not exist")
continue
# Calls, and constants (upper case: a lower-case "geo.json" in a string is no access).
for m in re.finditer(r'(?<![\w.])' + alias + r'\.(\w+\(|[A-Z][A-Z0-9_]*\b)', code):
name = m.group(1).rstrip('(')
if name not in exports[mod]:
line = code[: m.start()].count('\n') + 1
problem(f"{f}:{line}: {alias}.{name} is not exported by dawnline.{mod}")
for names, mod in re.findall(r"import \{([^}]*)\} from 'dawnline\.([\w.]+)'", code):
if mod not in exports:
problem(f"{f}: imports dawnline.{mod}, which does not exist")
continue
for name in re.split(r'\s*,\s*', names.strip()):
name = re.split(r'\s+as\s+', name)[0].strip()
if name and name not in exports[mod]:
problem(f"{f}: {name} is not exported by dawnline.{mod}")
# rpcd methods: every rpc module's `methods` is merged by the plugin, no name is
# defined twice (the later one would silently win), and the ACL's read list
# names methods that exist.
methods = {}
for f in glob.glob(f"{MODDIR}/rpc/*.uc"):
text = strip_comments(open(f, encoding='utf-8').read())
m = re.search(r'^export const methods = \{\n(.*?)^\};', text, re.M | re.S)
if not m:
continue
mod = modname(f)
if os.path.exists(PLUGIN) and f"from 'dawnline.{mod}'" not in open(PLUGIN, encoding='utf-8').read():
problem(f"{PLUGIN}: does not import dawnline.{mod}, whose methods would be missing")
for name in re.findall(r"^\t'?(\w+)'?: \{", m.group(1), re.M):
if name in methods:
problem(f"{f}: method {name} is also defined in dawnline.{methods[name]}")
methods[name] = mod
if methods and os.path.exists(ACL):
acl = json.load(open(ACL, encoding='utf-8'))['luci-app-dawnline']
for kind in ('read', 'write'):
for name in acl.get(kind, {}).get('ubus', {}).get('luci.dawnline', []):
if name != '*' and name not in methods:
problem(f"{ACL}: {kind} lists {name}, which no dawnline.rpc module defines")
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")
print(f"lint-ucode: {len(files)} files checked" + (", problems found" if bad else ", ok"))
sys.exit(bad)
+72
View File
@@ -0,0 +1,72 @@
#!/bin/sh
# shellcheck shell=dash
#
# Release notes for a tag, from the commits since the previous tag:
# scripts/release-notes.sh v0.3.1 [repository]
# PREV_TAG=v0.1.1 scripts/release-notes.sh v0.3.0 (compare with another tag)
#
# Release commits ("Dawnline 0.3.1") list their changes as "- " lines in the
# body: those become the points. Other commits add their title; merges are
# skipped. Wrapped points are joined into one line, so the Components tab
# (and anything else reading the release) gets one change per line.
set -eu
TAG="${1:?usage: release-notes.sh <tag> [owner/repo]}"
REPO="${2:-tickcount/luci-app-dawnline}"
git rev-parse -q --verify "$TAG^{commit}" >/dev/null || {
echo "release-notes: no tag $TAG" >&2
exit 1
}
# The previous release: the nearest older tag, or PREV_TAG when a tag was never published.
PREV="${PREV_TAG:-$(git describe --tags --abbrev=0 --match 'v[0-9]*' "$TAG^" 2>/dev/null || true)}"
if [ -n "$PREV" ] && ! git rev-parse -q --verify "$PREV^{commit}" >/dev/null; then
echo "release-notes: no tag $PREV" >&2
exit 1
fi
RANGE="$TAG"
[ -n "$PREV" ] && RANGE="$PREV..$TAG"
# git log runs alone first: a failure must stop the script, not vanish into the pipe.
git log --no-merges --format='%s' "$RANGE" >/dev/null
# One record per commit, newest first: the subject, then the body; records end with RS (\036).
points="$(git log --no-merges --format='%s%n%b%x1e' "$RANGE" | awk '
BEGIN { RS = "\036" }
{
n = split($0, line, "\n")
title = ""
for (i = 1; i <= n; i++) if (line[i] != "") { title = line[i]; start = i + 1; break }
if (title == "") next
got = 0; cur = ""
for (i = start; i <= n; i++) {
if (line[i] ~ /^[ \t]*[-*][ \t]+/) {
if (cur != "") { print "- " cur; got = 1 }
cur = line[i]; sub(/^[ \t]*[-*][ \t]+/, "", cur)
} else if (cur != "" && line[i] ~ /^[ \t]+[^ \t]/) {
l = line[i]; sub(/^[ \t]+/, "", l); cur = cur " " l
} else if (cur != "") { print "- " cur; got = 1; cur = "" }
}
if (cur != "") { print "- " cur; got = 1 }
# A release commit without a list says nothing new; any other commit is its title.
if (!got && title !~ /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) print "- " title
}')"
if [ -n "$points" ]; then
printf "## What’s new\n\n%s\n\n" "$points"
fi
cat <<EOF
## Install
Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk):
\`\`\`sh
sh -c "\$(wget -qO- https://raw.githubusercontent.com/$REPO/main/install.sh)"
\`\`\`
Or update from LuCI → Network → Dawnline → Components.
EOF
if [ -n "$PREV" ]; then
printf '\n**Full Changelog**: https://github.com/%s/compare/%s...%s\n' "$REPO" "$PREV" "$TAG"
else
printf '\n**Full Changelog**: https://github.com/%s/commits/%s\n' "$REPO" "$TAG"
fi
Executable
+773
View File
@@ -0,0 +1,773 @@
#!/bin/sh
# shellcheck shell=dash
#
# Dawnline uninstaller for OpenWrt.
#
# sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
#
# Backs up the configuration, runs Dawnline's own removal (the same as
# Settings → Remove Dawnline from this router: tunnels, firewall rules, portal,
# routing and the home-like link go away), removes the package and cleans what
# is left. AmneziaWG stays unless --remove-awg is given. `--help` lists the
# options.
UNINSTALLER_VERSION="1.0.0"
PKG_NAME="luci-app-dawnline"
# Removal order: LuCI pieces first, the kernel module last.
AWG_PKGS="luci-i18n-amneziawg-ru luci-proto-amneziawg amneziawg-tools kmod-amneziawg"
LOG_FILE="/tmp/dawnline-uninstall.log"
LOCK_DIR="/tmp/dawnline.install.lock.d"
DATA_DIR="/etc/dawnline"
BACKUP_DIR="$DATA_DIR/backups"
ASSUME_YES=0
PURGE=0
REMOVE_AWG=0
DRY_RUN=0
VERBOSE=0
LOG_READY=0
LOCK_HELD=0
TMP_DIR=""
PKG_MANAGER=""
PKG_IS_APK=0
STEP=0
STEPS=6
BACKUP_PATH=""
FAILED=0
_STREAM_PID=""
_STREAM_STOP=""
ESC="$(printf '\033')"
if [ -t 1 ] 2>/dev/null && [ "${TERM:-dumb}" != "dumb" ]; then
C_RESET="${ESC}[0m"
C_BOLD="${ESC}[1m"
C_RED="${ESC}[31;1m"
C_GREEN="${ESC}[32;1m"
C_YELLOW="${ESC}[33;1m"
C_CYAN="${ESC}[36;1m"
else
C_RESET=""
C_BOLD=""
C_RED=""
C_GREEN=""
C_YELLOW=""
C_CYAN=""
fi
START_TS="$(date +%s 2>/dev/null || echo 0)"
# ---------- output ----------
ts_elapsed() {
_now="$(date +%s 2>/dev/null || echo "$START_TS")"
_el=$((_now - START_TS))
[ "$_el" -ge 0 ] 2>/dev/null || _el=0
printf '+%02d:%02d' $((_el / 60)) $((_el % 60))
}
log_line() {
[ "$LOG_READY" -eq 1 ] || return 0
printf '[%s %s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null)" "$(ts_elapsed)" "$1" >>"$LOG_FILE" 2>/dev/null || true
}
msg() {
log_line "INFO $1"
printf ' [%s] %s%s%s\n' "$(ts_elapsed)" "$C_CYAN" "$1" "$C_RESET"
}
ok() {
log_line "OK $1"
printf ' [%s] %s%s✓%s %s\n' "$(ts_elapsed)" "$C_GREEN" "$C_BOLD" "$C_RESET" "$1"
}
warn() {
log_line "WARN $1"
printf ' [%s] %s%s⚠%s %s\n' "$(ts_elapsed)" "$C_YELLOW" "$C_BOLD" "$C_RESET" "$1" >&2
}
err() {
log_line "ERROR $1"
printf ' [%s] %s%s✗%s %s\n' "$(ts_elapsed)" "$C_RED" "$C_BOLD" "$C_RESET" "$1" >&2
}
debug() {
log_line "DEBUG $1"
[ "$VERBOSE" -eq 1 ] || return 0
printf ' [%s] [debug] %s\n' "$(ts_elapsed)" "$1" >&2
}
dry() {
msg "[dry-run] would $1"
}
step() {
STEP=$((STEP + 1))
log_line "STEP [$STEP/$STEPS] $1"
printf ' [%s] %s[%s/%s] %s%s\n' "$(ts_elapsed)" "$C_BOLD" "$STEP" "$STEPS" "$1" "$C_RESET"
}
fail() {
err "$1"
[ "$LOG_READY" -eq 1 ] && err "Uninstaller log: $LOG_FILE"
exit 1
}
usage() {
cat <<EOF
Dawnline Uninstaller v${UNINSTALLER_VERSION}
Usage: sh uninstall.sh [options]
-y, --yes Do not ask for confirmation
-p, --purge Also delete the configuration, keys, history and every
backup (/etc/config/dawnline, /etc/dawnline). No backup is made.
--keep-awg Keep AmneziaWG (the default: other tunnels may use it)
--remove-awg Also remove AmneziaWG, unless another interface still uses it
-n, --dry-run Show what would be removed; change nothing
-v, --verbose Print diagnostics
--version Print the uninstaller version
-h, --help Show this help
Without --purge a backup of the configuration is kept in $BACKUP_DIR:
after installing Dawnline again, restore it in Dawnline → Settings → Backups.
Log: $LOG_FILE
EOF
}
parse_args() {
while [ "$#" -gt 0 ]; do
case "$1" in
-y | --yes) ASSUME_YES=1 ;;
-p | --purge) PURGE=1 ;;
--keep-awg) REMOVE_AWG=0 ;;
--remove-awg) REMOVE_AWG=1 ;;
-n | --dry-run) DRY_RUN=1 ;;
-v | --verbose) VERBOSE=1 ;;
--version)
printf 'dawnline-uninstaller %s\n' "$UNINSTALLER_VERSION"
exit 0
;;
-h | --help)
usage
exit 0
;;
*)
err "Unknown option: $1 (see --help)"
return 2
;;
esac
shift
done
return 0
}
# ---------- process plumbing ----------
command_exists() { command -v "$1" >/dev/null 2>&1; }
acquire_lock() {
if mkdir "$LOCK_DIR" 2>/dev/null; then
echo "$$" >"$LOCK_DIR/pid"
LOCK_HELD=1
return 0
fi
_old="$(cat "$LOCK_DIR/pid" 2>/dev/null)"
if [ -n "$_old" ] && kill -0 "$_old" 2>/dev/null; then
err "Another Dawnline installer or uninstaller is running (pid $_old)"
return 1
fi
warn "Removing a stale installer lock${_old:+ (pid $_old)}"
rm -rf "$LOCK_DIR" 2>/dev/null
mkdir "$LOCK_DIR" 2>/dev/null || {
err "Cannot create the lock $LOCK_DIR"
return 1
}
echo "$$" >"$LOCK_DIR/pid"
LOCK_HELD=1
}
release_lock() {
[ "$LOCK_HELD" -eq 1 ] || return 0
[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR" 2>/dev/null
LOCK_HELD=0
}
_NL='
'
_stream_poll() {
_ssize="$(wc -c <"$_sf" 2>/dev/null | tr -d " ")"
case "$_ssize" in '' | *[!0-9]*) _ssize=0 ;; esac
[ "$_ssize" -gt "$_spos" ] || return 0
_sbuf="$_sbuf$(tail -c +$((_spos + 1)) "$_sf" 2>/dev/null)$_NL"
_spos="$_ssize"
case "$(tail -c 1 "$_sf" 2>/dev/null)" in
'') ;;
*) _sbuf="${_sbuf%"$_NL"}" ;;
esac
while :; do
case "$_sbuf" in
*"$_NL"*) ;;
*) break ;;
esac
_sline="${_sbuf%%"$_NL"*}"
_sbuf="${_sbuf#*"$_NL"}"
[ -n "$_sline" ] && printf ' [%s] [%s] %s\n' "$(ts_elapsed)" "$_stag" "$_sline"
done
return 0
}
_stream_loop() {
_sf="$1"
_stag="$2"
_sstop="$3"
_sparent="$4"
_spos=0
_sbuf=""
_sidle=0
while :; do
[ -e "$_sstop" ] && break
kill -0 "$_sparent" 2>/dev/null || break
_spre="$_spos"
_stream_poll
if [ "$_spos" -eq "$_spre" ]; then
_sidle=$((_sidle + 1))
[ $((_sidle % 10)) -eq 0 ] && printf ' [%s] [%s] … still running (%ss)\n' "$(ts_elapsed)" "$_stag" "$_sidle"
else
_sidle=0
fi
sleep 1
done
_stream_poll
[ -n "$_sbuf" ] && printf ' [%s] [%s] %s\n' "$(ts_elapsed)" "$_stag" "$_sbuf"
return 0
}
stream_stop() {
[ -n "$_STREAM_PID" ] || return 0
: >"$_STREAM_STOP" 2>/dev/null
wait "$_STREAM_PID" 2>/dev/null
_STREAM_PID=""
rm -f "$_STREAM_STOP" 2>/dev/null
return 0
}
# run_logged TAG COMMAND...: foreground, output streamed and kept in the log.
run_logged() {
_tag="$1"
shift
_out="$TMP_DIR/cmd.$$.out"
log_line "EXEC [$_tag] $*"
: >"$_out"
_STREAM_STOP="$_out.stop"
rm -f "$_STREAM_STOP"
_stream_loop "$_out" "$_tag" "$_STREAM_STOP" "$$" &
_STREAM_PID=$!
"$@" >"$_out" 2>&1 </dev/null
_rc=$?
stream_stop
if [ -s "$_out" ]; then
while IFS= read -r _line || [ -n "$_line" ]; do
log_line " [$_tag] $_line"
done <"$_out"
fi
log_line "EXIT [$_tag] $_rc"
cp "$_out" "$TMP_DIR/last.out" 2>/dev/null
rm -f "$_out"
return "$_rc"
}
# act DESCRIPTION TAG COMMAND...: run, or only say it in a dry run.
act() {
_desc="$1"
shift
if [ "$DRY_RUN" -eq 1 ]; then
dry "$_desc"
return 0
fi
debug "$_desc"
run_logged "$@"
}
# ---------- packages ----------
detect_package_manager() {
if command_exists apk; then
PKG_MANAGER="apk"
PKG_IS_APK=1
elif command_exists opkg; then
PKG_MANAGER="opkg"
PKG_IS_APK=0
else
err "Neither apk nor opkg is available"
return 1
fi
}
pkg_is_installed() {
if [ "$PKG_IS_APK" -eq 1 ]; then
apk info -e "$1" >/dev/null 2>&1
else
opkg status "$1" 2>/dev/null | grep -q '^Status: .* installed'
fi
}
installed_dawnline_pkgs() {
_l=""
pkg_is_installed "$PKG_NAME" && _l="$PKG_NAME"
if [ "$PKG_IS_APK" -eq 1 ]; then
_i18n="$(apk info 2>/dev/null | grep '^luci-i18n-dawnline-')"
else
_i18n="$(opkg list-installed 'luci-i18n-dawnline-*' 2>/dev/null | awk '{ print $1 }')"
fi
# Translations first: they depend on the app.
for _p in $_i18n; do _l="$_p $_l"; done
printf '%s' "$_l"
}
pkg_remove() {
_tag="$1"
shift
if [ "$PKG_IS_APK" -eq 1 ]; then
act "apk del $*" "$_tag" apk del "$@"
else
_w=0
while pidof opkg >/dev/null 2>&1 && [ "$_w" -lt 30 ]; do
_w=$((_w + 1))
sleep 1
done
act "opkg remove $*" "$_tag" opkg remove "$@"
fi
}
# ---------- steps ----------
dawnline_present() {
pkg_is_installed "$PKG_NAME" || [ -e /usr/bin/dawnline ] || [ -e /etc/init.d/dawnline ] ||
[ -e /etc/config/dawnline ] || [ -d "$DATA_DIR" ]
}
confirm() {
[ "$ASSUME_YES" -eq 0 ] && [ "$DRY_RUN" -eq 0 ] && [ -t 0 ] || return 0
printf ' This removes %sDawnline%s from the router: everyone is disconnected, and its\n' "$C_BOLD" "$C_RESET"
printf ' tunnels, firewall rules, portal and the %s package are removed.\n' "$PKG_NAME"
if [ "$PURGE" -eq 1 ]; then
printf ' %s--purge: the configuration, keys, history and every backup are deleted too.%s\n' "$C_RED" "$C_RESET"
printf ' %sThis cannot be undone.%s\n' "$C_RED" "$C_RESET"
else
printf ' A backup of the configuration is kept in %s.\n' "$BACKUP_DIR"
fi
if [ "$REMOVE_AWG" -eq 1 ]; then
printf ' AmneziaWG is removed too, unless another interface still uses it.\n'
else
printf ' AmneziaWG stays installed (other tunnels may use it; --remove-awg removes it).\n'
fi
printf '\n Remove Dawnline? [y/N] '
read -r _answer || _answer=""
case "$_answer" in
y | Y | yes | Yes | YES) ;;
*)
msg "Cancelled: nothing was changed"
exit 0
;;
esac
}
# An update (by hand or automatic) may be in the middle of opkg/apk: let it
# finish rather than tear the package out from under it. The updater holds
# UPDATE_LOCK for a whole job; once this script has it, no automatic update
# can start until the removal is over.
UPDATE_JOB=/var/run/dawnline/update-job.json
UPDATE_LOCK=/var/run/dawnline/update.lock
update_running() {
if command_exists flock && [ -e "$UPDATE_LOCK" ]; then
exec 8>>"$UPDATE_LOCK"
flock -n 8 && return 1
return 0
fi
[ -f "$UPDATE_JOB" ] || return 1
grep -q '"state": *"running"' "$UPDATE_JOB" 2>/dev/null || return 1
_pid="$(sed -n 's/.*"pid": *\([0-9][0-9]*\).*/\1/p' "$UPDATE_JOB" | head -n 1)"
[ -n "$_pid" ] && [ -d "/proc/$_pid" ]
}
wait_for_update() {
update_running || return 0
if [ "$DRY_RUN" -eq 1 ]; then
warn "An update is running: the removal would wait for it to finish"
return 0
fi
msg "An update is running: waiting for it to finish (up to 5 min)"
_w=0
while update_running; do
[ "$_w" -ge 300 ] && fail "The update is still running after 5 min. Nothing was removed; try again when it finishes"
sleep 5
_w=$((_w + 5))
[ $((_w % 30)) -eq 0 ] && msg "… still updating (${_w}s)"
done
ok "The update finished"
}
do_backup() {
step "Backing up the configuration"
if [ "$PURGE" -eq 1 ]; then
warn "--purge: no backup is made"
return 0
fi
if [ ! -f /etc/config/dawnline ]; then
ok "No /etc/config/dawnline: nothing to back up"
return 0
fi
if [ "$DRY_RUN" -eq 1 ]; then
dry "save /etc/config/dawnline and Dawnline's data to $BACKUP_DIR"
return 0
fi
_bn=""
if [ -x /usr/bin/dawnline ]; then
_bn="$(/usr/bin/dawnline backup --reason pre-remove 2>>"$LOG_FILE")"
[ -n "$_bn" ] && [ -f "$BACKUP_DIR/$_bn" ] || _bn=""
[ -n "$_bn" ] || warn "dawnline backup failed; saving the files directly"
fi
if [ -z "$_bn" ]; then
# The same archive format Dawnline makes, so Settings → Backups can restore it.
_bn="dawnline-$(date +%Y%m%d-%H%M%S)-pre-remove.tar.gz"
set -- etc/config/dawnline
for _f in usage.json events.json; do
[ -f "$DATA_DIR/$_f" ] && set -- "$@" "${DATA_DIR#/}/$_f"
done
mkdir -p "$BACKUP_DIR" && chmod 700 "$DATA_DIR" "$BACKUP_DIR" 2>/dev/null
tar -czf "$BACKUP_DIR/$_bn" -C / "$@" 2>>"$LOG_FILE" || {
rm -f "$BACKUP_DIR/$_bn"
fail "The backup failed and nothing was removed (--purge removes without a backup)"
}
fi
chmod 600 "$BACKUP_DIR/$_bn" 2>/dev/null
BACKUP_PATH="$BACKUP_DIR/$_bn"
ok "Backup: $BACKUP_PATH"
}
do_teardown() {
step "Running Dawnline's own removal"
if ubus list luci.dawnline >/dev/null 2>&1; then
# The same call as Settings → Remove Dawnline from this router.
if act "call luci.dawnline uninstall (Settings → Remove Dawnline)" rpc \
ubus -t 120 call luci.dawnline uninstall '{"confirm":"remove"}'; then
[ "$DRY_RUN" -eq 1 ] && return 0
if grep -q '"ok": *true' "$TMP_DIR/last.out" 2>/dev/null; then
ok "Tunnels, firewall rules, portal and routing removed; service stopped"
return 0
fi
fi
warn "luci.dawnline uninstall failed: $(sed -n 's/.*"error": *"\(.*\)".*/\1/p' "$TMP_DIR/last.out" 2>/dev/null | head -n 1)"
fi
if [ -x /usr/bin/dawnline ]; then
act "stop the Dawnline service" stop /etc/init.d/dawnline stop
if act "run 'dawnline teardown'" teardown /usr/bin/dawnline teardown; then
ok "dawnline teardown removed what Dawnline created"
else
warn "dawnline teardown failed: leftovers are cleaned in step 5"
fi
act "disable the Dawnline service" disable /etc/init.d/dawnline disable
return 0
fi
if [ -x /etc/init.d/dawnline ]; then
act "stop and disable the Dawnline service" stop sh -c '/etc/init.d/dawnline stop; /etc/init.d/dawnline disable'
fi
warn "/usr/bin/dawnline is missing: leftovers are cleaned in step 5"
}
do_remove_package() {
step "Removing the package"
_pkgs="$(installed_dawnline_pkgs)"
if [ -z "$_pkgs" ]; then
ok "$PKG_NAME is not installed"
return 0
fi
# shellcheck disable=SC2086
pkg_remove pkg $_pkgs
if [ "$DRY_RUN" -eq 0 ] && pkg_is_installed "$PKG_NAME"; then
err "$PKG_MANAGER could not remove $PKG_NAME (see $LOG_FILE)"
FAILED=1
return 0
fi
[ "$DRY_RUN" -eq 1 ] || ok "Removed: $_pkgs"
}
do_awg() {
step "AmneziaWG"
_have=""
for _p in $AWG_PKGS; do
pkg_is_installed "$_p" && _have="$_have $_p"
done
_have="${_have# }"
if [ -z "$_have" ]; then
ok "AmneziaWG is not installed"
return 0
fi
if [ "$REMOVE_AWG" -eq 0 ]; then
ok "AmneziaWG kept (other tunnels may use it; --remove-awg removes it)"
return 0
fi
# AmneziaWG interfaces that are not Dawnline's (tagged _dawnline).
_users=""
for _i in $(uci -q show network 2>/dev/null | sed -n "s/^network\.\([^.]*\)\.proto='amneziawg'$/\1/p"); do
[ -n "$(uci -q get "network.$_i._dawnline")" ] || _users="$_users $_i"
done
if [ -n "$_users" ]; then
warn "AmneziaWG kept: still used by interface(s)$_users"
return 0
fi
# shellcheck disable=SC2086
pkg_remove awg $_have
if [ "$DRY_RUN" -eq 0 ]; then
if pkg_is_installed kmod-amneziawg || pkg_is_installed amneziawg-tools; then
warn "AmneziaWG could not be removed completely (see $LOG_FILE)"
else
ok "AmneziaWG removed"
fi
fi
}
# Only objects Dawnline names as its own (see "What Dawnline changes" in the
# README); normally `dawnline teardown` has removed all of them already.
clean_network_leftovers() {
_ifs="$(uci -q show network 2>/dev/null | sed -n "s/^network\.\([^.]*\)\._dawnline=.*/\1/p")"
_fw="$(uci -q show firewall 2>/dev/null | sed -n 's/^firewall\.\(dawnline[A-Za-z0-9_]*\)=.*/\1/p')"
_found=0
if [ -n "$_ifs" ]; then
_found=1
for _i in $_ifs; do
if [ "$DRY_RUN" -eq 1 ]; then
dry "delete network interface $_i"
else
ifdown "$_i" >/dev/null 2>&1
uci -q delete "network.$_i"
fi
done
[ "$DRY_RUN" -eq 1 ] || {
uci -q commit network
ubus call network reload >/dev/null 2>&1
}
[ "$DRY_RUN" -eq 1 ] || ok "Removed leftover tunnel interfaces: $(echo "$_ifs" | tr '\n' ' ')"
fi
if [ -n "$_fw" ]; then
_found=1
if [ "$DRY_RUN" -eq 1 ]; then
dry "delete firewall sections: $(echo "$_fw" | tr '\n' ' ')"
else
for _s in $_fw; do uci -q delete "firewall.$_s"; done
uci -q commit firewall
/etc/init.d/firewall reload >/dev/null 2>&1
ok "Removed leftover firewall sections: $(echo "$_fw" | tr '\n' ' ')"
fi
fi
for _t in dawnline dawnline_reply; do
command_exists nft && nft list table inet "$_t" >/dev/null 2>&1 || continue
_found=1
if [ "$DRY_RUN" -eq 1 ]; then
dry "delete the nft table inet $_t"
else
nft delete table inet "$_t" 2>/dev/null
ok "Removed the nft table inet $_t"
fi
done
if [ -e /var/run/netns/dawnline ] || ip link show dlx0 >/dev/null 2>&1 || ip link show dll0 >/dev/null 2>&1; then
_found=1
if [ "$DRY_RUN" -eq 1 ]; then
dry "delete the dawnline network namespace and its veth links"
else
ip link del dlx0 >/dev/null 2>&1
ip link del dll0 >/dev/null 2>&1
ip netns del dawnline >/dev/null 2>&1 || rm -f /var/run/netns/dawnline
ok "Removed the dawnline network namespace (policy rules left behind go away on reboot)"
fi
fi
clean_routing_leftovers "$_ifs" && _found=1
[ "$_found" -eq 1 ] || ok "No tunnel, firewall, nft or routing leftovers"
}
# Dawnline's policy rules: priority 90 sent the portal's and the tunnels'
# answers by the main table (up to 0.4.0); 5200-5299 are the "like a home
# device" loop for a tunnel interface (Dawnline's, or one already gone), with
# tables 2077-2176.
clean_routing_leftovers() {
_ours=" $(echo "$1" | tr '\n' ' ') "
_rules=""
for _fam in -4 -6; do
_r="$(ip "$_fam" rule show 2>/dev/null | awk -v fam="$_fam" -v ours="$_ours" '
{ pr = $1; sub(/:$/, "", pr); pr += 0; line = $0; sub(/^[0-9]+:[ \t]*/, "", line) }
pr == 90 && line ~ /ipproto (tcp|udp) sport [0-9]+ lookup main/ { print fam "|" pr "|" line; next }
pr >= 5200 && pr < 5300 && fam == "-4" && match(line, /iif [^ ]+/) {
dev = substr(line, RSTART + 4, RLENGTH - 4)
if (line ~ /\[detached\]/ || index(ours, " " dev " ")) print fam "|" pr "|" line
}')"
[ -n "$_r" ] && _rules="$_rules$_r
"
done
_rules="$(printf '%s' "$_rules" | sed '/^$/d')"
[ -n "$_rules" ] || return 1
_tables="$(printf '%s\n' "$_rules" | awk '{ t = $NF + 0; if ($(NF - 1) == "lookup" && t >= 2077 && t < 2177) print t }' | sort -u)"
if [ "$DRY_RUN" -eq 1 ]; then
printf '%s\n' "$_rules" | while IFS='|' read -r _f _p _l; do dry "delete ip $_f rule $_p: $_l"; done
for _t in $_tables; do dry "flush route table $_t"; done
return 0
fi
printf '%s\n' "$_rules" | while IFS='|' read -r _f _p _l; do
# "from all" and "[detached]" are how ip prints a rule, not how it takes one.
_spec="$(echo "$_l" | sed -e 's/^from all //' -e 's/ \[detached\]//')"
# shellcheck disable=SC2086 # the rule spec is words for ip
ip "$_f" rule del priority "$_p" $_spec 2>/dev/null
done
for _t in $_tables; do ip -4 route flush table "$_t" 2>/dev/null; done
ok "Removed $(printf '%s\n' "$_rules" | wc -l | tr -d ' ') leftover routing rule(s)"
return 0
}
do_leftovers() {
step "Cleaning up leftovers"
clean_network_leftovers
if grep -qs '/usr/libexec/dawnline/' /etc/crontabs/root; then
if [ "$DRY_RUN" -eq 1 ]; then
dry "remove Dawnline lines from /etc/crontabs/root"
else
sed -i '\#/usr/libexec/dawnline/#d' /etc/crontabs/root
/etc/init.d/cron restart >/dev/null 2>&1
ok "Removed the heartbeat cron job"
fi
fi
set -- /var/run/dawnline /var/run/dawnline-dns.pid /var/etc/dawnline-dns.conf \
/var/etc/dawnline-dns.resolv /var/etc/dawnline-ns.nft /tmp/hosts/dawnline /tmp/dawnline-update \
/www/cgi-bin/dawnline-portal
# The package's own files, only once the package manager has let go of them.
if ! pkg_is_installed "$PKG_NAME"; then
set -- "$@" /usr/bin/dawnline /usr/libexec/dawnline /usr/share/dawnline /usr/share/ucode/dawnline \
/etc/init.d/dawnline /etc/hotplug.d/iface/95-dawnline /etc/uci-defaults/90_dawnline \
/usr/share/rpcd/ucode/luci.dawnline /usr/share/rpcd/acl.d/luci-app-dawnline.json \
/usr/share/luci/menu.d/luci-app-dawnline.json /www/luci-static/resources/dawnline \
/www/luci-static/resources/view/dawnline
for _r in /etc/rc.d/*dawnline; do [ -e "$_r" ] && set -- "$@" "$_r"; done
fi
if [ "$PURGE" -eq 1 ]; then
set -- "$@" "$DATA_DIR" /etc/config/dawnline /etc/config/dawnline-opkg /etc/config/dawnline.apk-new
fi
_gone=""
for _p in "$@"; do
[ -e "$_p" ] || [ -L "$_p" ] || continue
_gone="$_gone $_p"
if [ "$DRY_RUN" -eq 1 ]; then
dry "delete $_p"
else
rm -rf "$_p"
fi
done
if [ -n "$_gone" ] && [ "$DRY_RUN" -eq 0 ]; then
log_line "INFO deleted:$_gone"
case "$_gone" in *"/tmp/hosts/dawnline"*) killall -HUP dnsmasq 2>/dev/null ;; esac
ok "Removed leftover files ($(echo "$_gone" | wc -w | tr -d ' '))"
elif [ -z "$_gone" ]; then
ok "No leftover files"
fi
if [ "$PURGE" -eq 1 ] && [ "$DRY_RUN" -eq 0 ]; then
ok "Configuration, keys, history and backups deleted (--purge)"
elif [ "$PURGE" -eq 0 ]; then
_kept=""
[ -f /etc/config/dawnline ] && _kept="/etc/config/dawnline"
[ -d "$DATA_DIR" ] && _kept="${_kept:+$_kept and }$DATA_DIR (backups, history)"
[ -z "$_kept" ] || ok "Kept: $_kept"
fi
if [ "$DRY_RUN" -eq 1 ]; then
dry "clear the LuCI caches"
else
rm -f /tmp/luci-indexcache* /var/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null
ok "LuCI caches cleared"
fi
}
do_reload_luci() {
step "Reloading LuCI"
_done=""
for _svc in rpcd uhttpd; do
[ -x "/etc/init.d/$_svc" ] || continue
act "restart $_svc" "$_svc" "/etc/init.d/$_svc" restart && _done="${_done:+$_done and }$_svc"
done
[ "$DRY_RUN" -eq 1 ] || [ -z "$_done" ] || ok "Restarted $_done (log in to LuCI again if asked)"
return 0
}
cleanup() {
trap '' HUP INT TERM
stream_stop
[ -n "$TMP_DIR" ] && rm -rf "$TMP_DIR" 2>/dev/null
release_lock
}
on_hup() { exit 129; }
on_int() { exit 130; }
on_term() { exit 143; }
on_pipe() {
trap '' PIPE
exit 141
}
main() {
trap cleanup EXIT
trap on_hup HUP
trap on_int INT
trap on_term TERM
trap on_pipe PIPE
parse_args "$@" || exit 2
[ "$(id -u 2>/dev/null || echo 1)" = 0 ] || fail "Run the uninstaller as root"
acquire_lock || exit 1
: >"$LOG_FILE" 2>/dev/null && chmod 600 "$LOG_FILE" 2>/dev/null && LOG_READY=1
log_line "INFO Dawnline Uninstaller $UNINSTALLER_VERSION: $0 $*"
TMP_DIR="$(mktemp -d /tmp/dawnline-uninstaller.XXXXXX 2>/dev/null)" || TMP_DIR=""
[ -n "$TMP_DIR" ] || {
TMP_DIR="/tmp/dawnline-uninstaller.$$"
mkdir -p "$TMP_DIR" || fail "Cannot create a temporary directory in /tmp"
}
detect_package_manager || fail "No supported package manager"
printf '\n %s%sDawnline Uninstaller%s v%s\n' "$C_CYAN" "$C_BOLD" "$C_RESET" "$UNINSTALLER_VERSION"
printf ' Removes Dawnline and everything it set up; AmneziaWG stays unless asked\n\n'
[ "$DRY_RUN" -eq 1 ] && msg "Dry run: nothing on the router is changed"
if ! dawnline_present; then
ok "Dawnline is not installed: nothing to do"
return 0
fi
confirm
wait_for_update
# Once started, an SSH drop must not leave the removal half done.
trap '' HUP
do_backup
do_teardown
do_remove_package
do_awg
do_leftovers
do_reload_luci
_took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS))
if [ "$DRY_RUN" -eq 1 ]; then
ok "Dry run finished in ${_took}s: nothing was changed"
msg "Log: $LOG_FILE"
return 0
fi
if [ "$FAILED" -eq 1 ]; then
err "Dawnline was not removed completely in ${_took}s"
else
ok "Dawnline removed in ${_took}s"
fi
[ -n "$BACKUP_PATH" ] && msg "Backup: $BACKUP_PATH (restore it in Dawnline → Settings → Backups after reinstalling)"
msg "Log: $LOG_FILE"
[ "$FAILED" -eq 0 ] || exit 1
}
main "$@"
+1
View File
@@ -2,3 +2,4 @@ node_modules/
coverage/
package-lock.json
src/portal/fonts/
src/admin/styles/*.css
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.3.0",
"version": "0.4.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.3.0",
"version": "0.4.2",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.3.0",
"version": "0.4.2",
"private": true,
"license": "MIT",
"type": "module",
+127 -75
View File
@@ -4,8 +4,10 @@
import type { Circle, Person, Server, Status } from '../shared/types';
import { E } from './e';
import { api, type HomeHost } from './api';
import { attempt, button, closeModal, confirmDialog, modal } from './ui';
import { input } from './kit';
import { button } from './ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
import { attempt } from './ui/toast';
import { chipToggle, input } from './ui/controls';
import { icon } from '../shared/icons';
type Service = Status['services'][number];
@@ -21,7 +23,7 @@ export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'l
/* ---------- Home services ---------- */
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => void) {
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => unknown) {
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: 'NAS' });
const addr = input(sv?.address ?? prefill.address ?? '', { placeholder: '192.168.1.10', class: 'cbi-input-text dl-mono' });
const ports = input((sv?.ports ?? prefill.ports ?? []).join(', '), {
@@ -34,7 +36,7 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
sv ? `Edit ${sv.name}` : 'Add service',
[field('Name', name), field('Address', addr), field('Ports', ports)],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Save',
@@ -88,59 +90,91 @@ function portGroups(h: HomeHost): [string, string[]][] {
return by.size ? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)]) : DEFAULT_PORTS;
}
/** Services shared by all servers, and the devices at home to add them from. */
export function homeServices(st: Status, serverId: string, reload: () => void): HTMLElement {
const services = st.services;
/** Home services as a live part of Server → Access: `update` repaints it from a new status. */
export interface HomeServices {
el: HTMLElement;
update(st: Status): void;
}
/**
* Services shared by all servers, and the devices at home to add them from.
* The devices are read once; `reload` refreshes the status after a change
* (the rest of the Access section, and what is typed there, stays).
*/
export function homeServices(initial: Status, serverId: string, reload: () => Promise<unknown>): HomeServices {
let st = initial;
let hosts: { hosts: HomeHost[]; mdns: boolean } | null = null;
let failed = false;
/** The "Add from devices at home" fold, once opened or closed by hand. */
let open: boolean | null = null;
/** Devices with a change on its way: a second click would add the service twice. */
const busy = new Set<string>();
const list = E('div', { class: 'dl-list' });
const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, 'Looking for devices at home…'));
const rows = services.length
? services.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
),
]),
button('Edit', () => serviceDialog(sv, {}, reload)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
)
reload();
},
'neutral',
{ title: 'Remove', 'aria-label': `Remove ${sv.name}` },
),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')];
const paintRows = () => {
const services = st.services;
dom.content(
list,
services.length
? services.map((sv) =>
E('div', { class: 'dl-row' }, [
icon('home'),
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, sv.name),
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
),
]),
button('Edit', () => serviceDialog(sv, {}, reload)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
)
await reload();
},
'neutral',
{ title: 'Remove', 'aria-label': `Remove ${sv.name}` },
),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')],
);
};
/** Ports chosen for a device: add, change or remove its service at once. */
async function choose(h: HomeHost, ports: string[] | null) {
const sv = services.find((s) => s.address === h.address);
const ok =
ports === null
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
: await attempt(
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
sv ? `${sv.name} updated` : `${h.name || h.address} added`,
);
if (ok) reload();
if (busy.has(h.address)) return;
busy.add(h.address);
paintPicker();
try {
const sv = st.services.find((s) => s.address === h.address);
const ok =
ports === null
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
: await attempt(
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
sv ? `${sv.name} updated` : `${h.name || h.address} added`,
);
if (ok) await reload();
} finally {
busy.delete(h.address);
paintPicker();
}
}
function hostRow(h: HomeHost): HTMLElement {
const sv = services.find((s) => s.address === h.address);
const sv = st.services.find((s) => s.address === h.address);
const all = !!sv && !sv.ports.length;
const chosen = new Set(sv?.ports ?? []);
const wait = busy.has(h.address);
const chip = (label: string, on: boolean, click: () => void) =>
E('button', { type: 'button', class: `dl-chipbtn${on ? ' on' : ''}`, 'aria-pressed': on ? 'true' : 'false', click }, label);
chipToggle(label, on, click, { disabled: wait ? 'disabled' : null, 'aria-busy': wait ? 'true' : null });
return E('div', { class: 'dl-row' }, [
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, h.name || h.address), E('span', { class: 'dl-mono dl-faint' }, h.address)]),
@@ -161,36 +195,46 @@ export function homeServices(st: Status, serverId: string, reload: () => void):
]);
}
function paintPicker() {
if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home."));
if (!hosts) return;
const r = hosts;
if (!r.hosts.length) return dom.content(picker, E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'));
// Open while there are no services yet (that is where they come from), then as left.
const fold = E('details', { class: 'dl-params', open: (open ?? !st.services.length) ? '' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Add from devices at home'),
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
r.mdns
? 'Ports they announce over Bonjour. Pick what to open, or all ports.'
: 'Devices that got an address from this router. Pick the ports to open, or all ports.',
),
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
]),
]);
fold.addEventListener('toggle', () => (open = (fold as HTMLDetailsElement).open));
dom.content(picker, fold);
}
api
.homeHosts(serverId)
.then((r) => {
const open = r.hosts.some((h) => services.some((s) => s.address === h.address)) && !services.length;
dom.content(
picker,
r.hosts.length
? E('details', { class: 'dl-params', open: open ? '' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Add from devices at home'),
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
r.mdns
? 'Ports they announce over Bonjour. Pick what to open, or all ports.'
: 'Devices that got an address from this router. Pick the ports to open, or all ports.',
),
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
]),
])
: E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'),
);
hosts = r;
paintPicker();
})
.catch(() => dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home.")));
.catch(() => {
failed = true;
paintPicker();
});
paintRows();
return E('div', { class: 'dl-stack gap8' }, [
const el = E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-iflead' }, [
E('div', { class: 'dl-iflead-row' }, [
E('b', {}, 'Home services'),
@@ -202,14 +246,22 @@ export function homeServices(st: Status, serverId: string, reload: () => void):
'Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.',
),
]),
E('div', { class: 'dl-list' }, rows),
list,
picker,
]);
return {
el,
update(n: Status) {
st = n;
paintRows();
paintPicker();
},
};
}
/* ---------- Circles ---------- */
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => void) {
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => unknown) {
const used = new Set(st.circles.filter((c) => c.server === serverId).map((c) => c.color));
let color = ci?.color ?? CIRCLE_COLORS.findIndex((_, i) => !used.has(i));
if (color < 0) color = 0;
@@ -287,7 +339,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
)
: '',
E('span', { class: 'dl-spacer' }),
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Save',
@@ -305,7 +357,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
}
/** The server's circles as chips (click to edit) and a round "+" to add one. */
export function circleChips(st: Status, serverId: string, onDone: () => void): HTMLElement {
export function circleChips(st: Status, serverId: string, onDone: () => unknown): HTMLElement {
const list = st.circles.filter((c) => c.server === serverId);
return E('div', { class: 'dl-chips-row dl-circles' }, [
...list.map((c) => {
+94 -28
View File
@@ -1,6 +1,6 @@
// luci.dawnline RPC bindings. The backend reports failures as { error }.
import type { AwgCaps, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
function call<T>(method: string, params: string[] = []) {
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
@@ -25,6 +25,7 @@ export interface SetupDefaults {
portal_port: number;
taken: string[];
awg: AwgCaps;
awg_state?: AwgState;
}
export interface Backup {
@@ -40,6 +41,12 @@ export interface UpdateComponent {
installed?: string | null;
latest?: string | null;
update?: boolean;
/** latest | outdated | dev (installed is newer than the release) | '' (unknown). */
status?: 'latest' | 'outdated' | 'dev' | '';
/** When this component was last checked. */
time?: number;
url?: string | null;
published?: string | null;
note?: string;
error?: string;
repo?: string;
@@ -78,24 +85,89 @@ export interface UpdatesStatus {
home?: boolean;
needs?: Needs;
check: { time: number; components: Record<string, UpdateComponent> } | null;
job: {
action: string;
component: string | null;
state: 'running' | 'done' | 'failed';
started: number;
finished: number | null;
phase: string;
log: string[];
error: string | null;
} | null;
job: UpdateJob | null;
/** Router time, for the job timer. */
now: number;
repo: string;
policy: UpdatePolicy;
/** Automatic runs: the last check and the last scheduled install day. */
auto: { check?: number; install_day?: string };
/** The version kept for Roll back, per component. */
kept: Record<'app' | 'amneziawg', { version: string; build: AwgSource | null; saved: number | null } | null>;
/** Components → Activity, newest first. */
history: UpdateEvent[];
/** AmneziaWG interfaces (their Dawnline names): switching builds restarts them. */
tunnels: string[];
}
/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link. */
export interface UpdateEvent {
ts: number;
/** found: a check found updates; install: an update ran; error: a check or an update failed. */
kind: 'found' | 'install' | 'error';
auto?: boolean;
items?: string[];
component?: string | null;
from?: string | null;
to?: string | null;
state?: 'done' | 'failed';
error?: string | null;
took?: number;
}
export interface UpdateJob {
id: string;
action: string;
component: string | null;
state: 'running' | 'done' | 'failed';
started: number;
finished: number | null;
/** Started by Settings → Updates, not by a click. */
auto?: boolean;
phase: string;
from: string | null;
to: string | null;
log: string[];
error: string | null;
result: Record<string, any> | null;
}
/** Settings → Updates. */
export interface UpdatePolicy {
check: boolean;
interval: '6h' | '12h' | '1d' | '7d';
auto: boolean;
mode: 'immediate' | 'scheduled';
time: string;
targets: ('app' | 'amneziawg' | 'packages')[];
keep: boolean;
mirrors: boolean;
}
export interface Release {
tag: string;
name: string;
published: string | null;
prerelease: boolean;
url: string | null;
body: string | null;
assets: string[];
}
/** Missing packages by feature: the portal's HTTPS, ACME certificates, the home-like link, AmneziaWG itself. */
export interface Needs {
https: string[];
acme: string[];
home: string[];
bonjour: string[];
/** amneziawg-tools and/or kmod-amneziawg (older backends leave it out). */
awg?: string[];
}
/** The slow part of the portal settings, loaded after the page shows. */
export interface PortalInfo {
/** Addresses the portal could use, found on the router. */
candidates: { host: string; kind: 'name' | 'ip'; ips: string[]; here: boolean; cloudflare: boolean; cert: boolean }[];
/** The portal's checks from Health. */
checks: HealthCheck[];
}
export interface SettingsData {
@@ -107,10 +179,6 @@ export interface SettingsData {
port_owners: string[];
wan443_taken?: boolean;
portal_public_port?: number;
/** Addresses the portal could use, found on the router. */
portal_candidates?: { host: string; kind: 'name' | 'ip'; ips: string[]; here: boolean; cloudflare: boolean; cert: boolean }[];
/** The portal's checks from Health. */
portal_checks?: HealthCheck[];
geo_cached: number;
logs: LogsInfo;
}
@@ -189,8 +257,6 @@ export interface InterfacesData {
mesh: MeshMode;
};
like_home: LikeHome;
/** Find home devices: published from umdns as DNS-SD records. */
bonjour: { on: boolean; needs: string[]; running: boolean; services: number };
effective: {
wan: { dev: string | null; zone: string; auto: boolean; missing: boolean };
home: { dev: string; auto: boolean; nets: string[]; zone: string | null; missing: boolean }[];
@@ -293,14 +359,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
return r;
}
const statusRaw = call<Status>('status', ['days']);
export let lastStatusAt = 0;
async function status(days?: number): Promise<Status> {
const st = await statusRaw(days);
lastStatusAt = Date.now();
return st;
}
const status = call<Status>('status', ['days']);
/** One line of the service log: tunnel and service starts, stops, watchdog repairs, errors. */
export interface ServiceLogEntry {
@@ -334,8 +393,10 @@ export interface ServiceLog {
export type Health = { checks: HealthCheck[] } & ServiceLog;
export const api = {
rev: call<{ rev: number }>('rev'),
personUpdate,
settingsGet: call<SettingsData>('settings_get'),
portalInfo: call<PortalInfo>('portal_info'),
settingsUpdate: call<SettingsData>('settings_update', ['values']),
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
serviceDelete: call<unknown>('service_delete', ['id']),
@@ -379,6 +440,8 @@ export const api = {
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
serverUpdate: call<unknown>('server_update', ['id', 'values']),
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']),
personCreate: call<{ id: string; link: string | null }>('person_create', [
'name',
'slug',
@@ -413,5 +476,8 @@ export const api = {
exportJson: call<Record<string, unknown>>('export'),
importJson: call<unknown>('import', ['data']),
updatesStatus: call<UpdatesStatus>('updates_status'),
updatesRun: call<{ started: boolean }>('updates_run', ['what']),
updatesRun: call<{ started: boolean; job: UpdateJob | null }>('updates_run', ['what']),
updatesReleases: call<{ releases: Release[]; page: number }>('updates_releases', ['page']),
updatesNotes: call<Release & { repo: string }>('updates_notes', ['component', 'tag', 'build']),
updatesChanges: call<{ items: string[] }>('updates_changes', ['from', 'to']),
};
-96
View File
@@ -1,96 +0,0 @@
// DOM bar charts with a hover tooltip (traffic per day, sparklines).
import type { DayUsage } from '../shared/types';
import { E } from './e';
import { bytes } from '../shared/format';
function dayLabel(day: string): string {
const [y, m, d] = day.split('-').map(Number);
return new Date(y, m - 1, d).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
}
/**
* Daily traffic bars (download stacked over upload, from the person's point
* of view: router tx = download). `top(day)` may name the busiest device.
*/
export function trafficBars(series: DayUsage[], height = 180, top?: (day: string) => string | null): HTMLElement {
const max = Math.max(1, ...series.map((d) => d.rx + d.tx));
const tip = E('div', { class: 'dl-tip' });
tip.style.display = 'none';
const bars = E('div', { class: 'dl-bars' });
bars.style.height = `${height}px`;
series.forEach((d) => {
const total = d.rx + d.tx;
const col = E('div', { class: 'dl-bar' }, [E('i', { class: 'down' }), E('i', { class: 'up' })]);
(col.children[0] as HTMLElement).style.height = `${(d.tx / max) * 100}%`;
(col.children[1] as HTMLElement).style.height = `${(d.rx / max) * 100}%`;
if (!total) col.classList.add('empty');
col.addEventListener('mouseenter', () => {
const t = top?.(d.day);
tip.replaceChildren(
E('div', { class: 'dl-tip-title' }, dayLabel(d.day)),
E('div', { class: 'dl-muted' }, `↓ ${bytes(d.tx)} · ↑ ${bytes(d.rx)}`),
t ? E('div', { class: 'dl-faint' }, `Top: ${t}`) : '',
);
tip.style.display = '';
const r = col.getBoundingClientRect();
const host = bars.getBoundingClientRect();
const x = r.left - host.left + r.width / 2;
tip.style.left = `${Math.min(Math.max(x, 70), host.width - 70)}px`;
});
bars.appendChild(col);
});
bars.addEventListener('mouseleave', () => (tip.style.display = 'none'));
const first = series[0]?.day;
return E('div', { class: 'dl-chartbox' }, [
bars,
tip,
E('div', { class: 'dl-axis' }, [E('span', {}, first ? dayLabel(first) : ''), E('span', {}, 'Today')]),
]);
}
let floating: HTMLElement | null = null;
/** Floating tooltip that follows the pointer (for small charts and meters). */
export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
const show = (ev: MouseEvent) => {
floating ??= document.body.appendChild(E('div', { class: 'dl-tip dl-tip-float dl-root' }));
floating.replaceChildren(...content().map((c) => (typeof c === 'string' ? document.createTextNode(c) : c)));
floating.style.display = '';
floating.style.left = `${ev.clientX}px`;
floating.style.top = `${ev.clientY - 10}px`;
};
el.addEventListener('mouseenter', show);
el.addEventListener('mousemove', show);
el.addEventListener('mouseleave', () => floating && (floating.style.display = 'none'));
}
/** Tiny daily sparkline (oldest first, the last bar is today) with per-day tooltips. */
export function spark(values: number[], width = 120, height = 26): HTMLElement {
const max = Math.max(1, ...values);
const el = E('div', { class: 'dl-spark' });
el.style.width = `${width}px`;
el.style.height = `${height}px`;
const now = Date.now();
values.forEach((v, i) => {
const b = E('i');
b.style.height = `${Math.max(6, (v / max) * 100)}%`;
if (!v) b.classList.add('zero');
const back = values.length - 1 - i;
const d = new Date(now - back * 86400000);
attachTip(b, () => [
E(
'div',
{ class: 'dl-tip-title' },
back === 0
? 'Today'
: back === 1
? 'Yesterday'
: d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }),
),
E('div', { class: 'dl-muted' }, bytes(v)),
]);
el.appendChild(b);
});
return el;
}
+389
View File
@@ -0,0 +1,389 @@
// The AmneziaWG core in the admin: how a device connects (.conf, AmneziaVPN
// key, QR), the disguise and its parameters, and the core's own settings on
// Server → AmneziaWG. Plain WireGuard is AmneziaWG with the disguise off.
import type { AwgConfig, Server, Status } from '../../shared/types';
import { E } from '../e';
import { api } from '../api';
import { button } from '../ui/button';
import { confirmDialog } from '../ui/modal';
import { copyText, downloadFile } from '../ui/files';
import { attempt, notify } from '../ui/toast';
import { input } from '../ui/controls';
import { callout, card, group, row, svg } from '../ui/layout';
import { qrSvg } from '../../shared/qr';
import { vpnKey } from '../../shared/vpnkey';
import { icon } from '../../shared/icons';
import { methodInfo, methodPicker, type Method } from '../disguise';
import { coreHead, type Core, type CoreCtx } from './common';
/** `.conf` names of the disguise parameters, in file order. */
const CONF: [string, string][] = [
['jc', 'Jc'],
['jmin', 'Jmin'],
['jmax', 'Jmax'],
['s1', 'S1'],
['s2', 'S2'],
['s3', 'S3'],
['s4', 'S4'],
['h1', 'H1'],
['h2', 'H2'],
['h3', 'H3'],
['h4', 'H4'],
['i1', 'I1'],
['i2', 'I2'],
['i3', 'I3'],
['i4', 'I4'],
['i5', 'I5'],
['header_protection_key', 'HeaderProtectionKey'],
['content_padding_addition', 'ContentPaddingAddition'],
['rekey_after_time', 'RekeyAfterTime'],
['rekey_timeout', 'RekeyTimeout'],
['reject_after_time', 'RejectAfterTime'],
['keepalive_timeout', 'KeepaliveTimeout'],
['max_handshake_attempts', 'MaxHandshakeAttempts'],
['random_trailers', 'RandomTrailers'],
['disable_cookies', 'DisableCookies'],
];
/**
* The applied parameters, grouped by what they do, with a plain-language
* line per group. Collapsed by default; copyable as config lines.
*/
function paramsView(o: Record<string, string>): HTMLElement | null {
const has = (k: string) => o[k] != null && o[k] !== '';
const keys = CONF.filter(([k]) => has(k));
if (!keys.length) return null;
const val = (k: string, name: string) =>
E('span', { class: 'dl-pv' }, [E('i', {}, name), E('b', {}, k === 'header_protection_key' ? `${o[k].slice(0, 6)}••••` : o[k])]);
const group = (title: string, ic: string, text: string, ks: string[]) => {
const present = CONF.filter(([k]) => ks.includes(k) && has(k));
return present.length
? E('div', { class: 'dl-pgroup' }, [
E('div', { class: 'dl-pgroup-head' }, [icon(ic), E('b', {}, title)]),
E('p', {}, text),
E(
'div',
{ class: 'dl-pvals' },
present.map(([k, n]) => val(k, n)),
),
])
: '';
};
const jc = Number(o.jc || 0);
const signature = (o.i1 ?? '').includes('0x8580')
? 'A first packet shaped like a DNS answer.'
: 'Extra packets sent before the handshake.';
const conf = keys.map(([k, n]) => `${n} = ${o[k]}`).join('\n');
const body = E('div', { class: 'dl-pgrid' }, [
group(
'Junk packets',
'zap',
jc ? `${jc} random packet${jc === 1 ? '' : 's'} of ${o.jmin}–${o.jmax} bytes before each handshake.` : 'No junk packets.',
['jc', 'jmin', 'jmax'],
),
group('Padding', 'archive', 'Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.', [
's1',
's2',
's3',
's4',
]),
group('Packet types', 'key', 'The values that replace WireGuard’s recognisable message types.', ['h1', 'h2', 'h3', 'h4']),
group('Signatures', 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']),
group('Protection', 'lock', 'AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.', [
'header_protection_key',
'content_padding_addition',
'random_trailers',
'disable_cookies',
]),
group('Timing', 'clock', 'Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.', [
'rekey_after_time',
'rekey_timeout',
'reject_after_time',
'keepalive_timeout',
'max_handshake_attempts',
]),
]);
return E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Current parameters'),
E('span', { class: 'dl-pcount' }, String(keys.length)),
E('span', { class: 'dl-spacer' }),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(conf, 'Parameters copied');
},
},
'Copy as config',
),
]),
body,
]);
}
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): Node {
if (/^\s*\[.+\]\s*$/.test(line)) return E('span', { class: 'dl-conf-sec' }, line);
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
if (!m) return document.createTextNode(line);
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
return E('span', {}, [
E('span', { class: 'dl-conf-k' }, m[1]),
' ',
secret && !reveal ? E('span', { class: 'dl-conf-mask' }, '••••••••••••••••') : m[2],
]);
}
/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */
function fileCard(cfg: AwgConfig): HTMLElement {
let reveal = false;
const pre = E('pre', { class: 'dl-conf' });
const paint = () =>
dom.content(
pre,
cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])),
);
const eye = E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
reveal = !reveal;
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']);
paint();
},
},
[icon('key'), 'Show key'],
);
paint();
const size = new Blob([cfg.conf]).size;
return E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-filecard' }, [
E('span', { class: 'dl-filecard-ic' }, '.conf'),
E('span', { class: 'dl-stack' }, [
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes · import it in the app`),
]),
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Configuration'),
E('span', { class: 'dl-spacer' }),
eye,
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(cfg.conf, 'Configuration copied');
},
},
[icon('copy'), 'Copy'],
),
]),
pre,
]),
]);
}
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
return E(
'div',
{ class: 'dl-hint' },
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
);
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`);
const panes: Record<string, () => Node> = {
qr: () =>
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(cfg.conf), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button('Copy', () => copyText(key, 'Key copied'))]),
E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'),
]),
file: () => fileCard(cfg),
};
const body = E('div', { class: 'dl-connect-body' });
const seg = E('div', { class: 'dl-seg' });
const show = (id: string) => {
seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id));
dom.content(body, panes[id]());
};
for (const [id, label] of [
['file', 'File'],
['key', 'Key'],
['qr', 'QR code'],
])
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
show(initial);
return E('div', { class: 'dl-stack gap12' }, [seg, body]);
}
/** Switch the disguise (every device imports its configuration again). */
async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean) {
const info = methodInfo(m)!;
const people = ctx.st.people.filter((p) => p.server === srv.id);
const devices = people.reduce((n, p) => n + p.devices.length, 0);
const ok = await confirmDialog(
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
`${devices} AmneziaWG device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : ''}`,
same ? 'Generate and apply' : 'Switch and apply',
true,
);
if (!ok) return;
if (await attempt(() => api.serverObfuscation(srv.id, m), same ? 'New values applied' : `${info.title} applied`)) {
notify('Devices are marked “Update config” until they import again.', 'info', 6000);
await ctx.refresh();
}
}
/** Server → AmneziaWG: listening port, what goes into every configuration, disguise, tunnel. */
export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
const st: Status = ctx.st;
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const mtu = input(String(srv.mtu ?? ''), { placeholder: '1380', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
let selected: Method = current ?? 'standard';
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
const label = () =>
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
label();
const devs = st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
const tools = st.awg_state?.tools !== false;
return card(
'',
[
coreHead(
'AmneziaWG',
srv.up ? 'ok' : 'bad',
srv.up ? 'Running' : 'Not running',
`${srv.ifname} · ${devs} device${devs === 1 ? '' : 's'}`,
),
group('globe', 'Listening', 'Where devices reach this core from the internet', [
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
row('MTU', mtu, 'Lower it if some sites hang on mobile networks.'),
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
methodPicker(
st.awg,
selected,
(m) => {
selected = m;
label();
},
current,
tools,
),
// Only about an installed AmneziaWG: without one the server page says what to install.
tools && !st.awg.v3
? callout('info', [
'This router runs an older AmneziaWG. ',
E('b', {}, 'Maximum'),
' becomes available with kmod-amneziawg and amneziawg-tools 3.1.',
])
: '',
paramsView(srv.obf ?? {}) ?? '',
E('div', { class: 'dl-row-end' }, [
E('span', { class: 'dl-sub' }, 'Applies at once: every AmneziaWG device imports its configuration again.'),
apply,
]),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Tunnel'), E('span', { class: 'dl-pcount' }, '3')]),
E('div', { class: 'dl-params-body' }, [
row('Interface', E('span', { class: 'dl-mono' }, `${srv.ifname} · router ${srv.address}`)),
row('Tunnel subnet', E('span', { class: 'dl-mono' }, srv.subnet), 'Device addresses come from it.'),
row(
'Server public key',
E('span', { class: 'dl-keyrow' }, [
E('code', { class: 'dl-mono' }, srv.public_key),
button([icon('copy')], () => copyText(srv.public_key, 'Public key copied'), 'neutral', {
title: 'Copy',
class: 'cbi-button cbi-button-neutral dl-icon-only sm',
}),
]),
),
]),
]),
],
[
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
button('Save', () => ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved'), 'positive'),
],
);
}
/** Overview: the disguise in use, its stealth and speed, and the values devices carry in words. */
function overviewTile(srv: Server): HTMLElement {
const m = methodInfo(srv.preset);
const o = srv.obf ?? {};
const segs = (n: number, cls: string) =>
E(
'span',
{ class: `dl-segs ${cls}` },
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
);
const chips: string[] = [];
if (+o.jc) chips.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);
const pad = ['s1', 's2', 's3', 's4'].filter((k) => +o[k]).map((k) => `${k.toUpperCase()} ${o[k]}`);
if (pad.length) chips.push(pad.slice(0, 2).join(' · ') + (pad.length > 2 ? ` +${pad.length - 2}` : ''));
if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push('H1–H4 random');
if (o.i1) chips.push(o.i1.includes('0x8580') ? 'DNS-like first packet' : 'Signature packets');
if (o.header_protection_key) chips.push('Encrypted headers');
if (!chips.length) chips.push(m?.id === 'off' ? 'Plain WireGuard' : 'No values yet');
return E('div', { class: 'dl-bento-tile dl-disg' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-metric-label' }, 'Disguise'),
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, 'Change'),
]),
E('div', { class: 'dl-disg-id' }, [
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [E('b', {}, m ? m.title : 'Custom'), E('span', { class: 'dl-sub' }, m ? m.short : 'Set by hand')]),
]),
m
? E('div', { class: 'dl-disg-meters' }, [
E('span', {}, 'Stealth'),
segs(m.stealth, 'acc'),
E('span', {}, 'Speed'),
segs(m.speed, 'ok'),
])
: '',
E(
'div',
{ class: 'dl-disg-chips' },
chips.map((c) => E('span', {}, c)),
),
]);
}
export const awg: Core = {
id: 'awg',
label: 'AmneziaWG',
settingsCard,
overviewTile,
connectBlock,
qrText: (cfg) => cfg.conf,
appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`) },
file: { label: 'Download .conf', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) },
};
+41
View File
@@ -0,0 +1,41 @@
// What every tunnel core gives the admin (cores/index.ts holds the registry),
// what a core's settings card gets from the Server page, and that card's head.
import type { ClientConfig, Server, Status } from '../../shared/types';
import { E } from '../e';
/** What the Server page hands a core's settings card. */
export interface CoreCtx {
st: Status;
/** server_update with these values, then refresh. */
save: (values: Record<string, unknown>, ok?: string) => Promise<void>;
refresh: () => Promise<void>;
}
/** A tunnel core (AmneziaWG today): its name and the pieces of the admin that differ per core. */
export interface Core {
id: string;
/** "AmneziaWG": the server section, the address bar, the settings card. */
label: string;
/** Server → <label>: the core's own settings. */
settingsCard(ctx: CoreCtx, srv: Server): HTMLElement;
/** Overview: how the tunnel looks on the wire (the disguise tile). */
overviewTile(srv: Server): HTMLElement;
/** How a device connects: file / key / QR. */
connectBlock(cfg: ClientConfig, initial?: 'file' | 'key' | 'qr'): Promise<HTMLElement>;
/** What a QR code for the device carries. */
qrText(cfg: ClientConfig): string;
/** The key the device's app imports (⋯ → Copy key), with the menu label. */
appKey?: { label: string; make(cfg: ClientConfig): Promise<string> };
/** The config file the device imports, with the menu label. */
file: { label: string; make(cfg: ClientConfig): { name: string; text: string } };
}
/** Name, state pill and a short line: the head of a core's settings card. */
export function coreHead(title: string, tone: 'ok' | 'bad' | 'off' | '', state: string, sub: string): HTMLElement {
return E('div', { class: 'dl-corehead' }, [
E('h3', {}, title),
E('span', { class: `dl-pill ${tone}` }, state),
sub ? E('span', { class: 'dl-sub' }, sub) : '',
]);
}
+21
View File
@@ -0,0 +1,21 @@
// Tunnel cores by id. A server names its core (`core`, AmneziaWG when absent);
// the Server, device and person pages ask the registry instead of importing a
// core directly, so another core (VLESS/Xray) plugs in here.
import type { Server } from '../../shared/types';
import type { Core } from './common';
import { awg } from './awg';
export type { Core, CoreCtx } from './common';
const CORES: Record<string, Core> = { awg };
/** The core of a server (or of the server a person is on). */
export function coreOf(srv?: Pick<Server, 'core'> | null): Core {
return CORES[srv?.core || 'awg'] ?? awg;
}
/** The core of a person's server. */
export function coreFor(servers: Server[], serverId: string): Core {
return coreOf(servers.find((s) => s.id === serverId));
}
+5
View File
@@ -0,0 +1,5 @@
// Stylesheets are imported as text (tsup: loader '.css' → 'text').
declare module '*.css' {
const css: string;
export default css;
}
+185 -201
View File
@@ -1,21 +1,42 @@
// Device drawer: a right-hand panel with the device's status, connection
// (QR / key / file), details and actions. Replaces the old tabbed modal.
// (QR / key / file, from its server's core), details and actions; the ⋯ menu
// on a device card; and the admin's Add device dialog.
import type { ClientConfig, Device, Geo, Kind, LogEvent, Person } from '../shared/types';
import type { Device, Geo, Kind, LogEvent, Person } from '../shared/types';
import { E } from './e';
import { api } from './api';
import { attempt, button, closeModal, confirmDialog, copyText, downloadFile, modal, notify, svg } from './ui';
import { button } from './ui/button';
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
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 { deviceStatus } from './ui/badges';
import { qrSvg } from '../shared/qr';
import { vpnKey } from '../shared/vpnkey';
import { ago, bytes, KIND_LABEL, KINDS } from '../shared/format';
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
import { icon } from '../shared/icons';
import { eventBy } from './pages/overview';
import { spark } from './charts';
import { eventBy } from './events/model';
import { spark } from './widgets/spark';
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
import { coreFor, coreOf, type Core } from './cores';
import { onLiveChange } from './state/live';
let current: { close: () => void } | null = null;
/** What the page that opens a device hands over. */
export interface DeviceOpts {
/** Reload the page after a change made here. */
refresh: () => unknown;
geo?: Geo;
/** The router's clock (seconds) and day, for "5 min ago" and the chart labels. */
now?: number;
today?: string;
/** The device's server's core (AmneziaWG when not given). */
core?: Core;
/** The page's activity log, when it keeps one: the drawer reads it instead of fetching its own. */
events?: () => LogEvent[] | null;
}
function iso(ts: number): string {
function when(ts: number): string {
return ts
? new Date(ts * 1000).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
: '—';
@@ -36,154 +57,6 @@ function row(label: string, value: Node | string): HTMLElement {
return E('div', { class: 'dl-kvrow' }, [E('span', { class: 'dl-kvrow-k' }, label), E('span', { class: 'dl-kvrow-v' }, value)]);
}
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
function confLine(line: string, reveal: boolean): Node {
if (/^\s*\[.+\]\s*$/.test(line)) return E('span', { class: 'dl-conf-sec' }, line);
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
if (!m) return document.createTextNode(line);
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
return E('span', {}, [
E('span', { class: 'dl-conf-k' }, m[1]),
' ',
secret && !reveal ? E('span', { class: 'dl-conf-mask' }, '••••••••••••••••') : m[2],
]);
}
/** The .conf as a file card (download) and a folded, highlighted view with copy and a hidden key. */
function fileCard(cfg: ClientConfig): HTMLElement {
let reveal = false;
const pre = E('pre', { class: 'dl-conf' });
const paint = () =>
dom.content(
pre,
cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])),
);
const eye = E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
reveal = !reveal;
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']);
paint();
},
},
[icon('key'), 'Show key'],
);
paint();
const size = new Blob([cfg.conf]).size;
return E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-filecard' }, [
E('span', { class: 'dl-filecard-ic' }, '.conf'),
E('span', { class: 'dl-stack' }, [
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes · import it in the app`),
]),
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Configuration'),
E('span', { class: 'dl-spacer' }),
eye,
E(
'button',
{
type: 'button',
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(cfg.conf, 'Configuration copied');
},
},
[icon('copy'), 'Copy'],
),
]),
pre,
]),
]);
}
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
export async function connectBlock(cfg: ClientConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
if (!cfg.has_private_key)
return E(
'div',
{ class: 'dl-hint' },
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
);
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`);
const panes: Record<string, () => Node> = {
qr: () =>
E('div', { class: 'dl-qr-pane' }, [
svg(qrSvg(cfg.conf), 'dl-qr'),
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button('Copy', () => copyText(key, 'Key copied'))]),
E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'),
]),
file: () => fileCard(cfg),
};
const body = E('div', { class: 'dl-connect-body' });
const seg = E('div', { class: 'dl-seg' });
const show = (id: string) => {
seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id));
dom.content(body, panes[id]());
};
for (const [id, label] of [
['file', 'File'],
['key', 'Key'],
['qr', 'QR code'],
])
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
show(initial);
return E('div', { class: 'dl-stack gap12' }, [seg, body]);
}
function drawer(title: Node, body: Node, foot: Node | null, onClose: () => void): { close: () => void; panel: HTMLElement } {
current?.close();
const panel = E('aside', { class: 'dl-drawer', role: 'dialog', 'aria-modal': 'true' }, [
E('div', { class: 'dl-drawer-head' }, [
title,
E('button', { type: 'button', class: 'dl-drawer-x', 'aria-label': 'Close', click: () => close() }, icon('x')),
]),
E('div', { class: 'dl-drawer-body' }, body),
foot ? E('div', { class: 'dl-drawer-foot' }, foot) : '',
]);
const overlay = E(
'div',
{
class: 'dl-drawer-overlay dl-root',
click: (ev: Event) => {
if (ev.target === overlay) close();
},
},
panel,
);
const onKey = (ev: KeyboardEvent) => {
// LuCI keeps an empty .modal in the page; the body class says whether one is open.
if (ev.key === 'Escape' && !document.body.classList.contains('modal-overlay-active')) close();
};
function close() {
document.removeEventListener('keydown', onKey);
overlay.classList.remove('open');
setTimeout(() => overlay.remove(), 220);
if (current === handle) current = null;
onClose();
}
const handle = { close, panel };
document.addEventListener('keydown', onKey);
document.body.appendChild(overlay);
requestAnimationFrame(() => overlay.classList.add('open'));
current = handle;
return handle;
}
const DEV_EVENT: Record<string, [string, string, string]> = {
connect: ['ok', 'Connected', 'plug'],
disconnect: ['', 'Went offline', 'plug'],
@@ -194,7 +67,7 @@ const DEV_EVENT: Record<string, [string, string, string]> = {
};
/** Activity of one device, newest first. */
function deviceEvents(events: LogEvent[], id: string): HTMLElement {
function deviceEvents(events: LogEvent[], id: string, now?: number): HTMLElement {
const mine = events
.filter((e) => e.device === id && DEV_EVENT[e.type])
.reverse()
@@ -223,37 +96,47 @@ function deviceEvents(events: LogEvent[], id: string): HTMLElement {
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts)),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts, now)),
]);
}),
);
}
function statusLine(d: Device): HTMLElement {
// Status as coloured text, no dots (only avatars carry one).
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
if (!d.handshake) return E('span', { class: 'dl-dstat warn' }, 'Waiting for the first connection');
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake)}`);
/** Open the drawer of a device that was just made or changed, with fresh status. */
async function reopen(personId: string, deviceId: string, o: DeviceOpts) {
const st = await api.status(1).catch(() => null);
const p2 = st?.people.find((x) => x.id === personId);
const d2 = p2?.devices.find((x) => x.id === deviceId);
if (st && p2 && d2)
void openDevice(p2, d2, { ...o, geo: st.geo, now: st.now, today: todayOf(st.series), core: coreFor(st.servers, p2.server) });
}
/** Device drawer; `refresh` reloads the page after changes. */
export async function openDevice(person: Person, dev: Device, refresh: () => unknown, geo?: Geo) {
/** Device drawer. */
export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const cfg = await attempt(() => api.deviceConfig(dev.id));
if (!cfg) return;
const core = o.core ?? coreOf(null);
let d = dev;
let p = person;
const connect = await connectBlock(cfg);
let geo = o.geo;
let now = o.now;
let today = o.today ?? isoDay(new Date());
const connect = await core.connectBlock(cfg);
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
const log = E('div', {}, E('div', { class: 'dl-sub' }, 'Loading…'));
let logEvents: LogEvent[] = [];
const loadLog = async () => {
const showLog = (events: LogEvent[]) => {
logEvents = events.filter((e) => e.device === d.id);
dom.content(log, deviceEvents(events, d.id, now));
};
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */
const loadLog = async (force = false) => {
const own = o.events?.();
if (own && !force) return showLog(own);
const ev = await api.events(5000).catch(() => null);
if (!ev) return;
logEvents = ev.events.filter((e) => e.device === d.id);
dom.content(log, deviceEvents(ev.events, d.id));
if (ev) showLog(ev.events);
};
const paint = () => {
@@ -265,14 +148,17 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
E('h3', {}, d.name),
button([icon('edit')], () => rename(), 'neutral', { title: 'Rename', class: 'cbi-button cbi-button-neutral dl-icon-only sm' }),
]),
E('span', { class: 'dl-sub' }, [`${p.name} · ${KIND_LABEL[d.kind]}`]),
E('span', { class: 'dl-sub' }, `${p.name} · ${KIND_LABEL[d.kind]}`),
]),
]);
const week = d.spark.reduce((a, b) => a + b, 0);
dom.content(
stats,
E('div', { class: 'dl-dstats' }, [
E('div', { class: 'dl-dstats-cell wide' }, [E('span', { class: 'dl-metric-label' }, 'Status'), statusLine(d)]),
E('div', { class: 'dl-dstats-cell wide' }, [
E('span', { class: 'dl-metric-label' }, 'Status'),
deviceStatus(d, now, 'Waiting for the first connection'),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'This month'),
E('b', {}, bytes(d.month[0] + d.month[1])),
@@ -281,7 +167,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'Last 7 days'),
E('b', {}, bytes(week)),
spark(d.spark, 120, 22),
spark(d.spark, 120, 22, today),
]),
]),
);
@@ -308,13 +194,13 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(reload, 300)),
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(changed, 300)),
},
'Reset',
),
]),
),
row('Added', `${iso(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
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)}…` : '—'),
@@ -326,7 +212,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
[icon(d.disabled ? 'play' : 'pause'), d.disabled ? ' Enable' : ' Disable'],
async () => {
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled'))
await reload();
await changed();
},
'neutral',
d.disabled ? {} : { class: 'cbi-button cbi-button-neutral dl-btn-warn' },
@@ -343,12 +229,9 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
return;
const c = await attempt(() => api.deviceRotate(d.id), 'New keys generated');
if (c) {
refresh();
o.refresh();
handle.close();
const st = await api.status(1);
const p2 = st.people.find((x) => x.id === p.id);
const d2 = p2?.devices.find((x) => x.id === d.id);
if (p2 && d2) openDevice(p2, d2, refresh, st.geo);
await reopen(p.id, d.id, o);
}
}),
E('span', { class: 'dl-spacer' }),
@@ -366,7 +249,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
return;
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) {
handle.close();
refresh();
o.refresh();
}
},
'negative',
@@ -374,6 +257,7 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
]);
};
/** The device's own state, fresh from the router; the page underneath is left alone. */
const reload = async () => {
const st = await api.status(1).catch(() => null);
const p2 = st?.people.find((x) => x.id === p.id);
@@ -382,8 +266,14 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
p = p2;
d = d2;
geo = st.geo;
now = st.now;
today = todayOf(st.series);
paint();
refresh();
};
/** After a change made here: this drawer and the page. */
const changed = async () => {
await reload();
o.refresh();
};
const rename = () => {
@@ -392,14 +282,14 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
`Rename ${d.name}`,
[E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Save',
async () => {
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
closeModal();
await reload();
await changed();
}
},
'positive',
@@ -435,7 +325,11 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
{
type: 'button',
class: 'dl-linkbtn danger',
click: () => clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, loadLog),
click: () =>
clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, () => {
void loadLog(true);
o.refresh();
}),
},
'Clear',
),
@@ -453,17 +347,110 @@ export async function openDevice(person: Person, dev: Device, refresh: () => unk
{ class: 'dl-stack gap16' },
setUp ? [stats, connectSec, detailsSec, activitySec] : [stats, detailsSec, activitySec, connectSec],
);
loadLog();
const watch = window.setInterval(() => {
reload();
loadLog();
}, 8000);
const handle = drawer(titleEl, body, foot, () => clearInterval(watch));
void loadLog();
// Live status and log: at once when something happens (state/live.ts), and every 30 s anyway.
const live = () => {
void reload();
void loadLog();
};
const off = onLiveChange(live);
const watch = window.setInterval(live, 30000);
const handle = drawer(titleEl, body, foot, () => {
clearInterval(watch);
off();
});
paint();
}
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOpts) {
const core = o.core ?? coreOf(null);
const cfg = () => attempt(() => api.deviceConfig(d.id));
const items: (MenuItem | null)[] = [
{
label: 'Show QR code',
icon: icon('qr'),
run: async () => {
const c = await cfg();
if (!c) return;
modal(
`${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.'),
]),
cancelButton('Close'),
);
},
},
{
label: core.file.label,
icon: icon('download'),
run: async () => {
const c = await cfg();
if (!c) return;
const f = core.file.make(c);
downloadFile(f.name, f.text, 'application/octet-stream');
},
},
core.appKey
? {
label: core.appKey.label,
icon: icon('copy'),
run: async () => {
const c = await cfg();
if (c) copyText(await core.appKey!.make(c), 'Key copied');
},
}
: null,
null,
{ label: 'Rename', icon: icon('edit'), run: () => openDevice(p, d, o) },
{
label: 'New keys',
icon: icon('key'),
run: async () => {
if (
await confirmDialog(
'Generate new keys?',
'The current configuration on this device stops working until it is imported again.',
'Generate',
true,
)
)
if (await attempt(() => api.deviceRotate(d.id), 'New keys generated')) o.refresh();
},
},
{
label: d.disabled ? 'Enable' : 'Disable',
icon: icon(d.disabled ? 'play' : 'pause'),
warn: !d.disabled,
run: async () => {
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled'))
o.refresh();
},
},
{
label: 'Delete',
icon: icon('trash'),
danger: true,
run: async () => {
if (
await confirmDialog(
`Remove ${d.name}?`,
'The device is disconnected immediately and its configuration stops working.',
'Remove',
true,
)
)
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) o.refresh();
},
},
];
dropdown(anchor, items);
}
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
export function addDevice(person: Person, refresh: () => unknown) {
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;
let kind: Kind = 'phone';
const kinds = E(
@@ -507,7 +494,7 @@ export function addDevice(person: Person, refresh: () => unknown) {
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Name'), nameInput]),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Add device',
@@ -517,11 +504,8 @@ export function addDevice(person: Person, refresh: () => unknown) {
if (!r) return;
closeModal();
notify(`${name} added`, 'success', 3000);
refresh();
const st = await api.status(1);
const p2 = st.people.find((x) => x.id === person.id);
const d2 = p2?.devices.find((x) => x.id === r.id);
if (p2 && d2) openDevice(p2, d2, refresh, st.geo);
o.refresh();
await reopen(person.id, r.id, o);
},
'positive',
),
+15 -2
View File
@@ -73,6 +73,12 @@ const NEEDS: Record<keyof AwgCaps, string> = {
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> = {
v2: 'Needs AmneziaWG on the router.',
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
};
function dots(n: number, label: string): HTMLElement {
return E('span', { class: 'dl-dots', title: `${label}: ${n} of 4` }, [
E('span', { class: 'dl-dots-label' }, label),
@@ -87,8 +93,15 @@ function dots(n: number, label: string): HTMLElement {
/**
* Method cards. `current` gets a badge; unavailable methods stay visible but
* disabled with the reason, so it is clear what an upgrade would bring.
* `installed` is false while the router has no AmneziaWG tools at all.
*/
export function methodPicker(caps: AwgCaps, selected: Method, onSelect: (m: Method) => void, current?: string): HTMLElement {
export function methodPicker(
caps: AwgCaps,
selected: Method,
onSelect: (m: Method) => void,
current?: string,
installed = true,
): HTMLElement {
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': 'Disguise method' });
const paint = () =>
dom.content(
@@ -122,7 +135,7 @@ export function methodPicker(caps: AwgCaps, selected: Method, onSelect: (m: Meth
E(
'div',
{ class: 'dl-method-foot' },
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, NEEDS[m.needs!])],
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
),
],
);
+12
View File
@@ -0,0 +1,12 @@
// CSV for the log export. Cells a spreadsheet would run as a formula (= + - @,
// tab, CR) get a leading apostrophe; quotes, commas and line breaks are quoted.
export function csvCell(v: unknown): string {
let s = v == null ? '' : String(v);
if (/^[=+\-@\t\r]/.test(s)) s = `'${s}`;
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
export function toCsv<K extends string>(cols: readonly K[], rows: Record<K, unknown>[]): string {
return [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
}
+74
View File
@@ -0,0 +1,74 @@
// The activity log's vocabulary: categories, who did what, problems, retention.
// No DOM and no RPC here (see ./render for rows).
import type { LogEvent } from '../../shared/types';
import type { LogCategory, LogsInfo, ServiceLogEntry } from '../api';
/** Mirrors CATEGORY in dawnline.live. */
const CATEGORY: Record<string, LogCategory> = {
connect: 'connections',
disconnect: 'connections',
roam: 'connections',
device_added: 'people',
device_removed: 'people',
devices_removed: 'people',
device_changed: 'people',
device_keys: 'people',
link_changed: 'people',
person_added: 'people',
person_removed: 'people',
person_changed: 'people',
paused: 'people',
resumed: 'people',
paused_all: 'people',
resumed_all: 'people',
portal_blocked: 'problems',
};
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
export const CATEGORY_LABEL: Record<LogCategory, string> = {
connections: 'Connections',
people: 'People',
problems: 'Problems',
};
export const CATEGORY_HELP: Record<LogCategory, string> = {
connections: 'Connects, disconnects and IP changes',
people: 'People and their devices added, changed, paused, removed',
problems: 'Blocked portal sign-ins (tunnels and services are in the service log)',
};
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed', 'paused_all', 'resumed_all'];
/** Who did it. Older events have no `by`: LuCI and the portal marked it in the detail. */
export function eventBy(e: LogEvent): 'admin' | 'portal' | null {
if (e.by) return e.by;
if (ADMIN_TYPES.includes(e.type) || e.detail === 'by admin' || e.detail?.endsWith(' (admin)')) return 'admin';
if (e.detail?.endsWith(' (portal)')) return 'portal';
return null;
}
/** The detail without the old "(admin)" / "(portal)" / "by admin" marks. */
export function plainDetail(e: LogEvent): string {
return (e.detail ?? '').replace(/ \((admin|portal)\)$/, '').replace(/^by admin$/, '');
}
/** One line of the Log: an activity event or a service log entry. */
export type LogItem = { ts: number; ev?: LogEvent; sys?: ServiceLogEntry };
export const isProblem = (x: LogItem) =>
x.sys ? ['error', 'repair', 'down'].includes(x.sys.level) : categoryOf(x.ev!.type) === 'problems';
export function retentionText(p: LogsInfo['policy']): string {
const age = p.keep_days > 0 ? `${p.keep_days} day${p.keep_days === 1 ? '' : 's'}` : 'no age limit';
const where =
p.persist === 'off'
? 'kept in memory only (lost on reboot)'
: `saved to flash ${p.persist === '10min' ? 'every 10 minutes' : 'hourly'}`;
return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`;
}
+256
View File
@@ -0,0 +1,256 @@
// Log rows: an activity event as a sentence ("You added device Phone for
// Myata"), its tile and time, and a service log line.
import type { LogEvent, Status } from '../../shared/types';
import type { ServiceLogEntry } from '../api';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ago } from '../../shared/format';
import { SYSTEM_SOURCE, eventBy, plainDetail } from './model';
/** What the people and servers in the log are called now. */
export type Names = Pick<Status, 'people' | 'servers'>;
const EVENT_TONE: Record<string, string> = {
connect: 'ok',
disconnect: '',
roam: '',
device_added: 'ok',
device_removed: '',
person_added: '',
person_removed: '',
paused: 'warn',
resumed: 'ok',
paused_all: 'warn',
resumed_all: 'ok',
portal_blocked: 'bad',
person_changed: '',
devices_removed: 'warn',
};
/** The icon in an event's tile: the device's kind for device events, else what happened. */
const EVENT_ICON: Record<string, string> = {
devices_removed: 'trash',
link_changed: 'link',
person_added: 'plus',
person_removed: 'trash',
person_changed: 'edit',
paused: 'pause',
resumed: 'play',
paused_all: 'pause',
resumed_all: 'play',
};
function eventIcon(st: Names, e: LogEvent): string {
if (e.device) {
const d = st.people.flatMap((p) => p.devices).find((x) => x.id === e.device);
return d?.kind ?? e.dkind ?? 'other';
}
return EVENT_ICON[e.type] ?? 'activity';
}
export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
const person = st.people.find((p) => p.id === e.person);
const who = person?.name ?? e.pname ?? e.person ?? '';
const dev = person?.devices.find((d) => d.id === e.device)?.name ?? e.dname ?? '';
const b = (t: string) => E('b', {}, t);
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
/** An address; at home, the name of the device that has it, with the address in brackets. */
const addr = (ip: string) =>
e.hosts?.[ip]
? [E('span', { class: 'dl-ev-host' }, [E('b', {}, e.hosts[ip]), E('span', { class: 'dl-faint' }, ` (${ip})`)])]
: [mono(ip)];
// What the bold name is (a person, a device), said before it in grey.
const kind = (t: string) => E('span', { class: 'dl-ev-kind' }, `${t} `);
const wd = dev ? `${who} · ${dev}` : who;
const detail = plainDetail(e);
const devName = detail || dev || 'a device';
// The admin's own actions start with an accent "You".
const you = (verb: string) => [E('span', { class: 'dl-you' }, 'You'), m(` ${verb} `)];
if (eventBy(e) === 'admin')
switch (e.type) {
case 'device_added':
return [...you('added'), kind('device'), b(devName), m(' for '), b(who)];
case 'device_removed':
return [...you('removed'), kind('device'), b(devName), m(' from '), b(who)];
case 'paused':
return [...you('paused'), kind('person'), b(who)];
case 'resumed':
return [...you('resumed'), kind('person'), b(who)];
case 'device_changed': {
const renamed = detail.startsWith('renamed from ');
return [
...you(renamed ? 'renamed' : detail),
kind('device'),
b(dev || 'a device'),
m(' of '),
b(who),
...(renamed ? [m(` · was ${detail.slice(13)}`)] : []),
];
}
case 'device_keys':
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
case 'link_changed':
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
case 'paused_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' paused everyone')];
case 'resumed_all':
return [E('span', { class: 'dl-you' }, 'You'), m(' resumed everyone')];
}
switch (e.type) {
case 'connect':
return [
kind('Device'),
b(wd),
m(' connected'),
...(e.detail ? [m(' from '), ...addr(e.detail)] : []),
...(e.where ? [m(` · ${e.where}`)] : []),
];
case 'disconnect':
return [kind('Device'), b(wd), m(' went offline')];
case 'roam':
return [
kind('Device'),
b(wd),
m(' changed network '),
...(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
];
case 'device_added':
return [
kind('Person'),
b(who),
m(' added '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_removed':
return [
kind('Person'),
b(who),
m(' removed '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
case 'device_keys':
return [kind('Person'), b(who), m(' issued new keys for '), kind('device'), b(devName), m(' on their portal')];
case 'person_added':
return [...you('added'), kind('person'), b(e.detail ?? who)];
case 'person_removed':
return [...you('removed'), kind('person'), b(e.detail ?? who)];
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 'paused':
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
case 'resumed':
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
case 'paused_all':
return [m('Everyone paused')];
case 'resumed_all':
return [m('Everyone resumed')];
case 'portal_blocked':
return [
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
m(' blocked '),
mono(e.detail ?? ''),
m(' for 15 min after too many wrong codes'),
];
case 'devices_removed':
return [kind('Person'), b(who), m(' — all devices removed, end date reached')];
default:
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
}
}
/** Events about the router rather than people look like service log lines: icon tile, colour by outcome. */
const SYSTEM_EVENT: Record<string, [string, string]> = {
portal_blocked: ['globe', 'bad'],
};
/** With several servers, which one a person's event happened on (left out where that is clear). */
function serverPill(st: Names, e: LogEvent): HTMLElement | '' {
if (st.servers.length < 2 || !e.person) return '';
const p = st.people.find((x) => x.id === e.person);
const srv = p && st.servers.find((s) => s.id === p.server);
return srv ? E('span', { class: 'dl-ev-srv', title: 'Server' }, srv.name) : '';
}
/** An activity event as a row; `time` replaces the "5 min ago" (`now` is the router's clock). */
export function eventRow(st: Names & { now?: number }, e: LogEvent, opts: { server?: boolean; time?: string } = {}): HTMLElement {
const sys = SYSTEM_EVENT[e.type];
const by = eventBy(e);
return E('div', { class: `dl-row${by === 'admin' ? ' dl-ev-by-admin' : sys ? ` dl-ev-by-system ${sys[1]}` : ''}` }, [
by === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: sys
? E('span', { class: 'dl-ev-tile sys' }, icon(sys[0]))
: E('span', { class: `dl-ev-tile ev ${EVENT_TONE[e.type] ?? ''}` }, icon(eventIcon(st, e))),
E('span', { class: 'dl-row-main' }, eventText(st, e)),
opts.server === false ? '' : serverPill(st, e),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, opts.time ?? ago(e.ts, st.now)),
]);
}
/** Colour per service log level (tile, source and row): neutral unless something came up, was repaired or failed. */
// "down" is a tunnel that stopped without Dawnline asking (its own stops are "info").
const SYS_TONE: Record<ServiceLogEntry['level'], string> = { info: '', up: 'ok', down: 'warn', repair: 'warn', error: 'bad' };
const SYS_ICON: Record<ServiceLogEntry['src'], string> = { awg: 'tunnel', dawnline: 'sunrise', portal: 'globe' };
/** A service log line: source, message, folded details; click to unfold. */
export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void, time: string): HTMLElement {
const admin = e.by === 'admin';
const row = E(
'div',
{
class: `dl-row dl-slog-row ${admin ? 'dl-ev-by-admin' : `dl-ev-by-system ${SYS_TONE[e.level] ?? ''}`}${e.detail ? ' has-detail' : ''}`,
},
[
admin
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: 'dl-ev-tile sys', title: e.level }, icon(SYS_ICON[e.src] ?? 'zap')),
E(
'span',
{ class: 'dl-row-main' },
admin
? [
E('span', { class: 'dl-you' }, 'You'),
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
e.who ? E('b', {}, e.who) : '',
e.note ? E('span', { class: 'dl-muted' }, ` · ${e.note}`) : '',
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
]
: [
// Servers have names people chose: say it is a server. Services name themselves.
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, 'Server ') : '',
E('b', { class: 'dl-sys-src', title: SYSTEM_SOURCE[e.src] ?? e.src }, e.who ?? SYSTEM_SOURCE[e.src] ?? e.src),
' ',
E('span', { class: 'dl-muted' }, e.msg),
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
],
),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, time),
],
);
if (e.detail)
row.addEventListener('click', (ev) => {
if (!(ev.target as HTMLElement).closest('pre')) toggle();
});
return row;
}
/** "Today", "Yesterday" or "Monday 12 October". */
export function dayTitle(ts: number): string {
const d = new Date(ts * 1000);
const today = new Date();
const y = new Date();
y.setDate(today.getDate() - 1);
if (d.toDateString() === today.toDateString()) return 'Today';
if (d.toDateString() === y.toDateString()) return 'Yesterday';
return d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });
}
+45 -82
View File
@@ -5,9 +5,11 @@ import type { MeshMode, Server, Status } from '../shared/types';
import { E } from './e';
import { api, type IfaceCategory, type InterfacesData, type NetDevice } from './api';
import { circleChips, homeServices } from './access';
import { attempt, button, notify } from './ui';
import { button } from './ui/button';
import { attempt, notify } from './ui/toast';
import { seg, sw } from './ui/controls';
import { attachTip } from './ui/tooltip';
import { installMissing } from './pkgs';
import { attachTip } from './charts';
import { icon } from '../shared/icons';
const GROUPS: [IfaceCategory, string][] = [
@@ -27,34 +29,22 @@ const ICON: Record<NetDevice['kind'], string> = {
other: 'link',
};
function sw(on: boolean, label: string, onChange: (v: boolean) => void): HTMLButtonElement {
const b = E(
'button',
{
type: 'button',
role: 'switch',
class: `dl-switch${on ? ' on' : ''}`,
'aria-checked': on ? 'true' : 'false',
'aria-label': label,
click: () => {
const v = !b.classList.contains('on');
b.classList.toggle('on', v);
b.setAttribute('aria-checked', v ? 'true' : 'false');
onChange(v);
},
},
E('i'),
) as HTMLButtonElement;
return b;
/** Server → Access cards; `update` takes a new status without touching the draft. */
export interface AccessCards {
el: HTMLElement;
update(st: Status): void;
}
/**
* Server → Access: how internet traffic leaves (Internet) and what home access
* reaches (Home network: networks, devices reaching each other, services).
* Both cards share one draft; either Save stores it.
* Both cards share one draft; either Save stores it. Changes that apply at
* once (devices reaching each other, services, circles) call `refresh`, which
* brings a new status here through `update`: the draft stays as it is.
*/
export function accessCards(srv: Server, st: Status, reload: () => void): HTMLElement {
export function accessCards(srv: Server, first: Status, refresh: () => Promise<unknown>): AccessCards {
const serverId = srv.id;
let st = first;
const root = E(
'div',
{ class: 'dl-stack gap16' },
@@ -69,7 +59,7 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
// "Other interfaces" stays open or folded across repaints.
let otherOpen = false;
// Built once: it reads the devices at home, which should not happen on every repaint.
const services = homeServices(st, serverId, reload);
const services = homeServices(st, serverId, refresh);
let lans = new Set<string>();
let initial = '';
@@ -322,32 +312,27 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
]),
]);
const meshSeg = E(
'div',
{ class: 'dl-seg sm', role: 'radiogroup', 'aria-label': 'Devices reach each other' },
(
[
['off', 'Off'],
['all', 'Everyone'],
['circles', 'Circles'],
] as const
).map(([v, t]) =>
E(
'button',
{
type: 'button',
role: 'radio',
class: mesh === v ? 'on' : '',
'aria-checked': mesh === v ? 'true' : 'false',
// Applies at once, like the choices on a person's page.
click: async () => {
if (mesh === v) return;
if (await attempt(() => api.serverUpdate(serverId, { mesh: v }), `Devices reach each other: ${t}`)) reload();
},
},
t,
),
),
const meshSeg = seg(
[
['off', 'Off'],
['all', 'Everyone'],
['circles', 'Circles'],
] as [MeshMode, string][],
mesh,
{
label: 'Devices reach each other',
cls: 'sm',
optimistic: false,
// Applies at once, like the choices on a person's page.
onChange: async (v) => {
const t = { off: 'Off', all: 'Everyone', circles: 'Circles' }[v];
if (!(await attempt(() => api.serverUpdate(serverId, { mesh: v }), `Devices reach each other: ${t}`))) return;
mesh = v;
d.config.mesh = v;
paint();
await refresh();
},
},
);
const homeCard = E('section', { class: 'dl-setsec dl-ifcard' }, [
@@ -372,10 +357,9 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
MESH_TEXT[mesh],
meshSeg,
'',
mesh === 'circles' ? circleChips(st, serverId, reload) : undefined,
mesh === 'circles' ? circleChips(st, serverId, refresh) : undefined,
),
bonjourRow(),
services,
services.el,
]),
E('div', { class: 'dl-setsec-foot' }, [
E(
@@ -397,34 +381,6 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
window.scrollTo({ top: y });
}
/** Find home devices: AirPlay, printers and shared Macs listed on Apple devices over the tunnel. */
function bonjourRow(): HTMLElement {
const b = d.bonjour;
const set = async (on: boolean) => {
if (await attempt(() => api.serverUpdate(serverId, { bonjour: on }), on ? 'Finding home devices' : 'Home devices no longer listed'))
load(false);
};
const state = b.needs.length
? E('span', { class: 'dl-warn' }, ` Needs ${b.needs.join(', ')}.`)
: b.on && !b.running
? E('span', { class: 'dl-warn' }, ' umdns is not running.')
: b.on
? ` Listing ${b.services} service${b.services === 1 ? '' : 's'} from home now.`
: '';
return setrow(
'wifi',
['Find home devices ', E('span', { class: 'dl-faint dl-w400' }, '· Bonjour')],
[
'iPhone, iPad and Mac on the VPN see AirPlay, printers and shared Macs at home, as on Wi-Fi. Android and Chromecast look only on the local network.',
state,
],
b.needs.length
? button('Install', () => installMissing('bonjour', b.needs, () => load(false)), 'positive')
: sw(b.on, 'Find home devices', (v) => set(v)),
b.on && b.running ? 'ok' : '',
);
}
/** Interfaces that can be home networks as tiles; the rest folded, by kind. */
function netPicker(): HTMLElement {
const avail = d.devices.filter(pickable);
@@ -477,5 +433,12 @@ export function accessCards(srv: Server, st: Status, reload: () => void): HTMLEl
}
load(true);
return root;
return {
el: root,
update(n: Status) {
st = n;
services.update(n);
if (d) paint();
},
};
}
+41 -11
View File
@@ -3,7 +3,11 @@
import type { Person } from '../shared/types';
import { E } from './e';
import { attempt, button, closeModal, copyText, downloadFile, modal, notify } from './ui';
import { api } from './api';
import { button } from './ui/button';
import { closeModal, modal } from './ui/modal';
import { copyText, downloadFile } from './ui/files';
import { attempt, notify } from './ui/toast';
import { icon } from '../shared/icons';
import { qrSvg } from '../shared/qr';
@@ -16,7 +20,7 @@ const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
function cardSvg(p: Person, server: string, link: string): string {
function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string {
const url = new URL(link);
const word = url.pathname.slice(1);
// Long names shrink to stay on one line (roughly 0.58 em per character).
@@ -60,19 +64,45 @@ async function toPng(svg: string): Promise<Blob> {
);
}
type Invitee = Pick<Person, 'id' | 'name' | 'link'> & { links?: string[] };
/** Who to invite; without `link` the card asks the router for the person's links (they are not in the status). */
type Invitee = Pick<Person, 'id' | 'name'> & { link?: string | null; links?: string[] };
/** The personal link and its other addresses (person_links); null while the portal is off. */
export async function personLinks(id: string): Promise<{ link: string; links: string[] } | null> {
const r = await attempt(() => api.personLinks(id));
if (!r) return null;
if (!r.link) {
notify('The personal portal is off. Turn it on in Settings.', 'warning');
return null;
}
return { link: r.link, links: r.links ?? [] };
}
/** Copy a person's personal link. */
export async function copyPersonLink(id: string) {
const r = await personLinks(id);
if (r) await copyText(r.link, 'Personal link copied');
}
/**
* The card with Copy link and Share / Download. Also the "is ready" step
* after adding someone.
*/
export async function inviteCard(p: Invitee, server: string, opts: { title?: string; lead?: string } = {}) {
if (!p.link) {
let link = p.link;
let links = p.links;
if (link === undefined) {
const r = await personLinks(p.id);
if (!r) return;
link = r.link;
links = r.links;
}
if (!link) {
notify('The personal portal is off. Turn it on in Settings.', 'warning');
return;
}
const link = p.link;
const png = await attempt(() => toPng(cardSvg(p as Person, server, link)));
const href = link;
const png = await attempt(() => toPng(cardSvg(p, server, href)));
if (!png) return;
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
const url = URL.createObjectURL(png);
@@ -105,12 +135,12 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
{ class: 'dl-muted' },
opts.lead ?? `Send ${p.name} the card or the link. They open it, add their devices and connect — no account needed.`,
),
E('button', { type: 'button', class: 'dl-invite-link', title: 'Copy link', click: () => copyText(link, 'Personal link copied') }, [
E('span', {}, link.replace(/^https:\/\//, '')),
E('button', { type: 'button', class: 'dl-invite-link', title: 'Copy link', click: () => copyText(href, 'Personal link copied') }, [
E('span', {}, href.replace(/^https:\/\//, '')),
icon('copy'),
]),
...(p.links ?? [])
.filter((l) => l !== link)
...(links ?? [])
.filter((l) => l !== href)
.map((l) =>
E('button', { type: 'button', class: 'dl-invite-link alt', title: 'Copy this link', click: () => copyText(l, 'Link copied') }, [
E('span', {}, l.replace(/^https?:\/\//, '')),
@@ -125,7 +155,7 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
]),
E('div', { class: 'dl-invite-actions' }, [
share,
button([icon('copy'), ' Copy link'], () => copyText(link, 'Personal link copied')),
button([icon('copy'), ' Copy link'], () => copyText(href, 'Personal link copied')),
]),
]),
]),
+39 -61
View File
@@ -1,48 +1,15 @@
// Activity log helpers shared by Activity, Settings, the person page and the
// device drawer: categories, export, and the clear / reset dialogs.
// Activity log actions shared by Diagnostics, Settings, the person page and
// the device drawer: export, and the clear / reset dialogs.
import type { LogEvent, Status } from '../shared/types';
import { E } from './e';
import { api, type LogCategory, type LogFilter, type ServiceLogEntry } from './api';
import { attempt, button, closeModal, downloadFile, modal, notify } from './ui';
import { eventBy } from './pages/overview';
/** Mirrors CATEGORY in dawnline.live. */
const CATEGORY: Record<string, LogCategory> = {
connect: 'connections',
disconnect: 'connections',
roam: 'connections',
device_added: 'people',
device_removed: 'people',
devices_removed: 'people',
device_changed: 'people',
device_keys: 'people',
link_changed: 'people',
person_added: 'people',
person_removed: 'people',
person_changed: 'people',
paused: 'people',
resumed: 'people',
paused_all: 'people',
resumed_all: 'people',
portal_blocked: 'problems',
};
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
export const CATEGORY_LABEL: Record<LogCategory, string> = {
connections: 'Connections',
people: 'People',
problems: 'Problems',
};
export const CATEGORY_HELP: Record<LogCategory, string> = {
connections: 'Connects, disconnects and IP changes',
people: 'People and their devices added, changed, paused, removed',
problems: 'Blocked portal sign-ins (tunnels and services are in the service log)',
};
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
import { button } from './ui/button';
import { cancelButton, closeModal, modal } from './ui/modal';
import { downloadFile } from './ui/files';
import { attempt, errorText, notify } from './ui/toast';
import { CATEGORIES, CATEGORY_LABEL, SYSTEM_SOURCE, categoryOf, eventBy } from './events/model';
import { toCsv } from './events/csv';
function names(st: Pick<Status, 'people'>) {
const people = new Map(st.people.map((p) => [p.id, p.name]));
@@ -50,13 +17,6 @@ function names(st: Pick<Status, 'people'>) {
return { people, devices };
}
function csvCell(v: unknown): string {
const s = v == null ? '' : String(v);
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
/** Download events (and service log entries, category "system") as CSV or JSON, names resolved, oldest first. */
export function exportEvents(
st: Pick<Status, 'people'>,
@@ -97,8 +57,7 @@ export function exportEvents(
return;
}
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where', 'by'] as const;
const csv = [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
downloadFile(name, csv, 'text/csv');
downloadFile(name, toCsv(cols, rows), 'text/csv');
}
const AGES: [string, string][] = [
@@ -108,6 +67,8 @@ const AGES: [string, string][] = [
['90', 'Older than 90 days'],
];
const removed = (n: number) => (n ? `${n} event${n === 1 ? '' : 's'} removed` : 'Nothing matched');
/**
* Ask what to clear and do it. `base` pins person/device; the dialog lets you
* pick a category (unless `category` is given) and an age.
@@ -138,21 +99,38 @@ export function clearLogDialog(
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Which events'), age]),
],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Clear',
async () => {
// System is the service log; "All categories" clears it too where it is shown.
const r = await attempt(async () => {
const sys = withSystem && (cat.value === 'system' || cat.value === '') ? await api.serviceLogClear(age.value) : { removed: 0 };
const ev =
cat.value === 'system' ? { removed: 0 } : await api.logsClear({ ...base, category: cat.value, older_days: age.value });
return { removed: sys.removed + ev.removed };
});
if (!r) return;
// The activity log first, then the service log ("System"; "All categories"
// clears it too where it is shown). Each result is reported on its own.
let n = 0;
if (cat.value !== 'system') {
try {
n += (await api.logsClear({ ...base, category: cat.value, older_days: age.value })).removed;
} catch (e) {
notify(errorText(e), 'error', 10000);
return;
}
}
if (withSystem && (cat.value === 'system' || cat.value === '')) {
try {
n += (await api.serviceLogClear(age.value)).removed;
} catch (e) {
closeModal();
notify(
`${cat.value === 'system' ? '' : `Activity: ${removed(n).toLowerCase()}. `}The service log was not cleared: ${errorText(e)}`,
'error',
10000,
);
done();
return;
}
}
closeModal();
notify(r.removed ? `${r.removed} event${r.removed === 1 ? '' : 's'} removed` : 'Nothing matched', 'success', 3000);
notify(removed(n), 'success', 3000);
done();
},
'negative',
@@ -173,7 +151,7 @@ export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string,
scope === 'all' ? 'Reset all traffic history?' : `Reset traffic history for ${label}?`,
[E('p', { class: 'dl-muted' }, body)],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Cancel'),
cancelButton(),
' ',
button(
'Reset',
-5
View File
@@ -121,11 +121,6 @@ declare global {
const poll: LuciPoll;
const dom: LuciDom;
const baseclass: { extend<T>(props: T): T };
// LuCI form/network/firewall/uci classes are used dynamically.
const form: any;
const network: any;
const firewall: any;
const uci: any;
}
export type { Child, LuciWidget, WidgetOptions };
+12 -13
View File
@@ -4,7 +4,7 @@
import { PeoplePage } from './pages/people';
import { ServerPage } from './pages/server';
import { SettingsPage } from './pages/settings';
import { UpdatesPage } from './pages/maintenance';
import { ComponentsPage } from './pages/components';
import { PersonPage } from './pages/person';
import { DiagnosticsPage } from './pages/diagnostics';
import { styleNode } from './styles';
@@ -12,11 +12,11 @@ import { styleNode } from './styles';
interface Page {
load(): Promise<any>;
render(data: any): Node | Promise<Node>;
/** Set by a form page when it rendered something without a form. */
/** No footer at all (otherwise LuCI's, without its form buttons). */
noFooter?: boolean;
}
function factory<P extends Page>(Cls: new () => P, formBased: boolean) {
function factory<P extends Page>(Cls: new () => P) {
return () => {
const page = new Cls();
const v: Record<string, unknown> = {
@@ -32,20 +32,19 @@ function factory<P extends Page>(Cls: new () => P, formBased: boolean) {
return page.noFooter ? document.createElement('div') : this.super('addFooter', []);
},
};
// Pages without a form.Map have nothing to save: hide the footer buttons.
if (!formBased) Object.assign(v, { handleSave: null, handleSaveApply: null, handleReset: null });
return v;
// No page is a LuCI form (changes go through RPC): nothing to Save & Apply.
return Object.assign(v, { handleSave: null, handleSaveApply: null, handleReset: null });
};
}
// The old Overview address opens the Servers page (it holds each server's overview now).
const overview = factory(ServerPage, false);
const people = factory(PeoplePage, true);
const server = factory(ServerPage, false);
const settings = factory(SettingsPage, false);
const person = factory(PersonPage, false);
const diagnostics = factory(DiagnosticsPage, false);
const updates = factory(UpdatesPage, false);
const overview = factory(ServerPage);
const people = factory(PeoplePage);
const server = factory(ServerPage);
const settings = factory(SettingsPage);
const person = factory(PersonPage);
const diagnostics = factory(DiagnosticsPage);
const updates = factory(ComponentsPage);
/** Health and Activity became Diagnostics tabs: old addresses and bookmarks go there. */
function moved(tab: '' | 'log') {
@@ -0,0 +1,50 @@
// Components → Activity: the latest updates, and checks that found something.
import type { UpdateEvent } from '../../api';
import { E } from '../../e';
import { icon } from '../../../shared/icons';
import { ago, duration } from '../../../shared/format';
import { jobComponent } from '../../updater/jobs';
import type { ComponentsPage } from './index';
const NAMES: Record<string, string> = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', all: 'Components' };
export function activity(page: ComponentsPage): HTMLElement {
const st = page.st;
const row = (e: UpdateEvent) => {
const comp = jobComponent(e.component ?? 'app');
const who = NAMES[comp] ?? 'Components';
const how = e.auto ? 'automatically' : 'by you';
let tone = 'ok',
ic = 'check',
text: (Node | string)[];
if (e.kind === 'found') {
tone = 'accent';
ic = 'download';
text = [E('b', {}, (e.items ?? []).join(', ')), ` found by ${e.auto ? 'the automatic check' : 'a check'}`];
} else if (e.state === 'failed') {
tone = 'bad';
ic = 'x';
text = [E('b', {}, who), ` ${e.kind === 'install' ? 'update' : 'check'} failed${e.error ? ` · ${e.error}` : ''}`];
} else {
const ver = e.from && e.to && e.from !== e.to ? ` ${e.from} → ${e.to}` : e.to ? ` ${e.to}` : '';
text = [E('b', {}, who), `${ver} ${ver ? '' : 'updated '}${how}${e.took ? ` · ${duration(e.took)}` : ''}`.replace(/\s+/g, ' ')];
}
return E('div', { class: 'dl-row' }, [
E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, text),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)),
]);
};
const h = st.history ?? [];
return E('section', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('span', { class: 'dl-spacer' }),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All in Log →'),
]),
h.length
? E('div', {}, h.slice(0, 8).map(row))
: E('p', { class: 'dl-sub dl-comp-empty' }, 'Updates, and checks that found something, show up here.'),
]);
}
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more