Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f12ca19e7 | ||
|
|
edeb1506fd | ||
|
|
7a6370aa9e | ||
|
|
466ca6c7b0 | ||
|
|
fd9543ce68 | ||
|
|
31a2065f05 | ||
|
|
2b98abdba4 | ||
|
|
1a2f0b327e | ||
|
|
5768856d76 | ||
|
|
972e522518 |
No files matched your search
@@ -12,10 +12,19 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
# Read-only by default; only the release job may write (publish the release).
|
# Read-only by default; only the release job may write (publish the release).
|
||||||
|
# Everything that runs here is pinned to a digest or a commit: the packages
|
||||||
|
# it publishes are installed as root on every router with automatic updates
|
||||||
|
# on, so a re-pointed tag must not be able to change what gets built.
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
# The same checks as on main (ci.yml), on the tag itself: nothing is built or
|
||||||
|
# published until they pass.
|
||||||
|
ci:
|
||||||
|
name: CI
|
||||||
|
uses: ./.github/workflows/ci.yml
|
||||||
|
|
||||||
version:
|
version:
|
||||||
name: Version
|
name: Version
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
@@ -23,7 +32,7 @@ jobs:
|
|||||||
version: ${{ steps.version.outputs.version }}
|
version: ${{ steps.version.outputs.version }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v5
|
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
@@ -44,21 +53,21 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
name: Build ${{ matrix.type }}
|
name: Build ${{ matrix.type }}
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
needs: version
|
needs: [version, ci]
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: true
|
fail-fast: true
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6' }
|
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6@sha256:a6bd28c380b251ebdb1d6d5f83e55ecb0a3c1808b5a8f4841424abc8019a903f' }
|
||||||
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3' }
|
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v5
|
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v5
|
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '22'
|
||||||
cache: npm
|
cache: npm
|
||||||
@@ -77,7 +86,7 @@ jobs:
|
|||||||
run: scripts/build-packages.sh ${{ matrix.type }}
|
run: scripts/build-packages.sh ${{ matrix.type }}
|
||||||
|
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||||
with:
|
with:
|
||||||
name: package-${{ matrix.type }}
|
name: package-${{ matrix.type }}
|
||||||
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }}
|
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }}
|
||||||
@@ -94,7 +103,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
# The whole history and the tags: the notes list the commits since the previous tag.
|
# The whole history and the tags: the notes list the commits since the previous tag.
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v5
|
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
@@ -105,7 +114,7 @@ jobs:
|
|||||||
cat notes.md
|
cat notes.md
|
||||||
|
|
||||||
- name: Download packages
|
- name: Download packages
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||||
with:
|
with:
|
||||||
pattern: package-*
|
pattern: package-*
|
||||||
path: release
|
path: release
|
||||||
@@ -118,7 +127,7 @@ jobs:
|
|||||||
cat sha256sums.txt
|
cat sha256sums.txt
|
||||||
|
|
||||||
- name: Publish the release
|
- name: Publish the release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||||
with:
|
with:
|
||||||
name: Dawnline ${{ github.ref_name }}
|
name: Dawnline ${{ github.ref_name }}
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.ref_name }}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
name: CI
|
name: CI
|
||||||
|
|
||||||
|
# Every push to main and every pull request; also called by build.yml, so a
|
||||||
|
# tag never publishes a release without these checks passing on it.
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
pull_request:
|
pull_request:
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -43,6 +46,7 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Sources and the test files (tsconfig.test.json).
|
||||||
- name: Type check
|
- name: Type check
|
||||||
id: types
|
id: types
|
||||||
run: npm run --silent typecheck
|
run: npm run --silent typecheck
|
||||||
@@ -51,12 +55,17 @@ jobs:
|
|||||||
id: tests
|
id: tests
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
|
# The bundles under package/ are committed: a build must change nothing
|
||||||
|
# and leave no new file behind (an output nobody added to git would be
|
||||||
|
# missing from the package).
|
||||||
- name: Build bundles and check they are committed
|
- name: Build bundles and check they are committed
|
||||||
id: build
|
id: build
|
||||||
run: |
|
run: |
|
||||||
npm run --silent build
|
npm run --silent build
|
||||||
if ! git diff --exit-code -- ../package; then
|
changed="$(git status --porcelain --untracked-files=all -- ../package)"
|
||||||
echo "::error::The committed bundles are out of date. Run 'npm run build' in web/ and commit the result."
|
if [ -n "$changed" ]; then
|
||||||
|
echo "$changed"
|
||||||
|
echo "::error::The committed bundles are out of date or the build left new files. Run 'npm run build' in web/ and commit the result."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -83,17 +92,25 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
|
# Every shell script by its shebang (the init script's is "/bin/sh
|
||||||
|
# /etc/rc.common"), so a new hotplug or libexec script is covered the
|
||||||
|
# day it appears. Files without a shebang (keep.d lists) are not shell.
|
||||||
- name: ShellCheck
|
- name: ShellCheck
|
||||||
run: |
|
run: |
|
||||||
shellcheck --version
|
shellcheck --version
|
||||||
shellcheck -S warning \
|
files="$(grep -rlIE '^#!(/usr)?/bin/(sh|bash|env (sh|bash))( |$)' \
|
||||||
install.sh \
|
install.sh uninstall.sh package/luci-app-dawnline/root scripts tests | sort)"
|
||||||
uninstall.sh \
|
echo "$files"
|
||||||
package/luci-app-dawnline/root/etc/init.d/dawnline \
|
for f in 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 \
|
||||||
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
|
package/luci-app-dawnline/root/usr/libexec/dawnline/resolver \
|
||||||
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
|
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
|
||||||
scripts/*.sh
|
package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate \
|
||||||
|
package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal; do
|
||||||
|
echo "$files" | grep -qx "$f" || { echo "::error file=$f::not found by the shebang scan"; exit 1; }
|
||||||
|
done
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
shellcheck -S warning $files
|
||||||
|
|
||||||
ucode:
|
ucode:
|
||||||
name: ucode static checks
|
name: ucode static checks
|
||||||
@@ -104,20 +121,52 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Use before definition
|
- name: Lint (use before definition, exports, POSIX regexes, rpcd methods)
|
||||||
run: python3 scripts/lint-ucode.py
|
run: python3 scripts/lint-ucode.py
|
||||||
|
|
||||||
- name: Executables keep their mode
|
- name: Executables keep their mode
|
||||||
run: |
|
run: |
|
||||||
cd package/luci-app-dawnline/root
|
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat usr/libexec/dawnline/postupdate \
|
||||||
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat \
|
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal usr/share/dawnline/portal/cgi.uc; do
|
||||||
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
|
[ -x "package/luci-app-dawnline/root/$f" ] || { echo "::error file=package/luci-app-dawnline/root/$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
|
||||||
|
done
|
||||||
|
for f in scripts/check-ucode.sh scripts/compile-ucode.sh scripts/ucode-container.sh tests/ucode/run.sh tests/ucode/fixtures/bin/awg; do
|
||||||
[ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
|
[ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
|
||||||
done
|
done
|
||||||
|
|
||||||
- name: Versions agree
|
- name: Versions agree
|
||||||
run: |
|
run: |
|
||||||
v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)"
|
v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)"
|
||||||
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc
|
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc ||
|
||||||
grep -q "\"version\": \"$v\"" web/package.json
|
{ echo "::error::util.uc VERSION differs from the Makefile ($v)"; exit 1; }
|
||||||
|
grep -q "\"version\": \"$v\"" web/package.json ||
|
||||||
|
{ echo "::error::web/package.json version differs from the Makefile ($v)"; exit 1; }
|
||||||
|
python3 - "$v" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
v = sys.argv[1]
|
||||||
|
lock = json.load(open('web/package-lock.json'))
|
||||||
|
got = (lock.get('version'), lock.get('packages', {}).get('', {}).get('version'))
|
||||||
|
if got != (v, v):
|
||||||
|
print(f"::error::web/package-lock.json says {got}, the Makefile {v}: run 'npm install' in web/")
|
||||||
|
sys.exit(1)
|
||||||
|
PY
|
||||||
echo "Version $v"
|
echo "Version $v"
|
||||||
|
|
||||||
|
ucode-compile:
|
||||||
|
# scripts/compile-ucode.sh and tests/ucode on the release's own ucode and
|
||||||
|
# libuci, in the OpenWrt rootfs containers scripts/ucode-container.sh pins
|
||||||
|
# by digest (24.10 = opkg, 25.12 = apk: the two the packages are built for).
|
||||||
|
name: ucode compiles and tests pass (OpenWrt ${{ matrix.release }})
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
release: ['24.10', '25.12']
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Compile every ucode file and run tests/ucode
|
||||||
|
run: scripts/ucode-container.sh ${{ matrix.release }}
|
||||||
@@ -17,13 +17,16 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
|
|||||||
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
|
- `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/`.
|
- `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`).
|
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
|
||||||
- `scripts/` — `lint-ucode.py`, `check-ucode.sh` (compiles every module on the router without installing), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
|
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
|
||||||
|
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
|
||||||
|
|
||||||
## Checks before a commit or deploy
|
## 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`.
|
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
|
||||||
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build` — and commit the rebuilt bundles.
|
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
|
||||||
- `shellcheck -S warning` for the shell scripts (CI runs it).
|
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm test`, `npm run build` — and commit the rebuilt bundles (CI fails on a changed or new file under `package/`).
|
||||||
|
- `shellcheck -S warning` for the shell scripts (CI finds them by shebang).
|
||||||
|
- A tag builds only after CI passes on it (`build.yml` calls `ci.yml`).
|
||||||
|
|
||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
|
|||||||
@@ -1,90 +1,182 @@
|
|||||||
# Dawnline
|
<div align="center">
|
||||||
|
|
||||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml)
|
<picture>
|
||||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml)
|
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
|
||||||
|
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
|
||||||
|
</picture>
|
||||||
|
|
||||||
Your OpenWrt router as a private VPN for the people you choose.
|
<h1>Dawnline</h1>
|
||||||
|
|
||||||
Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router
|
**Your OpenWrt router as a private VPN for the people you choose.**
|
||||||
and gives every person a personal link. They open it, add their own devices
|
|
||||||
(up to the limit you set) and connect with AmneziaVPN or AmneziaWG. You decide
|
|
||||||
what each person may reach: the home network, the internet, or both.
|
|
||||||
|
|
||||||
Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-liminal):
|
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Latest release" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
the same idea rebuilt around people instead of peers, with a personal portal,
|
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
limits, live traffic and a LuCI admin that follows a modern design.
|
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Downloads" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
|
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="License" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
|
<br>
|
||||||
|
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||||
|
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||||
|
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 and 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
|
||||||
|
|
||||||

|
[**Quick start**](#-quick-start) · [Features](#-features) · [How it works](#-how-it-works) · [Screenshots](#-a-closer-look) · [FAQ](#-faq) · [Development](#-development)
|
||||||
|
|
||||||
| People | A person |
|
</div>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
Dawnline runs an [AmneziaWG] server on your OpenWrt router and gives every
|
||||||
|
person you invite **a personal link**. They open it, **add their own phones and
|
||||||
|
computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide
|
||||||
|
**what each of them may reach** (the home network, the internet, or both) and
|
||||||
|
**for how long, how much and when**.
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/screenshots/portal.png" alt="The personal portal: devices and access, and adding a phone in three steps" width="860">
|
||||||
|
<br>
|
||||||
|
<sub>A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect.</sub>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## 💡 Why Dawnline?
|
||||||
|
|
||||||
|
Sharing a home VPN usually means making a config file by hand, sending it over
|
||||||
|
a messenger and hoping nobody shares it further. Dawnline turns that around:
|
||||||
|
|
||||||
|
| | A VPN by hand | With Dawnline |
|
||||||
|
|---|---|---|
|
||||||
|
| **Setting up a device** | You make a config and send it | They add it themselves from their link |
|
||||||
|
| **Who can do what** | Everyone gets the same | Home, internet or both, per person |
|
||||||
|
| **Ending access** | Find and delete their peers | A date, a data limit, or one click |
|
||||||
|
| **Knowing what goes on** | Read `wg show` | Who is online, traffic, places, a log |
|
||||||
|
| **When something breaks** | You find out from them | A watchdog notices and repairs it |
|
||||||
|
|
||||||
|
It is the successor of [Liminal]: the same idea rebuilt around people instead
|
||||||
|
of peers, with a personal portal, limits, live traffic and a LuCI admin that
|
||||||
|
follows a modern design.
|
||||||
|
|
||||||
|
## 🚀 Quick start
|
||||||
|
|
||||||
|
1. **Install** on the router (it asks before it changes anything):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Set up** in LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, and follow the
|
||||||
|
wizard. It suggests the port, the public address and the networks.
|
||||||
|
3. **Invite** someone: <kbd>Add person</kbd>, then send them the link or the
|
||||||
|
invite card with its QR code. They do the rest.
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> Behind Cloudflare, give the portal a port Cloudflare proxies: 2053, 2083,
|
||||||
|
> 2087, 2096 or 8443.
|
||||||
|
|
||||||
|
## ✨ Features
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<h3>🔗 A link, not an account</h3>
|
||||||
|
<p>Three words, like <code>vpn.example.com/kamiro-telosu-bavine</code>. The link is the key: no sign-up, no password, and a new link locks the old one out at once.</p>
|
||||||
|
</td>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<h3>📱 Their own devices</h3>
|
||||||
|
<p>People add, rename and remove devices up to their limit. Adding one walks them through it: the right app, then a QR code, a link, a key or a file.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>👥 People, not peers</h3>
|
||||||
|
<p>One card per person with their devices, who is online, traffic, end date and data limit. Filter by who needs attention or is paused.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🧭 Who reaches what</h3>
|
||||||
|
<p>The home network, the internet or both; only some networks or devices at home (a NAS, Home Assistant). Family sees family, guests see guests.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>⏳ Limits</h3>
|
||||||
|
<p>End dates, monthly or total data limits, allowed hours, a pause button. Changes apply at once, without dropping anyone else's connection.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🕶️ Disguise</h3>
|
||||||
|
<p>Presets that make the VPN traffic harder to spot and block, with what each one needs from the apps.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🏠 Internet like a home device</h3>
|
||||||
|
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🗺️ Overview and places</h3>
|
||||||
|
<p>Who is online with what, speed now, the last 30 days, and a map of where people connect from, at city level.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🩺 Repairs itself</h3>
|
||||||
|
<p>Health checks with one-click fixes, and a watchdog that checks the tunnels, access rules and portal every minute and mends them.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>📦 Updates and backups</h3>
|
||||||
|
<p>Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
## 🧩 How it works
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
you(["🛠️ You, in LuCI"]) -- "add a person" --> link["🔗 Their link"]
|
||||||
|
link -- "they open it" --> portal["📱 Their portal"]
|
||||||
|
portal -- "add a device" --> app["App and connection"]
|
||||||
|
app == "AmneziaWG tunnel" ==> router["🌅 Dawnline<br>on your router"]
|
||||||
|
router -- "if allowed" --> home["🏠 Home network"]
|
||||||
|
router -- "if allowed" --> net["🌍 Internet"]
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **You add a person** in LuCI and choose what they may reach, their device
|
||||||
|
limit, an end date or a data limit.
|
||||||
|
2. **They open their link** on any device. The portal is theirs alone: it shows
|
||||||
|
their devices and their access; access and limits stay yours to change.
|
||||||
|
3. **They add a device.** The portal points them to the app for that system and
|
||||||
|
hands over the connection; the router gives each device its own keys.
|
||||||
|
4. **The device connects** through the router's AmneziaWG server, and Dawnline
|
||||||
|
lets through what that person may reach, counts their traffic and keeps to
|
||||||
|
their limits.
|
||||||
|
|
||||||
|
## 📸 A closer look
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/screenshots/overview.png" alt="Overview: who is online, speed, the last 30 days and where people connect from" width="720">
|
||||||
|
<br>
|
||||||
|
<sub><b>Overview</b>: who is online, speed now, the last 30 days and a map of where people connect from.</sub>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<img alt="People: everyone on the server, with their devices, data and state" src="docs/screenshots/people.png">
|
||||||
|
<p align="center"><sub><b>People</b>: online, ending soon, over the limit, outside their hours, paused.</sub></p>
|
||||||
|
</td>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<img alt="A person: their devices, traffic, places and limits" src="docs/screenshots/person.png">
|
||||||
|
<p align="center"><sub><b>A person</b>: their devices, traffic, places and limits.</sub></p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
## 📋 Requirements
|
||||||
|
|
||||||
|
| | What Dawnline needs |
|
||||||
|---|---|
|
|---|---|
|
||||||
|  |  |
|
| **OpenWrt** | 24.10 (opkg, `.ipk`) or 25.12 (apk, `.apk`) |
|
||||||
|
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: the installer adds a build made for your firmware when they are missing |
|
||||||
|
| **Free flash** | about 2 MB |
|
||||||
|
|
||||||
| Personal portal | Home network access |
|
## 📥 Install
|
||||||
|---|---|
|
|
||||||
|  |  |
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- **People, not peers.** One card per person with device chips, live status,
|
|
||||||
traffic, end date and data limit. Add a person, send them the link or the
|
|
||||||
invite card (QR code), and they do the rest.
|
|
||||||
- **Personal portal.** Every person gets a link made of three words
|
|
||||||
(`https://vpn.example.com/kamiro-telosu-bavine`). The link is the key: no
|
|
||||||
accounts, no sessions, and a new link locks the old one out at once. People
|
|
||||||
add, rename and remove their devices and get each one as a QR code,
|
|
||||||
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
|
|
||||||
access or limits. Links work on 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
|
|
||||||
sees over DHCP). Devices of different people reach each other never, always,
|
|
||||||
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.
|
|
||||||
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
|
|
||||||
or total data limits, allowed hours, pause one person or everyone. Devices
|
|
||||||
drop off the tunnel at once (`awg syncconf`, no interface restart).
|
|
||||||
- **Disguise presets** for AmneziaWG obfuscation (junk packets,
|
|
||||||
header and padding parameters), with what each preset needs from the apps.
|
|
||||||
- **Internet like a home device.** Tunnel clients' internet traffic enters the
|
|
||||||
router from the LAN, through a small network namespace on the LAN bridge
|
|
||||||
(needs `kmod-veth`). Whatever handles LAN traffic on the router (proxies, DPI
|
|
||||||
bypass, DNS filters, the `lan` zone) handles VPN clients too, with no
|
|
||||||
per-tool integration.
|
|
||||||
- **Overview.** Who is online with what, speed now, today and the last 30 days,
|
|
||||||
and a map of where people connect from (city level).
|
|
||||||
- **Diagnostics.** Health checks with one-click fixes, including the ones that
|
|
||||||
matter for reaching the portal from outside (DNS, port forwards, reply
|
|
||||||
routing behind proxies such as SSClash/Mihomo, certificate coverage). A
|
|
||||||
watchdog checks the tunnels, access rules, portal, resolver and LuCI link
|
|
||||||
every minute and repairs them on its own (a cron job looks after the agent
|
|
||||||
itself). One log holds people's activity and the service log: tunnel starts
|
|
||||||
and stops with netifd's reasons, repairs and errors (`dawnline log` on the
|
|
||||||
router).
|
|
||||||
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
|
|
||||||
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
|
|
||||||
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
|
|
||||||
the few OpenWrt packages Dawnline adds.
|
|
||||||
- **Backups** nightly and before risky operations, JSON export/import to move
|
|
||||||
to another router.
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
- OpenWrt **24.10** (opkg, `.ipk`) or **25.12** (apk, `.apk`)
|
|
||||||
- AmneziaWG (`kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`):
|
|
||||||
the installer adds a build made for your firmware when it is missing
|
|
||||||
- About 2 MB of free flash
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
On the router:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||||
@@ -92,17 +184,21 @@ sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline
|
|||||||
|
|
||||||
The installer checks the firmware, the clock, free space and DNS, lets you pick
|
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
|
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,
|
changes anything. It downloads the package for your package manager, checks it
|
||||||
checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware
|
against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
|
||||||
if it is missing, then installs Dawnline with its dependencies and checks that
|
missing, then installs Dawnline and checks that LuCI can reach it.
|
||||||
LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup
|
|
||||||
wizard.
|
|
||||||
|
|
||||||
Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
|
> [!NOTE]
|
||||||
and the service state to `/etc/dawnline/installer-backups/` (the newest three
|
> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
|
||||||
are kept); if a step fails, it puts them back. Packages are not rolled back: to
|
> and the service state to `/etc/dawnline/installer-backups/` (the newest three
|
||||||
return to an older release, run the installer with `--tag`. Everything it does
|
> are kept), and puts them back if a step fails. Packages are not rolled back:
|
||||||
is logged to `/tmp/dawnline-install.log`.
|
> to return to an older release, run the installer with `--tag`. Everything it
|
||||||
|
> does is logged to `/tmp/dawnline-install.log`.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Installer options</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
With options, download it first:
|
With options, download it first:
|
||||||
|
|
||||||
@@ -119,39 +215,64 @@ sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
|
|||||||
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
|
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
|
||||||
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
|
| `-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) |
|
| `--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 |
|
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov], then [2Grey] (`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` |
|
| `--no-awg` | Same as `--awg skip` |
|
||||||
|
|
||||||
When GitHub is slow or blocked, the installer retries downloads through
|
</details>
|
||||||
`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
|
|
||||||
through a mirror:
|
<details>
|
||||||
|
<summary><b>When GitHub is slow or blocked</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
The installer retries downloads through `ghfast.top` and `gh-proxy.com` on its
|
||||||
|
own. To fetch the installer itself through a mirror:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.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)"
|
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):
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Installing by hand</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
From a [release](https://github.com/tickcount/luci-app-dawnline/releases):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
|
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
|
||||||
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
|
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
|
||||||
```
|
```
|
||||||
|
|
||||||
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
|
</details>
|
||||||
keys and history are kept, and a backup is made first.
|
|
||||||
|
|
||||||
**Remove** on the router:
|
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Updates</kbd>, or run the installer
|
||||||
|
again. Settings, keys and history are kept, and a backup is made first.
|
||||||
|
|
||||||
|
### Remove
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.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
|
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
|
||||||
removal (the same as **Settings → Remove Dawnline from this router**), removes
|
removal (the same as <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>),
|
||||||
the package and cleans up what is left. AmneziaWG stays installed, since other
|
removes the package and cleans up what is left. After installing Dawnline
|
||||||
tunnels may use it. After installing Dawnline again, restore the backup in
|
again, restore the backup in <kbd>Settings</kbd> › <kbd>Backups</kbd>.
|
||||||
**Settings → Backups**. With options, download it first:
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> AmneziaWG stays installed, since other tunnels may use it. Add `--remove-awg`
|
||||||
|
> to take it away too.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Uninstaller options</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
With options, download it first:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
|
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
|
||||||
@@ -165,25 +286,83 @@ sh /tmp/dawnline-uninstall.sh --dry-run
|
|||||||
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
|
| `--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 |
|
| `-n`, `--dry-run` | Show what would be removed; change nothing |
|
||||||
|
|
||||||
By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then
|
By hand: <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>
|
||||||
`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
|
(keeps a backup), then `opkg remove luci-app-dawnline` or
|
||||||
|
`apk del luci-app-dawnline`.
|
||||||
|
|
||||||
## What Dawnline changes on the router
|
</details>
|
||||||
|
|
||||||
|
## ❓ FAQ
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Which apps do people use?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
AmneziaVPN or AmneziaWG on phones and computers, and plain WireGuard when the
|
||||||
|
disguise is off. The portal shows each person the app for their system and how
|
||||||
|
to add the connection in it.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>What happens when someone loses their link?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
Make a new one on their page. The old link stops working at once; their devices
|
||||||
|
keep working, unless you tick the ones to remove with it.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Does it touch the rest of my router?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
Only what it created, and `dawnline teardown` removes all of it. The full list
|
||||||
|
is under [What Dawnline changes on the router](#-what-dawnline-changes-on-the-router).
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>How do I move to another router?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<kbd>Export JSON</kbd> in <kbd>Settings</kbd> › <kbd>Backups</kbd> on the old
|
||||||
|
one, install Dawnline on the new one and import the file there.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Where do the places on the map come from?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
From the address a device connects from, looked up at city level and cached on
|
||||||
|
the router. It can be turned off in <kbd>Settings</kbd>.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## 🧾 What Dawnline changes on the router
|
||||||
|
|
||||||
Only objects it created: network interfaces tagged `_dawnline`, firewall
|
Only objects it created: network interfaces tagged `_dawnline`, firewall
|
||||||
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
|
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
|
||||||
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
|
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
|
||||||
latter a port of the LAN bridge), policy rules for the tunnel interfaces with
|
latter a port of the LAN bridge, which needs `kmod-veth`), policy rules for the
|
||||||
one routing table, a second dnsmasq instance on port 5354
|
tunnel interfaces with one routing table, a second dnsmasq instance on port
|
||||||
(`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check
|
5354 (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat
|
||||||
and, while the portal is on, a uhttpd instance for it. `dawnline teardown`
|
check and, while the portal is on, a uhttpd instance for it.
|
||||||
removes all of them.
|
`dawnline teardown` removes all of them.
|
||||||
|
|
||||||
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
|
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
|
||||||
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
|
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
|
||||||
are kept in `/var/run/dawnline` and flushed to flash at most hourly.
|
are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access
|
||||||
|
changes reach the tunnel with `awg syncconf`, without restarting the interface;
|
||||||
|
`dawnline log` on the router shows the service log.
|
||||||
|
|
||||||
## Development
|
## 🛠️ Development
|
||||||
|
|
||||||
```
|
```
|
||||||
package/luci-app-dawnline/
|
package/luci-app-dawnline/
|
||||||
@@ -205,17 +384,25 @@ npm ci
|
|||||||
npm run format # Prettier
|
npm run format # Prettier
|
||||||
npm run ci # format check, types, tests, minified bundles
|
npm run ci # format check, types, tests, minified bundles
|
||||||
|
|
||||||
scripts/lint-ucode.py # static ucode checks
|
scripts/lint-ucode.py # static ucode checks
|
||||||
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
||||||
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
||||||
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
||||||
scripts/frame-screenshots.py # frame docs/screenshots/raw/*.png for this README
|
scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
|
||||||
|
scripts/frame-screenshots.py # frame them for this README
|
||||||
```
|
```
|
||||||
|
|
||||||
The web bundles are committed: CI fails when they are out of date. Pushing a
|
The web bundles are committed: CI fails when they are out of date. Pushing a
|
||||||
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK
|
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK
|
||||||
and publishes a release with `sha256sums.txt`.
|
and publishes a release with `sha256sums.txt`.
|
||||||
|
|
||||||
## License
|
---
|
||||||
|
|
||||||
[MIT](LICENSE)
|
<div align="center">
|
||||||
|
<sub>Made for OpenWrt · <a href="LICENSE">MIT license</a> · <a href="#readme">Back to top ↑</a></sub>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
[AmneziaWG]: https://docs.amnezia.org/
|
||||||
|
[Liminal]: https://github.com/tickcount/openwrt-liminal
|
||||||
|
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
|
||||||
|
[2Grey]: https://github.com/2Grey/awg-openwrt
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#ffffff"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#0a0a0a"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0a0a0a" fill-opacity=".5"/></svg>
|
||||||
|
After Width: | Height: | Size: 254 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#0a0a0a"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#ffffff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#ffffff" fill-opacity=".5"/></svg>
|
||||||
|
After Width: | Height: | Size: 254 B |
|
Before Width: | Height: | Size: 287 KiB |
|
Before Width: | Height: | Size: 427 KiB |
|
Before Width: | Height: | Size: 283 KiB After Width: | Height: | Size: 457 KiB |
|
Before Width: | Height: | Size: 283 KiB After Width: | Height: | Size: 397 KiB |
|
Before Width: | Height: | Size: 323 KiB After Width: | Height: | Size: 430 KiB |
|
Before Width: | Height: | Size: 274 KiB After Width: | Height: | Size: 363 KiB |
|
Before Width: | Height: | Size: 162 KiB |
|
Before Width: | Height: | Size: 344 KiB |
|
Before Width: | Height: | Size: 158 KiB After Width: | Height: | Size: 435 KiB |
|
Before Width: | Height: | Size: 159 KiB After Width: | Height: | Size: 373 KiB |
|
Before Width: | Height: | Size: 200 KiB After Width: | Height: | Size: 407 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 187 KiB |
@@ -779,8 +779,11 @@ select_release() {
|
|||||||
}
|
}
|
||||||
_tags="$(jsonfilter -i "$_rl" -e '@[@.draft=false && @.prerelease=false].tag_name' 2>/dev/null)"
|
_tags="$(jsonfilter -i "$_rl" -e '@[@.draft=false && @.prerelease=false].tag_name' 2>/dev/null)"
|
||||||
[ -n "$_tags" ] || _tags="$(jsonfilter -i "$_rl" -e '@[*].tag_name' 2>/dev/null)"
|
[ -n "$_tags" ] || _tags="$(jsonfilter -i "$_rl" -e '@[*].tag_name' 2>/dev/null)"
|
||||||
|
# Newest first. BusyBox sort ignores -t/-k numeric keys here (falls back to
|
||||||
|
# an ascending string sort), so pad each part and reverse-sort as strings.
|
||||||
_tags="$(printf '%s\n' "$_tags" | sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' |
|
_tags="$(printf '%s\n' "$_tags" | sed 's/^v//' | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' |
|
||||||
sort -t. -k1,1nr -k2,2nr -k3,3nr | uniq | head -n 10)"
|
awk -F. '{ printf "%06d%06d%06d %s\n", $1, $2, $3, $0 }' | sort -r | cut -d' ' -f2 |
|
||||||
|
uniq | head -n 10)"
|
||||||
_count=0
|
_count=0
|
||||||
for _t in $_tags; do _count=$((_count + 1)); done
|
for _t in $_tags; do _count=$((_count + 1)); done
|
||||||
[ "$_count" -gt 1 ] || return 0
|
[ "$_count" -gt 1 ] || return 0
|
||||||
@@ -1133,6 +1136,22 @@ install_awg() {
|
|||||||
ok "AmneziaWG $(pkg_version amneziawg-tools) installed"
|
ok "AmneziaWG $(pkg_version amneziawg-tools) installed"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# netifd reads its protocol handlers only when it starts: a network that was
|
||||||
|
# up before AmneziaWG was installed doesn't know the amneziawg protocol, and no
|
||||||
|
# tunnel can come up. Restarted detached and last, so an SSH session dropping
|
||||||
|
# with it can't cut the install short.
|
||||||
|
awg_netifd_restart() {
|
||||||
|
[ "$AWG_ACTION" != skip ] && [ -x /lib/netifd/proto/amneziawg.sh ] || return 0
|
||||||
|
ubus call network get_proto_handlers 2>/dev/null | grep -q '"amneziawg"' && return 0
|
||||||
|
msg "Restarting the network so it knows AmneziaWG (connections drop for a few seconds)"
|
||||||
|
log_line "INFO network restart: netifd has no amneziawg protocol handler"
|
||||||
|
(
|
||||||
|
trap '' HUP
|
||||||
|
sleep 2
|
||||||
|
/etc/init.d/network restart
|
||||||
|
) </dev/null >/dev/null 2>&1 &
|
||||||
|
}
|
||||||
|
|
||||||
install_dawnline() {
|
install_dawnline() {
|
||||||
_force=0
|
_force=0
|
||||||
case "$MODE" in reinstall | downgrade) _force=1 ;; esac
|
case "$MODE" in reinstall | downgrade) _force=1 ;; esac
|
||||||
@@ -1350,6 +1369,7 @@ main() {
|
|||||||
msg "Open LuCI → Network → Dawnline:"
|
msg "Open LuCI → Network → Dawnline:"
|
||||||
fi
|
fi
|
||||||
msg " $(lan_url)"
|
msg " $(lan_url)"
|
||||||
|
awg_netifd_restart
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
include $(TOPDIR)/rules.mk
|
include $(TOPDIR)/rules.mk
|
||||||
|
|
||||||
PKG_NAME:=luci-app-dawnline
|
PKG_NAME:=luci-app-dawnline
|
||||||
PKG_VERSION:=0.4.2
|
PKG_VERSION:=0.10.0
|
||||||
PKG_RELEASE:=1
|
PKG_RELEASE:=1
|
||||||
PKG_LICENSE:=MIT
|
PKG_LICENSE:=MIT
|
||||||
|
|
||||||
|
|||||||
@@ -5,25 +5,25 @@
|
|||||||
'require poll';
|
'require poll';
|
||||||
'require rpc';
|
'require rpc';
|
||||||
'require ui';
|
'require ui';
|
||||||
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
|
var vi=Object.create;var Po=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var wi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var ki=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var $i=(n,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of xi(e))!yi.call(n,a)&&a!==r&&Po(n,a,{get:()=>e[a],enumerable:!(o=bi(e,a))||o.enumerable});return n};var Ci=(n,e,r)=>(r=n!=null?vi(wi(n)):{},$i(e||!n||!n.__esModule?Po(r,"default",{value:n,enumerable:!0}):r,n));var Wo=ki((Uo,Go)=>{"use strict";var jo=(function(){var n=function(C,k){var y=236,w=17,b=C,H=r[k],f=null,g=0,M=null,T=[],z={},W=function(A,N){g=b*4+17,f=(function(S){for(var O=new Array(S),_=0;_<S;_+=1){O[_]=new Array(S);for(var j=0;j<S;j+=1)O[_][j]=null}return O})(g),q(0,0),q(g-7,0),q(0,g-7),V(),I(),de(A,N),b>=7&&Q(A),M==null&&(M=F(b,H,T)),ee(M,N)},q=function(A,N){for(var S=-1;S<=7;S+=1)if(!(A+S<=-1||g<=A+S))for(var O=-1;O<=7;O+=1)N+O<=-1||g<=N+O||(0<=S&&S<=6&&(O==0||O==6)||0<=O&&O<=6&&(S==0||S==6)||2<=S&&S<=4&&2<=O&&O<=4?f[A+S][N+O]=!0:f[A+S][N+O]=!1)},Z=function(){for(var A=0,N=0,S=0;S<8;S+=1){W(!0,S);var O=a.getLostPoint(z);(S==0||A>O)&&(A=O,N=S)}return N},I=function(){for(var A=8;A<g-8;A+=1)f[A][6]==null&&(f[A][6]=A%2==0);for(var N=8;N<g-8;N+=1)f[6][N]==null&&(f[6][N]=N%2==0)},V=function(){for(var A=a.getPatternPosition(b),N=0;N<A.length;N+=1)for(var S=0;S<A.length;S+=1){var O=A[N],_=A[S];if(f[O][_]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?f[O+j][_+Y]=!0:f[O+j][_+Y]=!1}},Q=function(A){for(var N=a.getBCHTypeNumber(b),S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[Math.floor(S/3)][S%3+g-8-3]=O}for(var S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[S%3+g-8-3][Math.floor(S/3)]=O}},de=function(A,N){for(var S=H<<3|N,O=a.getBCHTypeInfo(S),_=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<6?f[_][8]=j:_<8?f[_+1][8]=j:f[g-15+_][8]=j}for(var _=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<8?f[8][g-_-1]=j:_<9?f[8][15-_-1+1]=j:f[8][15-_-1]=j}f[g-8][8]=!A},ee=function(A,N){for(var S=-1,O=g-1,_=7,j=0,Y=a.getMaskFunction(N),J=g-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var ue=0;ue<2;ue+=1)if(f[O][J-ue]==null){var xe=!1;j<A.length&&(xe=(A[j]>>>_&1)==1);var te=Y(O,J-ue);te&&(xe=!xe),f[O][J-ue]=xe,_-=1,_==-1&&(j+=1,_=7)}if(O+=S,O<0||g<=O){O-=S,S=-S;break}}},B=function(A,N){for(var S=0,O=0,_=0,j=new Array(N.length),Y=new Array(N.length),J=0;J<N.length;J+=1){var ue=N[J].dataCount,xe=N[J].totalCount-ue;O=Math.max(O,ue),_=Math.max(_,xe),j[J]=new Array(ue);for(var te=0;te<j[J].length;te+=1)j[J][te]=255&A.getBuffer()[te+S];S+=ue;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[J],De.getLength()-1),So=Ae.mod(De);Y[J]=new Array(De.getLength()-1);for(var te=0;te<Y[J].length;te+=1){var To=te+So.getLength()-Y[J].length;Y[J][te]=To>=0?So.getAt(To):0}}for(var _o=0,te=0;te<N.length;te+=1)_o+=N[te].totalCount;for(var Gn=new Array(_o),Qt=0,te=0;te<O;te+=1)for(var J=0;J<N.length;J+=1)te<j[J].length&&(Gn[Qt]=j[J][te],Qt+=1);for(var te=0;te<_;te+=1)for(var J=0;J<N.length;J+=1)te<Y[J].length&&(Gn[Qt]=Y[J][te],Qt+=1);return Gn},F=function(A,N,S){for(var O=l.getRSBlocks(A,N),_=d(),j=0;j<S.length;j+=1){var Y=S[j];_.put(Y.getMode(),4),_.put(Y.getLength(),a.getLengthInBits(Y.getMode(),A)),Y.write(_)}for(var J=0,j=0;j<O.length;j+=1)J+=O[j].dataCount;if(_.getLengthInBits()>J*8)throw"code length overflow. ("+_.getLengthInBits()+">"+J*8+")";for(_.getLengthInBits()+4<=J*8&&_.put(0,4);_.getLengthInBits()%8!=0;)_.putBit(!1);for(;!(_.getLengthInBits()>=J*8||(_.put(y,8),_.getLengthInBits()>=J*8));)_.put(w,8);return B(_,O)};z.addData=function(A,N){N=N||"Byte";var S=null;switch(N){case"Numeric":S=c(A);break;case"Alphanumeric":S=p(A);break;case"Byte":S=u(A);break;case"Kanji":S=x(A);break;default:throw"mode:"+N}T.push(S),M=null},z.isDark=function(A,N){if(A<0||g<=A||N<0||g<=N)throw A+","+N;return f[A][N]},z.getModuleCount=function(){return g},z.make=function(){if(b<1){for(var A=1;A<40;A++){for(var N=l.getRSBlocks(A,H),S=d(),O=0;O<T.length;O++){var _=T[O];S.put(_.getMode(),4),S.put(_.getLength(),a.getLengthInBits(_.getMode(),A)),_.write(S)}for(var j=0,O=0;O<N.length;O++)j+=N[O].dataCount;if(S.getLengthInBits()<=j*8)break}b=A}W(!1,Z())},z.createTableTag=function(A,N){A=A||2,N=typeof N>"u"?A*4:N;var S="";S+='<table style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: "+N+"px;",S+='">',S+="<tbody>";for(var O=0;O<z.getModuleCount();O+=1){S+="<tr>";for(var _=0;_<z.getModuleCount();_+=1)S+='<td style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: 0px;",S+=" width: "+A+"px;",S+=" height: "+A+"px;",S+=" background-color: ",S+=z.isDark(O,_)?"#000000":"#ffffff",S+=";",S+='"/>';S+="</tr>"}return S+="</tbody>",S+="</table>",S},z.createSvgTag=function(A,N,S,O){var _={};typeof arguments[0]=="object"&&(_=arguments[0],A=_.cellSize,N=_.margin,S=_.alt,O=_.title),A=A||2,N=typeof N>"u"?A*4:N,S=typeof S=="string"?{text:S}:S||{},S.Line 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 S%2&&A>0?Ae.substring(0,Ae.length-S-1)+Array(S+1).join("▀"):Ae.substring(0,Ae.length-1)};return z.createASCII=function(A,N){if(A=A||1,A<2)return pe(N);A-=1,N=typeof N>"u"?A*2:N;var S=z.getModuleCount()*A+N*2,O=N,_=S-N,j,Y,J,ue,xe=Array(A+1).join("██"),te=Array(A+1).join(" "),De="",Ae="";for(j=0;j<S;j+=1){for(J=Math.floor((j-O)/A),Ae="",Y=0;Y<S;Y+=1)ue=1,O<=Y&&Y<_&&O<=j&&j<_&&z.isDark(J,Math.floor((Y-O)/A))&&(ue=0),Ae+=ue?xe:te;for(J=0;J<A;J+=1)De+=Ae+`
|
||||||
`}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
|
`}return De.substring(0,De.length-1)},z.renderTo2dContext=function(A,N){N=N||2;for(var S=z.getModuleCount(),O=0;O<S;O++)for(var _=0;_<S;_++)A.fillStyle=z.isDark(O,_)?"black":"white",A.fillRect(O*N,_*N,N,N)},z};n.stringToBytesFuncs={default:function(C){for(var k=[],y=0;y<C.length;y+=1){var w=C.charCodeAt(y);k.push(w&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(C,k){var y=(function(){for(var b=m(C),H=function(){var I=b.read();if(I==-1)throw"eof";return I},f=0,g={};;){var M=b.read();if(M==-1)break;var T=H(),z=H(),W=H(),q=String.fromCharCode(M<<8|T),Z=z<<8|W;g[q]=Z,f+=1}if(f!=k)throw f+" != "+k;return g})(),w=63;return function(b){for(var H=[],f=0;f<b.length;f+=1){var g=b.charCodeAt(f);if(g<128)H.push(g);else{var M=y[b.charAt(f)];typeof M=="number"?(M&255)==M?H.push(M):(H.push(M>>>8),H.push(M&255)):H.push(w)}}return H}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var C=[[],[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,y=7973,w=21522,b={},H=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return b.getBCHTypeInfo=function(f){for(var g=f<<10;H(g)-H(k)>=0;)g^=k<<H(g)-H(k);return(f<<10|g)^w},b.getBCHTypeNumber=function(f){for(var g=f<<12;H(g)-H(y)>=0;)g^=y<<H(g)-H(y);return f<<12|g},b.getPatternPosition=function(f){return C[f-1]},b.getMaskFunction=function(f){switch(f){case o.PATTERN000:return function(g,M){return(g+M)%2==0};case o.PATTERN001:return function(g,M){return g%2==0};case o.PATTERN010:return function(g,M){return M%3==0};case o.PATTERN011:return function(g,M){return(g+M)%3==0};case o.PATTERN100:return function(g,M){return(Math.floor(g/2)+Math.floor(M/3))%2==0};case o.PATTERN101:return function(g,M){return g*M%2+g*M%3==0};case o.PATTERN110:return function(g,M){return(g*M%2+g*M%3)%2==0};case o.PATTERN111:return function(g,M){return(g*M%3+(g+M)%2)%2==0};default:throw"bad maskPattern:"+f}},b.getErrorCorrectPolynomial=function(f){for(var g=s([1],0),M=0;M<f;M+=1)g=g.multiply(s([1,i.gexp(M)],0));return g},b.getLengthInBits=function(f,g){if(1<=g&&g<10)switch(f){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:"+f}else if(g<27)switch(f){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:"+f}else if(g<41)switch(f){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:"+f}else throw"type:"+g},b.getLostPoint=function(f){for(var g=f.getModuleCount(),M=0,T=0;T<g;T+=1)for(var z=0;z<g;z+=1){for(var W=0,q=f.isDark(T,z),Z=-1;Z<=1;Z+=1)if(!(T+Z<0||g<=T+Z))for(var I=-1;I<=1;I+=1)z+I<0||g<=z+I||Z==0&&I==0||q==f.isDark(T+Z,z+I)&&(W+=1);W>5&&(M+=3+W-5)}for(var T=0;T<g-1;T+=1)for(var z=0;z<g-1;z+=1){var V=0;f.isDark(T,z)&&(V+=1),f.isDark(T+1,z)&&(V+=1),f.isDark(T,z+1)&&(V+=1),f.isDark(T+1,z+1)&&(V+=1),(V==0||V==4)&&(M+=3)}for(var T=0;T<g;T+=1)for(var z=0;z<g-6;z+=1)f.isDark(T,z)&&!f.isDark(T,z+1)&&f.isDark(T,z+2)&&f.isDark(T,z+3)&&f.isDark(T,z+4)&&!f.isDark(T,z+5)&&f.isDark(T,z+6)&&(M+=40);for(var z=0;z<g;z+=1)for(var T=0;T<g-6;T+=1)f.isDark(T,z)&&!f.isDark(T+1,z)&&f.isDark(T+2,z)&&f.isDark(T+3,z)&&f.isDark(T+4,z)&&!f.isDark(T+5,z)&&f.isDark(T+6,z)&&(M+=40);for(var Q=0,z=0;z<g;z+=1)for(var T=0;T<g;T+=1)f.isDark(T,z)&&(Q+=1);var de=Math.abs(100*Q/g/g-50)/5;return M+=de*10,M},b})(),i=(function(){for(var C=new Array(256),k=new Array(256),y=0;y<8;y+=1)C[y]=1<<y;for(var y=8;y<256;y+=1)C[y]=C[y-4]^C[y-5]^C[y-6]^C[y-8];for(var y=0;y<255;y+=1)k[C[y]]=y;var w={};return w.glog=function(b){if(b<1)throw"glog("+b+")";return k[b]},w.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return C[b]},w})();function s(C,k){if(typeof C.length>"u")throw C.length+"/"+k;var y=(function(){for(var b=0;b<C.length&&C[b]==0;)b+=1;for(var H=new Array(C.length-b+k),f=0;f<C.length-b;f+=1)H[f]=C[f+b];return H})(),w={};return w.getAt=function(b){return y[b]},w.getLength=function(){return y.length},w.multiply=function(b){for(var H=new Array(w.getLength()+b.getLength()-1),f=0;f<w.getLength();f+=1)for(var g=0;g<b.getLength();g+=1)H[f+g]^=i.gexp(i.glog(w.getAt(f))+i.glog(b.getAt(g)));return s(H,0)},w.mod=function(b){if(w.getLength()
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?`
|
`)}function qi(n){let e=new Map(n.people.map(o=>[o.id,o.name])),r=new Map(n.people.flatMap(o=>o.devices.map(a=>[a.id,a.name])));return{people:e,devices:r}}function Fe(n,e,r,o="",a=[]){let i=qi(n),s=[...e.map(p=>({ts:p.ts,category:It(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
|
||||||
${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
|
${p.detail}`:""}`,where:Bt[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,dr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ki=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],cr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Lt.map(d=>t("option",{value:d,selected:d===a?"selected":null},ut[d])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ki.map(([d,c])=>t("option",{value:d},c)));oe(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await P.logsClear({...r,category:s.value,older_days:l.value})).removed}catch(c){U(be(c),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await P.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${cr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(cr(d),"success",3e3),o()},"negative")])}function Mt(n,e,r,o){let a=n==="device"?`Clears ${r}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${r}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${r}?`,[t("p",{class:"dl-muted"},a)],[ie()," ",D("Reset",async()=>{await G(()=>P.usageClear(n,e),"Traffic history reset")&&(ae(),o())},"negative")])}function ve(n,e,r){let o=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!o.classList.contains("on");eo(o,a),r?.(a)}},t("i"));return o}function eo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,r={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let o=t("div",{class:`dl-seg${r.cls?` ${r.cls}`:""}`,role:"radiogroup","aria-label":r.label??null,"data-value":e}),a=()=>o.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===o.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)o.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==o.dataset.value&&(r.optimistic!==!1&&(o.dataset.value=i,a()),r.onChange?.(i))}},s));return a(),o}function qe(n,e,r,o={}){return t("button",{type:"button",...o,class:`dl-chipbtn${e?" on":""}${o.class?` ${o.class}`:""}`,"aria-pressed":e?"true":"false",click:r},n)}function hn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function le(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Vi={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:""},Ji={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 Yi(n){let e={};for(let[r,o]of Object.entries(Ji))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Zi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Vi[d],i=r.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Yi(o),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config: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(`
|
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Qi(n){let e="";for(let r=0;r<n.length;r+=32768)e+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Zi(n,e))),a=r?await Xi(o):null;return`vpn://${Qi(a??o)}`}var ur=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Ot=n=>ur.find(e=>e.id===n),fn=n=>n.v3?"max":n.v2?"balanced":"off",jt=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,es={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},ts={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function pr(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:r<n?"on":""})))])}function gn(n,e,r,o,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ur.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[pr(l.stealth,"Stealth"),pr(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},(a?es:ts)[l.needs])])])}));return s(),i}function mr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var hr=[["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 ns(n){let e=c=>n[c]!=null&&n[c]!=="",r=hr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=hr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).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(`
|
`),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),me(l,"Parameters copied")}},"Copy as config")]),d])}function fr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function os(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
|
||||||
`).flatMap((s,l)=>l?[`
|
`).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
|
`,fr(s,e)]:[fr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[v(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[v("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes`)]),D([v("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),me(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function rs(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,n.server),o={qr:()=>t("div",{class:"dl-qr-pane"},[an(n.conf),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),D("Copy",()=>me(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>os(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function as(n,e,r,o){let a=Ot(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await se(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>P.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function is(n,e){let r=n.st,o=le(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=le(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=le(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Ot(e.preset)?e.preset:void 0,l=s??fn(r.awg),d=D("",()=>as(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[v("reset")," Generate new values"]:[`Switch to ${Ot(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=ge("UDP port",o,()=>Rt(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));P.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=ge("MTU",a,()=>Zo(a.value,e.mtus)),h=ge("Keep-alive",i,()=>Qo(i.value));return Nt("",[mr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[jt(e.preset)?ct("warn",[t("b",{},jt(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",gn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ns(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ce("Server public key",t("span",{c
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(`
|
`),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let E=r??null,R=r?.id,C,k=0,y=f=>{R!==f.id&&(R=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await P.updatesStatus().catch(()=>null);C=f?.job?.id,k=f?.now??0;let g=await P.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==C&&(E=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let w=null,b=0;for(;;){if(await ia(1e3),w=await P.updatesStatus().catch(()=>null),!w){if(++b>60)break;continue}b=0;let f=w.job;if(!f||!aa(f,R,C,k)){if(Date.now()-i>15e3)break;continue}if(y(f),E=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.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(`
|
`),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=oa(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=na((f.finished??w.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(w),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},E.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([D("Copy log",()=>me($.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
|
`),"Log copied")),m(!0)]),U(`${Mn[o]??"Update"}: ${E.error??"failed"}`,"error"),e.onDone?.(w),E;if(d.className="dl-pill ok",d.textContent="Finished",a&&w){let f=ra(w,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[v(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(w),f.update&&e.onUpdate){let g=w;h([m(),D(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return E}if(o==="app"&&E.to){let f=E.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let M=()=>{ui.menu?.flushCache(),location.reload()};h([m(),D("Reload now",M,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await ia(1500),(await P.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(M,800),E;return g.textContent="Services restarted. Reload the page to use the new version.",E}let H=o==="pkgs"?`Updated ${[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${E.to?` ${E.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},H)])),h([m()]),U(H,"success"),e.onDone?.(w),E}var Ds={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function sa(n,e,r,o){return!await se(`Install ${e}?`,r,"Install")||(await Vt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Tn(n){return sa("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 Jt(n,e,r){return n==="awg"?Tn(r):e.length?sa(`pkgs:${e.join(",")}`,Ds[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function la(n,e){if(n==="awg")return Tn(e);let r=await G(()=>P.updatesStatus());return r?Jt(n,r.needs?.[n]??[],e):!1}var As=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Hs={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function da(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=Xr(a,o,r),h=new Set,m="",E=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),R=()=>s.detected.lan||s.saved.lan||"",C=()=>(l?s.detected.wan||s.saved.wan:d)||"",k=()=>new Map(s.devices.map(I=>[I.name,I])),y=()=>{let I=k();return[...c&&R()?[R()]:[],...[...h].filter(Q=>Q!==R())].filter(Q=>Q!==C()).map(Q=>I.get(Q)??{name:Q,nets:[],missing:!0})},w=(I,V)=>{s=I,V&&(l=I.config.auto_wan,d=I.config.wan_device||I.detected.wan||I.saved.wan||"",c=I.config.auto_lan,p=I.config.lan_like,u=I.config.mesh??(I.config.device_mesh?"all":"off"),h=new Set(I.config.lan_devices),m=E()),q()},b=async I=>{let V=await P.interfaces(o).catch(Q=>(U(Q.message,"error"),null));V&&w(V,I)};function H(I){let V=c&&I.name===R(),Q=!!I.own||!!I.master||I.name===C()||V;return V||h.has(I.name)||!Q&&(I.nets.length>0||!!I.missing)}function f(I){let V=c&&I.name===R(),Q=I.name===C(),de=!V&&h.has(I.name),B=!(!!I.own||!!I.master||Q||V)&&(I.nets.length>0||de||!!I.missing),F=(de||V)&&!I.zone&&!I.missing,ne=I.missing?"Not present right now":I.own?"This server":I.master?`Port of ${I.master}`:Q?`Internet${I.zone?` · zone ${I.zone}`:""}`:I.nets.length?I.nets.join(", "):"No IPv4 network",pe=t("button",{type:"button",class:`dl-if${de?" sel":""}${V?" auto":""}${!B&&!de&&!V?" off":""}${F?" warn":""}`,"aria-pressed":de||V?"true":"false","aria-disabled":B?null:"true",click:()=>{B&&(h.has(I.name)?h.delete(I.name):h.add(I.name),q())}},[t("span",{class:"dl-if-ic"},v(Hs[I.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},I.name),t("span",{class:"dl-if-sub"},ne)]),V?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return he(pe,()=>[t("div",{class:"dl-tip-title"},I.name),t("div",{class:"dl-muted"},[I.logical?`Interface ${I.logical}`:"No netifd interface",I.zone?` · zone ${I.zone}`:" · no firewall zone"]),I.members.length?t("div",{class:"dl-muted"},`Ports: ${I.members.join(", ")}`):"",I.nets.length?t("div",{class:"dl-mono"},I.nets.join(", ")):"",F?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",I.master?t("div",{class:"dl-muted"},`Choose ${I.master} to include it.`):""]),pe}function g(){let I=s.like_home;return!p||!s.config.lan_li
Line truncated
|
||||||
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(t.push(e("pre",{},i.join(`
|
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(t("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(`
|
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(s(),e.push(t("h5",{},r(c[2])))):p?(a.length&&s(),o||(o=t("ul",{}),e.push(o)),o.appendChild(t("li",{},r(p[1])))):d.trim()?(o&&(o=null),a.push(d.trim())):s()}return i&&e.push(t("pre",{},i.join(`
|
||||||
`))),s(),t}function Zo(n){let t=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
|
`))),s(),e}function Ma(n){let e=[],r=!1;for(let o 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(`
|
`)){let a=/^#{1,6}\s+(.*)$/.exec(o);if(a){if(r=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(o)&&(r=!1);r||e.push(o)}return e.join(`
|
||||||
`).replace(/\n{3,}/g,`
|
`).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(`
|
`).trim()}async function Zt(n,e,r,o){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";oe(r,[i,a],[D([v("copy")," Copy"],()=>me(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await P.updatesNotes(n,e,o??"");s=Ma(l.body||"");let d=Ea(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(a,s.trim()?La(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var Sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Co=n=>n?Ue(n):"";function Js(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function _a(n,e){let r=n.st,o=r.policy,a=r.kept?.app,i=e?.update&&e.tag?e.tag:r.version,s=x=>()=>Zt("app",x,`What’s new in Dawnline ${x.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ys(n,e.tag,e.update?r.version:""):null,d=e?.tag??i,c=o.check&&r.auto?.check?r.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[o.interval]??24)*3600:0,p=(x,$)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},x),t("span",{class:"dl-comp-side-v"},$)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${r.repo}`,"_blank","noopener")},null,{label:`Reinstall ${r.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",r.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${r.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",r.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",r.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[r.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Co(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Co(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(x=>t("li",{},x))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",r.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Zs(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${r.repo}`,target:"_blank",rel:"noopener"},r.repo)]),p("Auto-update",[o.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},o.auto?o.mode==="immediate"?"as soon as found":`${Sa[o.interval]==="weekly"?"weekly":"daily"} at ${o.time}`:o.check?`checks ${Sa[o.interval]}`:"checks off")]),p("Last check",r.check?[re(r.check.time,r.now),c>r.now?t("span",{class:"dl-faint"},`· next in ${xt(c-r.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},o.keep?"Kept after the next update":"Off")])])])}function Ys(n,e,r){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let o=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await 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
|
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(r,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Js(o(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Zs(n){let e=t("div",{class:"dl-params-body"}),r=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return r.addEventListener("toggle",()=>{n.versOpen=r.open,n.versOpen&&Nn(n,e)}),n.versOpen&&Nn(n,e),r}async function Nn(n,e){let r=le("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),o=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");Ta(n,p)};r.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),o(r.value))});let a=t("div",{class:"dl-comp-tag"},[r,D("Install",()=>o(r.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),Nn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),D("Try again",()=>Nn(n,e))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let c=n.st.version;dom.content(e,[a,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Co(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===c?Ee("ok","Installed"):D("Install",()=>Ta(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Ta(n,e){let r=e.replace(/^v/,"");r.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${r}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${r}`,n.st.version)}function Pa(n,e){let r=n.st,o=r.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,d=!!e?.ru,c=r.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",p)}),o&&u.push({label:`Roll back to ${o.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${o.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let x=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((f,g,M)=>f!==null||g>0&&M[g-1]!==null),$=r.tunnels??[],h=$.length?`Switching restarts ${$.length===1?"the tunnel":`${$.length} tunnels`} for a few seconds: ${$.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=$.length>1?`${$.slice(0,-1).join(", ")} and ${$[$.length-1]}`:$[0],E=$.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",R=async f=>{let g=a[f];await se(p?`Switch to AmneziaWG ${g.gen}?`:`Install AmneziaWG ${g.gen}?`,`The ${g.label} build, ${g.version}. ${h}${g.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${f}${d?":ru":""}`,p?`Switching to AmneziaWG ${g.gen}`:"Installing AmneziaWG",p??void 0)},C=f=>{let g=a[f],M=s===f&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},g.gen?`AmneziaWG ${g.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${g.label} · ${g.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},g.version??"none yet"),t("span",{class:"dl-comp-bact"},M?Ee("ok","Active"):g.version?D(p?"Switch":"Install",()=>R(f),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},k=i.map(f=>a[f]?.newer?`${a[f].label} moves to ${a[f].newer.gen} with OpenWrt ${a[f].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
|
`)}a.push(p),l+=c-1}let s=D([v("more")],()=>Ce(s,[{label:"Export CSV",icon:v("download"),run:()=>Fe(r,o,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Fe(r,o,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},o.length>10?`latest 10 of ${o.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var In=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[r,o,a]=await Promise.all([P.status(30),e?P.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:r,ev:o?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let r=this.st.people.find(s=>s.id===this.id);if(!r)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=r;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let o=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&r.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>Ge(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>o.isConnected,apply:(s,l)=>this.apply(s,l)}),o}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,r){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o){r||(location.href=_t(this.p?.server));return}this.p=o,this.paint(r),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,r){var i;this.poller?.claim();let o=await G(()=>P.personUpdate(this.p.id,e),r);if(!o)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=o.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=o.person),this.p=o.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return St(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:_t(e.server)},this.st.servers.find(r=>r.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:_t(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Se(this.parts.crumbs,this.crumbs(),e),Se(this.parts.head,ja(this),e),Se(this.parts.traffic,Ua(this),e),Se(this.parts.devices,Ga(this),e),Se(this.parts.limits,Ya(this),e),this.paintPlaces(e),Se(this.parts.activity,Qa(this),e)}paintPlaces(e=!1){let r=Za(this);r&&Se(this.parts.places,r,e&&!this.mapOpen)}};var sl={ok:"check",warn:"alert",error:"x",skip:"pause"},Bn=class{constructor(e,r,o,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=r,this.events=o,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(r,o)}async run(e){let r=e?await An(e):await P.health().catch(()=>null);r&&(this.take(r),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let r=e.filter(s=>s.status==="error").length,o=e.filter(s=>s.status==="warn").length;dom.content(this.summary,r?ct("error",`${r} problem${r>1?"s":""} need attention.`):o?ct("warn",`${o} warnLine 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 });
|
`);function fi(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=El,n}function ht(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async o=>{let a=await e.render(o),i=document.createElement("div");return i.className="dl-root",i.append(fi(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var C1=ht(Yt),E1=ht(mt),L1=ht(Yt),M1=ht(zn),S1=ht(In),T1=ht(Un),_1=ht(Rn);function gi(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 P1=gi(""),D1=gi("log");return baseclass.extend({ activity: D1, diagnostics: T1, health: P1, overview: C1, people: E1, person: S1, server: L1, settings: M1, updates: _1 });
|
||||||
@@ -5,5 +5,7 @@ case "$ACTION" in ifup|ifdown|ifup-failed) ;; *) exit 0 ;; esac
|
|||||||
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
|
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
|
||||||
# In order (a quick down/up must not log up first).
|
# In order (a quick down/up must not log up first).
|
||||||
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
|
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
|
||||||
[ "$ACTION" = ifup ] && /usr/bin/dawnline sync >/dev/null 2>&1 &
|
# A disabled Dawnline leaves the tunnels empty: nothing would enforce end
|
||||||
|
# dates, limits or hours once the devices were loaded.
|
||||||
|
[ "$ACTION" = ifup ] && /etc/init.d/dawnline enabled && /usr/bin/dawnline sync >/dev/null 2>&1 &
|
||||||
exit 0
|
exit 0
|
||||||
@@ -21,9 +21,15 @@ start_portal() {
|
|||||||
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
|
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
|
||||||
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
|
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
|
||||||
|
|
||||||
|
# Portal processes at once: each loads the whole model (a burst of 16 could
|
||||||
|
# empty a 128 MB router), so four, and two on a router with little memory;
|
||||||
|
# the rest of 64 connections wait their turn.
|
||||||
|
local procs=4 mem
|
||||||
|
mem="$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)"
|
||||||
|
[ -n "$mem" ] && [ "$mem" -le 160 ] && procs=2
|
||||||
procd_open_instance portal
|
procd_open_instance portal
|
||||||
procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \
|
procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \
|
||||||
-D -n 16 -N 64 -t 20 -T 30 -k 10 -A 1 \
|
-D -n "$procs" -N 64 -t 20 -T 30 -k 10 -A 1 \
|
||||||
-s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http
|
-s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http
|
||||||
procd_set_param file "$cert"
|
procd_set_param file "$cert"
|
||||||
procd_set_param respawn 3600 5 0
|
procd_set_param respawn 3600 5 0
|
||||||
@@ -36,7 +42,8 @@ start_resolver() {
|
|||||||
procd_open_instance dns
|
procd_open_instance dns
|
||||||
procd_set_param command /usr/libexec/dawnline/resolver
|
procd_set_param command /usr/libexec/dawnline/resolver
|
||||||
procd_set_param file /var/etc/dawnline-dns.conf
|
procd_set_param file /var/etc/dawnline-dns.conf
|
||||||
procd_set_param respawn 3600 5 0
|
# A new config kills it (dawnline.resolver): back within a second, not five.
|
||||||
|
procd_set_param respawn 3600 1 0
|
||||||
procd_close_instance
|
procd_close_instance
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +66,8 @@ start_service() {
|
|||||||
stop_service() {
|
stop_service() {
|
||||||
mkdir -p /var/run/dawnline
|
mkdir -p /var/run/dawnline
|
||||||
date +%s > /var/run/dawnline/agent.stopped
|
date +%s > /var/run/dawnline/agent.stopped
|
||||||
|
# Copies procd doesn't know about (started by hand, or left by an older version) go too.
|
||||||
|
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' | xargs -r kill 2>/dev/null
|
||||||
}
|
}
|
||||||
|
|
||||||
reload_service() {
|
reload_service() {
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# Dawnline first-run / upgrade housekeeping.
|
# Dawnline first-run / upgrade housekeeping.
|
||||||
|
|
||||||
|
# Locations are off by default since 0.5.2 (lookups send addresses to a third
|
||||||
|
# party); a router that had them on by the old default keeps them on.
|
||||||
|
if [ -f /etc/config/dawnline ] && [ -z "$(uci -q get dawnline.settings.geo_enabled)" ]; then
|
||||||
|
uci -q set dawnline.settings.geo_enabled=1
|
||||||
|
uci -q commit dawnline
|
||||||
|
fi
|
||||||
|
|
||||||
[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG'
|
[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG'
|
||||||
config settings 'settings'
|
config settings 'settings'
|
||||||
option portal_enabled '0'
|
option portal_enabled '0'
|
||||||
@@ -17,6 +24,13 @@ uci -q commit dawnline
|
|||||||
rm -f /etc/dawnline/alerts.json
|
rm -f /etc/dawnline/alerts.json
|
||||||
# Backups moved into Settings.
|
# Backups moved into Settings.
|
||||||
rm -f /www/luci-static/resources/view/dawnline/backups.js
|
rm -f /www/luci-static/resources/view/dawnline/backups.js
|
||||||
|
# "Pause everyone" is gone: turning a server off does the same, so a
|
||||||
|
# router left paused keeps its servers off instead of letting everyone in.
|
||||||
|
if [ "$(uci -q get dawnline.settings.paused_all)" = 1 ]; then
|
||||||
|
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.=]*\)=server$/\1/p'); do uci -q set "dawnline.$s.enabled=0"; done
|
||||||
|
fi
|
||||||
|
uci -q delete dawnline.settings.paused_all
|
||||||
|
uci -q commit dawnline
|
||||||
# Portal assets moved out of the web root (served only with a valid code).
|
# Portal assets moved out of the web root (served only with a valid code).
|
||||||
rm -rf /usr/share/dawnline/portal/www/assets
|
rm -rf /usr/share/dawnline/portal/www/assets
|
||||||
|
|
||||||
@@ -43,6 +57,12 @@ grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root || {
|
|||||||
# A reload keeps LuCI logins but sometimes misses the plugin; restart only then.
|
# A reload keeps LuCI logins but sometimes misses the plugin; restart only then.
|
||||||
sleep 2
|
sleep 2
|
||||||
ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; }
|
ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; }
|
||||||
/etc/init.d/dawnline enable
|
# A fresh install starts the service; an upgrade restarts it only where the
|
||||||
/etc/init.d/dawnline restart
|
# admin had it on (a disabled Dawnline stays that way).
|
||||||
|
if [ "$PKG_UPGRADE" = 1 ]; then
|
||||||
|
/etc/init.d/dawnline enabled && /etc/init.d/dawnline restart
|
||||||
|
else
|
||||||
|
/etc/init.d/dawnline enable
|
||||||
|
/etc/init.d/dawnline restart
|
||||||
|
fi
|
||||||
exit 0
|
exit 0
|
||||||
@@ -12,11 +12,31 @@ import * as pc from 'dawnline.portalcert';
|
|||||||
import * as watchdog from 'dawnline.watchdog';
|
import * as watchdog from 'dawnline.watchdog';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
import * as store from 'dawnline.store';
|
import * as store from 'dawnline.store';
|
||||||
|
import * as devices from 'dawnline.devices';
|
||||||
import {
|
import {
|
||||||
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
|
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
|
|
||||||
const args = ARGV;
|
/** Options that take no value. */
|
||||||
|
const FLAGS = [ 'json', 'yes', 'conf' ];
|
||||||
|
|
||||||
|
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
|
||||||
|
const opts = {};
|
||||||
|
const args = [];
|
||||||
|
for (let i = 0; i < length(ARGV); i++) {
|
||||||
|
let a = ARGV[i];
|
||||||
|
if (a == '-n')
|
||||||
|
a = '--n';
|
||||||
|
if (substr(a, 0, 2) == '--') {
|
||||||
|
let name = substr(a, 2);
|
||||||
|
if (index(FLAGS, name) >= 0)
|
||||||
|
opts[name] = true;
|
||||||
|
else
|
||||||
|
opts[name] = ARGV[++i] ?? '';
|
||||||
|
}
|
||||||
|
else
|
||||||
|
push(args, a);
|
||||||
|
}
|
||||||
const cmd = args[0] ?? 'help';
|
const cmd = args[0] ?? 'help';
|
||||||
|
|
||||||
function out(v) {
|
function out(v) {
|
||||||
@@ -24,10 +44,41 @@ function out(v) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function opt(name, dflt) {
|
function opt(name, dflt) {
|
||||||
for (let i = 1; i < length(args); i++)
|
return opts[name] ?? dflt;
|
||||||
if (args[i] == `--${name}`)
|
}
|
||||||
return args[i + 1];
|
|
||||||
return dflt;
|
/** Fixed-width columns: a header, then one line per row. */
|
||||||
|
function table(cols, rows) {
|
||||||
|
let w = map(cols, (c) => length(c));
|
||||||
|
for (let r in rows)
|
||||||
|
for (let i, v in r)
|
||||||
|
w[i] = max(w[i], length(`${v}`));
|
||||||
|
let line = (r) => rtrim(join(' ', map(r, (v, i) => sprintf(`%-${w[i]}s`, `${v}`))));
|
||||||
|
out(line(cols));
|
||||||
|
for (let r in rows)
|
||||||
|
out(line(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `--since 30m|2h|3d|YYYY-MM-DD` as a time, or null. */
|
||||||
|
function since_time(s) {
|
||||||
|
if (!s)
|
||||||
|
return null;
|
||||||
|
let m = match(s, /^([0-9]+)([mhd])$/);
|
||||||
|
if (m)
|
||||||
|
return time() - +m[1] * { m: 60, h: 3600, d: 86400 }[m[2]];
|
||||||
|
m = match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
|
||||||
|
if (m)
|
||||||
|
return timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 0, min: 0, sec: 0 });
|
||||||
|
die('--since takes 30m, 2h, 3d or a date like 2026-10-18.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "5m", "3h", "2d": how long ago, for the lists. */
|
||||||
|
function ago(secs) {
|
||||||
|
return secs < 3600 ? `${int(secs / 60)}m` : secs < 86400 ? `${int(secs / 3600)}h` : `${int(secs / 86400)}d`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function the_person(m, slug) {
|
||||||
|
return m.people[slug ?? ''] ?? die(slug ? `Unknown person: ${slug}.` : 'Which person? Give their id (dawnline person ls).');
|
||||||
}
|
}
|
||||||
|
|
||||||
function help() {
|
function help() {
|
||||||
@@ -39,19 +90,24 @@ Usage: dawnline <command>
|
|||||||
sync Push devices and access rules to the tunnels
|
sync Push devices and access rules to the tunnels
|
||||||
status People and devices with live state (JSON)
|
status People and devices with live state (JSON)
|
||||||
health Run health checks (JSON)
|
health Run health checks (JSON)
|
||||||
|
person ls [--json] Everyone: id, name, access, state, devices, last seen
|
||||||
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
||||||
[--expires YYYY-MM-DD] [--quota GB]
|
[--expires YYYY-MM-DD] [--quota GB] [--server id]
|
||||||
person link <slug> Print the personal portal link
|
person link <id> Print the personal portal link
|
||||||
person rm <slug> Remove a person and their devices
|
person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
|
||||||
device add <slug> <name> [--kind phone|computer|tablet|router]
|
device ls [person] [--json]
|
||||||
|
device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
|
||||||
device conf <id> Print a device configuration (.conf)
|
device conf <id> Print a device configuration (.conf)
|
||||||
device rm <id> Remove a device
|
device rm <id> Remove a device
|
||||||
backup Create a backup in /etc/dawnline/backups
|
backup Create a backup in /etc/dawnline/backups
|
||||||
portal-cert Print the certificate and key the portal uses
|
portal-cert Print the certificate and key the portal uses
|
||||||
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
|
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
|
||||||
log Service log: tunnel and service starts, stops, repairs (newest first)
|
log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
|
||||||
|
Service log: tunnel and service starts, stops, repairs (newest first)
|
||||||
teardown Remove everything Dawnline created on the router
|
teardown Remove everything Dawnline created on the router
|
||||||
version`);
|
version
|
||||||
|
|
||||||
|
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -106,40 +162,100 @@ try {
|
|||||||
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
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 })));
|
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
|
||||||
}
|
}
|
||||||
else if (cmd == 'health')
|
else if (cmd == 'health') {
|
||||||
out(health.health());
|
let checks = health.health();
|
||||||
|
out(checks);
|
||||||
|
if (length(filter(checks, (c) => c.status == 'error')))
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
else if (cmd == 'person' && args[1] == 'ls') {
|
||||||
|
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
||||||
|
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
|
||||||
|
if (opts.json)
|
||||||
|
out(people);
|
||||||
|
else
|
||||||
|
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
|
||||||
|
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
|
||||||
|
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
|
||||||
|
]));
|
||||||
|
}
|
||||||
else if (cmd == 'person' && args[1] == 'add') {
|
else if (cmd == 'person' && args[1] == 'add') {
|
||||||
let id = store.transact((c, m) => 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'),
|
name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
|
||||||
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
|
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
|
||||||
}));
|
}));
|
||||||
let m2 = core.load();
|
let m2 = core.load();
|
||||||
out(core.portal_url(m2, m2.people[id]) ?? id);
|
live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
|
||||||
|
out(`Added ${m2.people[id].name} (${id})`);
|
||||||
|
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
|
||||||
}
|
}
|
||||||
else if (cmd == 'person' && args[1] == 'link') {
|
else if (cmd == 'person' && args[1] == 'link') {
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let p = m.people[args[2]] ?? die('Unknown person.');
|
let p = the_person(m, args[2]);
|
||||||
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.');
|
out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
|
||||||
}
|
}
|
||||||
else if (cmd == 'person' && args[1] == 'rm') {
|
else if (cmd == 'person' && args[1] == 'rm') {
|
||||||
store.transact((c, m) => core.delete_person(c, m, args[2]));
|
let m = core.load();
|
||||||
apply.sync();
|
let p = the_person(m, args[2]);
|
||||||
|
let n = length(p.devices);
|
||||||
|
if (n && !opts.yes)
|
||||||
|
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
|
||||||
|
store.transact((c, m) => core.delete_person(c, m, p.id));
|
||||||
|
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
|
||||||
|
let s = apply.sync();
|
||||||
|
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
|
||||||
|
if (s.warning)
|
||||||
|
warn(`dawnline: ${s.warning}\n`);
|
||||||
|
}
|
||||||
|
else if (cmd == 'device' && args[1] == 'ls') {
|
||||||
|
let m = core.load(), d = live.dump(m);
|
||||||
|
let who = args[2] ? the_person(m, args[2]) : null;
|
||||||
|
let rows = [];
|
||||||
|
for (let id, dev in m.devices) {
|
||||||
|
let p = m.people[dev.person];
|
||||||
|
if (!p || (who && p.id != who.id))
|
||||||
|
continue;
|
||||||
|
let peer = d.peers[dev.public_key];
|
||||||
|
let online = live.online(d, id, peer);
|
||||||
|
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
|
||||||
|
online, handshake: +(peer?.handshake ?? 0) });
|
||||||
|
}
|
||||||
|
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
|
||||||
|
if (opts.json)
|
||||||
|
out(rows);
|
||||||
|
else
|
||||||
|
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
|
||||||
|
r.id, r.person, r.name, r.kind, r.address,
|
||||||
|
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
|
||||||
|
]));
|
||||||
}
|
}
|
||||||
else if (cmd == 'device' && args[1] == 'add') {
|
else if (cmd == 'device' && args[1] == 'add') {
|
||||||
// Keys first: generating them runs the awg tool, not worth holding the config lock for.
|
// Through the same door as LuCI and the portal: event, "issued" marker, capability check.
|
||||||
let keys = awg.new_keys();
|
let m = core.load();
|
||||||
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys }));
|
let p = the_person(m, args[2]);
|
||||||
apply.sync();
|
if (!args[3])
|
||||||
out(id);
|
die('Which name? dawnline device add <person> <name>.');
|
||||||
|
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
|
||||||
|
if (opts.conf)
|
||||||
|
print(r.config.conf);
|
||||||
|
else
|
||||||
|
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
|
||||||
|
if (r.warning)
|
||||||
|
warn(`dawnline: ${r.warning}\n`);
|
||||||
}
|
}
|
||||||
else if (cmd == 'device' && args[1] == 'conf') {
|
else if (cmd == 'device' && args[1] == 'conf') {
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let d = m.devices[args[2]] ?? die('Unknown device.');
|
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
|
||||||
|
awg.mark_issued(m, d.id);
|
||||||
print(awg.client_config(m, d).conf);
|
print(awg.client_config(m, d).conf);
|
||||||
}
|
}
|
||||||
else if (cmd == 'device' && args[1] == 'rm') {
|
else if (cmd == 'device' && args[1] == 'rm') {
|
||||||
store.transact((c, m) => core.delete_device(c, m, args[2]));
|
let m = core.load();
|
||||||
apply.sync();
|
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
|
||||||
|
let r = devices.remove(d.id, { by: 'admin' });
|
||||||
|
out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
|
||||||
|
if (r.warning)
|
||||||
|
warn(`dawnline: ${r.warning}\n`);
|
||||||
}
|
}
|
||||||
else if (cmd == 'backup')
|
else if (cmd == 'backup')
|
||||||
out(backup.backup_create(opt('reason')));
|
out(backup.backup_create(opt('reason')));
|
||||||
@@ -153,7 +269,22 @@ try {
|
|||||||
out(`${core.portal_http_port(m)}`);
|
out(`${core.portal_http_port(m)}`);
|
||||||
}
|
}
|
||||||
else if (cmd == 'log') {
|
else if (cmd == 'log') {
|
||||||
for (let e in watchdog.view(core.load()).log) {
|
let n = +opt('n', 0) || 0;
|
||||||
|
let since = since_time(opt('since'));
|
||||||
|
let level = opt('level'), src = opt('src');
|
||||||
|
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
|
||||||
|
die('--level takes error, down, repair, up or info.');
|
||||||
|
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
|
||||||
|
die('--src takes awg, dawnline or portal.');
|
||||||
|
let log = filter(slog_read(n && !since && !level && !src ? n : null),
|
||||||
|
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
|
||||||
|
if (n && length(log) > n)
|
||||||
|
log = slice(log, 0, n);
|
||||||
|
if (opts.json) {
|
||||||
|
out(log);
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
for (let e in log) {
|
||||||
let t = localtime(e.ts);
|
let t = localtime(e.ts);
|
||||||
let text = e.by == 'admin'
|
let text = e.by == 'admin'
|
||||||
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
|
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
|
||||||
@@ -197,8 +328,12 @@ try {
|
|||||||
apply.teardown();
|
apply.teardown();
|
||||||
else if (cmd == 'version')
|
else if (cmd == 'version')
|
||||||
out(VERSION);
|
out(VERSION);
|
||||||
else
|
else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
|
||||||
help();
|
help();
|
||||||
|
else {
|
||||||
|
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
|
||||||
|
exit(2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
warn(`dawnline: ${e.message}\n`);
|
warn(`dawnline: ${e.message}\n`);
|
||||||
|
|||||||
@@ -11,9 +11,9 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
import * as uloop from 'uloop';
|
import * as uloop from 'uloop';
|
||||||
import { readfile, writefile, stat, unlink } from 'fs';
|
import { open, readfile, writefile, stat, unlink } from 'fs';
|
||||||
import {
|
import {
|
||||||
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
|
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
@@ -34,6 +34,21 @@ const LOG_FLUSH = { '10min': 600, hourly: 3600 };
|
|||||||
const RESYNC_EVERY = 600;
|
const RESYNC_EVERY = 600;
|
||||||
const CONFIG_FILE = '/etc/config/dawnline';
|
const CONFIG_FILE = '/etc/config/dawnline';
|
||||||
|
|
||||||
|
// One agent, procd's. A second copy would run forever beside it with the code
|
||||||
|
// it started with: its own events (pauses and resumes from stale states), its
|
||||||
|
// own counters and syncs. It takes no arguments: the commands are `dawnline`'s.
|
||||||
|
if (length(ARGV)) {
|
||||||
|
warn(`The agent takes no arguments (procd runs it). For commands use: dawnline ${join(' ', ARGV)}\n`);
|
||||||
|
exit(2);
|
||||||
|
}
|
||||||
|
ensure_dir(RUN_DIR);
|
||||||
|
// Held as long as the process lives; close-on-exec, so children don't keep it.
|
||||||
|
let instance = open(`${RUN_DIR}/agent.lock`, 'we');
|
||||||
|
if (!instance?.lock('xn')) {
|
||||||
|
warn(`The agent is already running (${RUN_DIR}/agent.lock is held). Use /etc/init.d/dawnline restart.\n`);
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
let usage = live.load_usage();
|
let usage = live.load_usage();
|
||||||
let last_states = null;
|
let last_states = null;
|
||||||
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
||||||
@@ -111,21 +126,24 @@ let conf_mtime = null;
|
|||||||
let cert_mtime = null;
|
let cert_mtime = null;
|
||||||
|
|
||||||
const REASON = {
|
const REASON = {
|
||||||
paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached',
|
paused: 'paused by admin', expired: 'end date reached',
|
||||||
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active',
|
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', server_off: 'server turned off',
|
||||||
|
active: 'active',
|
||||||
};
|
};
|
||||||
|
|
||||||
function check_people(m, states, events) {
|
function check_people(m, states, events) {
|
||||||
let ts = time();
|
let ts = time();
|
||||||
for (let id, p in m.people) {
|
for (let id, p in m.people) {
|
||||||
let st = states[id], prev = last_states?.[id];
|
let st = states[id], prev = last_states?.[id];
|
||||||
// The admin's own pauses are logged by rpcd when they happen; here only
|
// The admin's own pauses (and turning a server off or on) are logged by
|
||||||
// what changes on its own (end date, data limit, allowed hours).
|
// rpcd when they happen; here only what changes on its own (end date,
|
||||||
let by_admin = (x) => x == 'paused' || x == 'paused_all';
|
// data limit, allowed hours).
|
||||||
|
let by_admin = (x) => x == 'paused' || x == 'server_off';
|
||||||
if (prev != null && prev != st && !by_admin(prev) && !by_admin(st))
|
if (prev != null && prev != st && !by_admin(prev) && !by_admin(st))
|
||||||
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
|
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
|
||||||
// "Remove their devices" when the end date passes.
|
// "Remove their devices" when the end date passes: irreversible, so never
|
||||||
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) {
|
// on a clock that has not been set yet (a router before NTP is in 1970).
|
||||||
|
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices) && localtime(ts).year >= 2025) {
|
||||||
store.transact((c, mm) => {
|
store.transact((c, mm) => {
|
||||||
for (let d in mm.people[id]?.devices ?? [])
|
for (let d in mm.people[id]?.devices ?? [])
|
||||||
core.delete_device(c, mm, d);
|
core.delete_device(c, mm, d);
|
||||||
@@ -136,32 +154,6 @@ function check_people(m, states, events) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let last_home = 0;
|
|
||||||
|
|
||||||
/** Locate new client addresses for the admin map (a couple per minute). */
|
|
||||||
function check_geo(m) {
|
|
||||||
if (!m.settings.geo_enabled)
|
|
||||||
return;
|
|
||||||
let cache = geo.load();
|
|
||||||
let ips = [];
|
|
||||||
for (let id, rec in usage.devices)
|
|
||||||
for (let ip in keys(rec.ips ?? {}))
|
|
||||||
push(ips, ip);
|
|
||||||
let changed = geo.resolve(m.settings, cache, ips, 2);
|
|
||||||
if (time() - last_home > 3600) {
|
|
||||||
last_home = time();
|
|
||||||
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
|
||||||
changed = geo.resolve_home(m.settings, cache, wan) || changed;
|
|
||||||
}
|
|
||||||
if (changed)
|
|
||||||
geo.save(cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
function place_of(ip) {
|
|
||||||
let pl = geo.place(geo.load(), ip);
|
|
||||||
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Connections from home: the DHCP name of the address, as it is now. */
|
/** Connections from home: the DHCP name of the address, as it is now. */
|
||||||
function named(e) {
|
function named(e) {
|
||||||
let h = net.event_hosts(e, net.lan_names());
|
let h = net.event_hosts(e, net.lan_names());
|
||||||
@@ -198,6 +190,116 @@ function save_presence(people) {
|
|||||||
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
|
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- locations ---------- */
|
||||||
|
|
||||||
|
// A lookup run: this many addresses at most, within this many seconds; a run
|
||||||
|
// still going after GEO_KILL seconds (past every timeout) is given up.
|
||||||
|
const GEO_PER_RUN = 3;
|
||||||
|
const GEO_BUDGET = 12;
|
||||||
|
const GEO_KILL = 60;
|
||||||
|
|
||||||
|
let last_home = 0;
|
||||||
|
// Addresses the watcher saw connect or roam that wait for a run.
|
||||||
|
let geo_pending = {};
|
||||||
|
// The run in a child process (uloop.task) and when it started; null when none.
|
||||||
|
let geo_task = null, geo_since = 0;
|
||||||
|
|
||||||
|
/** Every client address still shown on the map (the cache never pushes these out). */
|
||||||
|
function geo_shown() {
|
||||||
|
let ips = [];
|
||||||
|
for (let id, rec in usage.devices)
|
||||||
|
for (let ip in keys(rec.ips ?? {}))
|
||||||
|
push(ips, ip);
|
||||||
|
return uniq(ips);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* A run's results: into the cache (the agent is its only writer), onto the
|
||||||
|
* connections in the activity log that were logged before their place was
|
||||||
|
* known, and to open pages at once: the revision moves for the people seen
|
||||||
|
* from those addresses.
|
||||||
|
*/
|
||||||
|
function geo_done(found) {
|
||||||
|
let cache = geo.load();
|
||||||
|
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
|
||||||
|
return;
|
||||||
|
geo.save(cache);
|
||||||
|
let where = {};
|
||||||
|
for (let ip, r in found)
|
||||||
|
if (r)
|
||||||
|
where[ip] = geo.label(r);
|
||||||
|
if (!length(keys(where)))
|
||||||
|
return;
|
||||||
|
let m = watch_model(), people = {};
|
||||||
|
for (let id, rec in usage.devices)
|
||||||
|
for (let ip in keys(where))
|
||||||
|
if (rec.ips?.[ip] && m.devices[id])
|
||||||
|
people[m.devices[id].person] = true;
|
||||||
|
live.set_places(where, time() - 3600);
|
||||||
|
save_presence(keys(people));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Locate client addresses for the admin map in a child process: a lookup
|
||||||
|
* waits on the network for seconds, and neither the 1-second watcher nor the
|
||||||
|
* tick may wait with it. Addresses that just connected go first, at once
|
||||||
|
* (the watcher calls this on a connect); the tick adds anything still shown
|
||||||
|
* that is missing or stale (`more`). One run at a time, a few addresses each;
|
||||||
|
* what just connected and did not fit waits for the next run.
|
||||||
|
*/
|
||||||
|
function geo_lookup(m, more) {
|
||||||
|
if (!m.settings.geo_enabled) {
|
||||||
|
geo_pending = {};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (geo_task && !geo_task.finished()) {
|
||||||
|
if (time() - geo_since < GEO_KILL)
|
||||||
|
return;
|
||||||
|
geo_task.kill();
|
||||||
|
}
|
||||||
|
geo_task = null;
|
||||||
|
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
|
||||||
|
let want = slice(todo, 0, GEO_PER_RUN);
|
||||||
|
let rest = {};
|
||||||
|
for (let ip in slice(todo, GEO_PER_RUN))
|
||||||
|
if (geo_pending[ip])
|
||||||
|
rest[ip] = true;
|
||||||
|
geo_pending = rest;
|
||||||
|
if (!length(want))
|
||||||
|
return;
|
||||||
|
let provider = m.settings.geo_provider;
|
||||||
|
let t = null;
|
||||||
|
t = uloop.task(() => {
|
||||||
|
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
|
||||||
|
instance.close();
|
||||||
|
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
|
||||||
|
}, (found) => {
|
||||||
|
if (geo_task == t)
|
||||||
|
geo_task = null;
|
||||||
|
geo_done(found);
|
||||||
|
if (length(keys(geo_pending)))
|
||||||
|
geo_lookup(watch_model());
|
||||||
|
});
|
||||||
|
geo_task = t;
|
||||||
|
geo_since = time();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
|
||||||
|
function check_geo(m) {
|
||||||
|
geo_lookup(m, geo_shown());
|
||||||
|
if (!m.settings.geo_enabled || time() - last_home <= 3600)
|
||||||
|
return;
|
||||||
|
last_home = time();
|
||||||
|
let cache = geo.load();
|
||||||
|
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
||||||
|
if (geo.resolve_home(m.settings, cache, wan))
|
||||||
|
geo.save(cache);
|
||||||
|
}
|
||||||
|
|
||||||
|
function place_of(ip) {
|
||||||
|
return geo.label(geo.place(geo.load(), ip));
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* One look at the tunnels. Connects (a new handshake from a device that was
|
* 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;
|
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
|
||||||
@@ -220,6 +322,10 @@ function watch() {
|
|||||||
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
|
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
|
||||||
ep = live.endpoint_ip(peer.endpoint);
|
ep = live.endpoint_ip(peer.endpoint);
|
||||||
}
|
}
|
||||||
|
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
|
||||||
|
// again only with a new handshake, not the one remembered from before.
|
||||||
|
else
|
||||||
|
last_hs[id] = 0;
|
||||||
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
|
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
|
||||||
let was = last_online[id];
|
let was = last_online[id];
|
||||||
if (on && !was) {
|
if (on && !was) {
|
||||||
@@ -246,22 +352,24 @@ function watch() {
|
|||||||
}
|
}
|
||||||
if (!length(keys(people)))
|
if (!length(keys(people)))
|
||||||
return;
|
return;
|
||||||
// The status first, then what takes longer (a geo lookup may wait on the network).
|
|
||||||
save_presence(keys(people));
|
save_presence(keys(people));
|
||||||
if (!length(events))
|
if (!length(events))
|
||||||
return;
|
return;
|
||||||
live.collect(m, usage, d);
|
live.collect(m, usage, d);
|
||||||
live.save_usage(usage, false);
|
live.save_usage(usage, false);
|
||||||
if (m.settings.geo_enabled && length(ips)) {
|
// The event carries the place when the cache already knows it. A new
|
||||||
let cache = geo.load();
|
// address is looked up at once, in a child process (geo_lookup): its place
|
||||||
if (geo.resolve(m.settings, cache, ips, length(ips)))
|
// goes onto this event and the revision moves again when it is known.
|
||||||
geo.save(cache);
|
|
||||||
}
|
|
||||||
for (let e in events)
|
for (let e in events)
|
||||||
if (e.type == 'connect')
|
if (e.type == 'connect')
|
||||||
e.where = place_of(e.detail);
|
e.where = place_of(e.detail);
|
||||||
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
|
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
|
||||||
save_presence(keys(people));
|
save_presence(keys(people));
|
||||||
|
if (m.settings.geo_enabled && length(ips)) {
|
||||||
|
for (let ip in ips)
|
||||||
|
geo_pending[ip] = true;
|
||||||
|
geo_lookup(m);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// What the service log was already told. On flash: the public address often
|
// What the service log was already told. On flash: the public address often
|
||||||
@@ -276,6 +384,33 @@ function note(k, v) {
|
|||||||
write_json(NOTES, notes, 0o600);
|
write_json(NOTES, notes, 0o600);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* End dates in the activity log: a heads-up once per end date when its
|
||||||
|
* warning window opens, and "keep access" passing it (which changes no
|
||||||
|
* state, so nothing else would say it). Not on a clock that is not set.
|
||||||
|
*/
|
||||||
|
function check_expiry(m, events) {
|
||||||
|
let ts = time();
|
||||||
|
if (localtime(ts).year < 2025)
|
||||||
|
return;
|
||||||
|
for (let id, p in m.people) {
|
||||||
|
if (!p.expires)
|
||||||
|
continue;
|
||||||
|
let end = date_end(p.expires);
|
||||||
|
if (end == null)
|
||||||
|
continue;
|
||||||
|
let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
|
||||||
|
if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
|
||||||
|
note(`warned:${id}`, p.expires);
|
||||||
|
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
|
||||||
|
}
|
||||||
|
if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
|
||||||
|
note(`kept:${id}`, p.expires);
|
||||||
|
push(events, { type: 'expired_kept', person: id, detail: p.expires });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** "Jan 1 2027" from the certificate, or null. */
|
/** "Jan 1 2027" from the certificate, or null. */
|
||||||
function cert_end(path) {
|
function cert_end(path) {
|
||||||
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
|
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
|
||||||
@@ -339,7 +474,10 @@ function nightly_backup() {
|
|||||||
backup.backup_create('auto');
|
backup.backup_create('auto');
|
||||||
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
|
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
|
||||||
}
|
}
|
||||||
catch (e) {}
|
catch (e) {
|
||||||
|
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
|
||||||
|
slog('dawnline', 'error', `nightly backup failed: ${e.message}`, null, 'Backup');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -370,7 +508,9 @@ function check_usage_reset(m) {
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
* Push devices and access rules when people's states changed, the config
|
* Push devices and access rules when people's states changed, the config
|
||||||
* file was written (by anyone: rpcd, the portal, the CLI, a restore), or
|
* file was written (by anyone: rpcd, the portal, the CLI, a restore), the
|
||||||
|
* access table is gone (a flushed ruleset: the firewall alone would let every
|
||||||
|
* device reach everything, so the sync unloads them until it is back), or
|
||||||
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
||||||
*/
|
*/
|
||||||
function sync_runtime(t) {
|
function sync_runtime(t) {
|
||||||
@@ -379,7 +519,7 @@ function sync_runtime(t) {
|
|||||||
let mt = st ? `${st.mtime}/${st.inode}` : null;
|
let mt = st ? `${st.mtime}/${st.inode}` : null;
|
||||||
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
|
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
|
||||||
(conf_mtime != null && mt != conf_mtime);
|
(conf_mtime != null && mt != conf_mtime);
|
||||||
if (changed || time() - last_sync > RESYNC_EVERY) {
|
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
|
||||||
apply.sync(t.m, usage);
|
apply.sync(t.m, usage);
|
||||||
last_sync = time();
|
last_sync = time();
|
||||||
}
|
}
|
||||||
@@ -429,6 +569,7 @@ const STEPS = [
|
|||||||
{ who: 'People', run: (t) => {
|
{ who: 'People', run: (t) => {
|
||||||
t.states = apply.states_for(t.m, usage);
|
t.states = apply.states_for(t.m, usage);
|
||||||
check_people(t.m, t.states, t.events);
|
check_people(t.m, t.states, t.events);
|
||||||
|
check_expiry(t.m, t.events);
|
||||||
} },
|
} },
|
||||||
{ who: 'Access rules', run: (t) => {
|
{ who: 'Access rules', run: (t) => {
|
||||||
if (t.states)
|
if (t.states)
|
||||||
@@ -470,8 +611,13 @@ function step(i, s, fn) {
|
|||||||
function tick() {
|
function tick() {
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
writefile(watchdog.BEAT, `${time()}`);
|
writefile(watchdog.BEAT, `${time()}`);
|
||||||
// A restore or import drops the live counters; start over from flash.
|
// A restore or import put other counters on flash (dawnline.backup leaves
|
||||||
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
// a marker): start over from them, whatever the watcher wrote since.
|
||||||
|
if (stat(live.USAGE_RELOAD)) {
|
||||||
|
unlink(live.USAGE_RELOAD);
|
||||||
|
usage = live.load_usage(true);
|
||||||
|
}
|
||||||
|
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
||||||
usage = live.load_usage();
|
usage = live.load_usage();
|
||||||
let t = { m: null, pol: null, reset: false, events: [] };
|
let t = { m: null, pol: null, reset: false, events: [] };
|
||||||
for (let i, s in STEPS)
|
for (let i, s in STEPS)
|
||||||
@@ -481,8 +627,10 @@ function tick() {
|
|||||||
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
|
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
|
||||||
step('save', { who: 'Traffic' }, () => {
|
step('save', { who: 'Traffic' }, () => {
|
||||||
live.save_usage(usage, persist);
|
live.save_usage(usage, persist);
|
||||||
if (persist)
|
if (persist) {
|
||||||
last_flush = time();
|
last_flush = time();
|
||||||
|
geo.flush();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
|
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
|
||||||
step('events', { who: 'Activity' }, () => {
|
step('events', { who: 'Activity' }, () => {
|
||||||
@@ -497,6 +645,7 @@ function tick() {
|
|||||||
function shutdown() {
|
function shutdown() {
|
||||||
live.save_usage(usage, true);
|
live.save_usage(usage, true);
|
||||||
live.persist_events();
|
live.persist_events();
|
||||||
|
geo.flush();
|
||||||
slog_trim(true);
|
slog_trim(true);
|
||||||
// A clean stop: the next start is not a crash.
|
// A clean stop: the next start is not a crash.
|
||||||
unlink(watchdog.BEAT);
|
unlink(watchdog.BEAT);
|
||||||
@@ -514,7 +663,13 @@ if (was != VERSION) {
|
|||||||
writefile(`${DATA_DIR}/version`, VERSION);
|
writefile(`${DATA_DIR}/version`, VERSION);
|
||||||
}
|
}
|
||||||
slog_restore();
|
slog_restore();
|
||||||
if (was && was != VERSION)
|
// postupdate put this (kept) version back because the new one did not come up.
|
||||||
|
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
|
||||||
|
unlink(`${RUN_DIR}/update-rolled-back`);
|
||||||
|
if (rolled)
|
||||||
|
slog('dawnline', 'error', `update to ${rolled} failed its check — rolled back to ${VERSION}`,
|
||||||
|
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.', 'Dawnline');
|
||||||
|
else if (was && was != VERSION)
|
||||||
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
|
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
|
||||||
else if (crashed)
|
else if (crashed)
|
||||||
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
|
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# Cron, every 5 minutes: the watchdog lives in the agent, so this looks after
|
# Cron, every 5 minutes: the watchdog lives in the agent, so this looks after
|
||||||
# the agent itself and kills it when it runs but has stopped ticking (procd
|
# the agent itself: ends any copy that isn't procd's, and kills procd's when it
|
||||||
# starts it again). Off with the watchdog (Health → Watchdog).
|
# runs but has stopped ticking (procd starts it again; that part is off with
|
||||||
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
|
# the watchdog, Health → Watchdog).
|
||||||
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
|
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
|
||||||
|
|
||||||
|
# Only procd's agent: any other copy (started by hand, or left by an older version that let
|
||||||
|
# it start) runs stale code beside it, with its own events and syncs. Always ended.
|
||||||
|
for p in $(pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent'); do
|
||||||
|
[ "$p" = "$pid" ] || kill -9 "$p" 2>/dev/null
|
||||||
|
done
|
||||||
|
|
||||||
|
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
|
||||||
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
|
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
|
||||||
|
|
||||||
now="$(date +%s)"
|
now="$(date +%s)"
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Dawnline — after its own package was replaced: restart, check that the new
|
||||||
|
# version answers (the LuCI link and the agent), and put the kept previous
|
||||||
|
# version back when it does not. Started detached by the updater
|
||||||
|
# (usr/libexec/dawnline/updater) with the version being installed.
|
||||||
|
# postupdate <version>
|
||||||
|
# Plain shell on purpose: a release whose ucode does not compile cannot check
|
||||||
|
# or repair itself, and the admin cannot click Roll back in a page that this
|
||||||
|
# same backend serves.
|
||||||
|
RUN=/var/run/dawnline
|
||||||
|
KEEP=/etc/dawnline/keep/app
|
||||||
|
to="${1:-?}"
|
||||||
|
|
||||||
|
sleep 2
|
||||||
|
/etc/init.d/rpcd reload >/dev/null 2>&1
|
||||||
|
/etc/init.d/dawnline restart >/dev/null 2>&1
|
||||||
|
|
||||||
|
up() {
|
||||||
|
ubus list luci.dawnline >/dev/null 2>&1 || return 1
|
||||||
|
ubus -t 10 call luci.dawnline rev >/dev/null 2>&1 || return 1
|
||||||
|
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
|
||||||
|
i=0
|
||||||
|
while [ "$i" -lt 12 ]; do
|
||||||
|
sleep 5
|
||||||
|
i=$((i + 1))
|
||||||
|
up && exit 0
|
||||||
|
done
|
||||||
|
|
||||||
|
logger -t dawnline "update to $to failed its check: luci.dawnline or the agent is not up"
|
||||||
|
set --
|
||||||
|
for f in "$KEEP"/*.ipk "$KEEP"/*.apk; do
|
||||||
|
[ -f "$f" ] && set -- "$@" "$f"
|
||||||
|
done
|
||||||
|
if [ "$#" -eq 0 ]; then
|
||||||
|
logger -t dawnline "no previous version is kept: nothing to roll back to"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if command -v apk >/dev/null 2>&1; then
|
||||||
|
apk add --allow-untrusted "$@" >/dev/null 2>&1
|
||||||
|
else
|
||||||
|
opkg install --force-reinstall --force-downgrade "$@" >/dev/null 2>&1
|
||||||
|
fi
|
||||||
|
/etc/init.d/rpcd restart >/dev/null 2>&1
|
||||||
|
/etc/init.d/dawnline restart >/dev/null 2>&1
|
||||||
|
mkdir -p "$RUN"
|
||||||
|
# The restored agent reports it in the service log on its start.
|
||||||
|
echo "$to" > "$RUN/update-rolled-back"
|
||||||
|
logger -t dawnline "rolled back from $to to the kept version"
|
||||||
|
exit 0
|
||||||
@@ -72,6 +72,8 @@ const ctx = {
|
|||||||
pol: POL,
|
pol: POL,
|
||||||
work: `/tmp/dawnline-update.${PID}`,
|
work: `/tmp/dawnline-update.${PID}`,
|
||||||
log, phase, run, save,
|
log, phase, run, save,
|
||||||
|
// An automatic run (nobody is watching: the previous version is always kept).
|
||||||
|
auto: () => job.auto,
|
||||||
versions: (from, to) => {
|
versions: (from, to) => {
|
||||||
job.from = from;
|
job.from = from;
|
||||||
job.to = to;
|
job.to = to;
|
||||||
@@ -241,16 +243,23 @@ function auto() {
|
|||||||
install(todo);
|
install(todo);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The restarts the job asked for, in one go, after its final state is saved. */
|
/**
|
||||||
|
* The restarts the job asked for, in one go, after its final state is saved.
|
||||||
|
* Dawnline's own package is restarted by postupdate, a shell that also checks
|
||||||
|
* the new version and rolls back to the kept one when it does not come up.
|
||||||
|
*/
|
||||||
function restarts() {
|
function restarts() {
|
||||||
|
if (after.app) {
|
||||||
|
let to = replace(`${job.to ?? ''}`, /[^A-Za-z0-9.-]/g, '');
|
||||||
|
system(`/usr/libexec/dawnline/postupdate '${to}' </dev/null >/dev/null 2>&1 &`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let cmds = [];
|
let cmds = [];
|
||||||
if (after.app)
|
if (after.apply)
|
||||||
push(cmds, '/etc/init.d/rpcd reload');
|
|
||||||
else if (after.apply)
|
|
||||||
push(cmds, '/usr/bin/dawnline apply');
|
push(cmds, '/usr/bin/dawnline apply');
|
||||||
if (after.uhttpd)
|
if (after.uhttpd)
|
||||||
push(cmds, '/etc/init.d/uhttpd restart');
|
push(cmds, '/etc/init.d/uhttpd restart');
|
||||||
if (after.app || after.apply || after.uhttpd)
|
if (after.apply || after.uhttpd)
|
||||||
push(cmds, '/etc/init.d/dawnline restart');
|
push(cmds, '/etc/init.d/dawnline restart');
|
||||||
if (length(cmds))
|
if (length(cmds))
|
||||||
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
|
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated
|
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use strict";(()=>{var it=Object.create;var He=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var ft=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var dt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ct(t))!ut.call(e,u)&&u!==r&&He(e,u,{get:()=>t[u],enumerable:!(i=ot(t,u))||i.enumerable});return e};var ht=(e,t,r)=>(r=e!=null?it(lt(e)):{},dt(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));var 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
|
"use strict";(()=>{var Oo=Object.create;var On=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var Ko=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var qo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of No(e))!Fo.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(r=Ro(e,o))||r.enumerable});return t};var Go=(t,e,n)=>(n=t!=null?Oo(Io(t)):{},qo(e||!t||!t.__esModule?On(n,"default",{value:t,enumerable:!0}):n,t));var gr=Ko((hr,mr)=>{"use strict";var fr=(function(){var t=function(d,m){var s=236,h=17,f=d,E=n[m],p=null,l=0,L=null,x=[],C={},R=function(w,k){l=f*4+17,p=(function(y){for(var T=new Array(y),S=0;S<y;S+=1){T[S]=new Array(y);for(var D=0;D<y;D+=1)T[S][D]=null}return T})(l),I(0,0),I(l-7,0),I(0,l-7),et(),Q(),it(w,k),f>=7&&ot(w),L==null&&(L=$t(f,E,x)),G(L,k)},I=function(w,k){for(var y=-1;y<=7;y+=1)if(!(w+y<=-1||l<=w+y))for(var T=-1;T<=7;T+=1)k+T<=-1||l<=k+T||(0<=y&&y<=6&&(T==0||T==6)||0<=T&&T<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=T&&T<=4?p[w+y][k+T]=!0:p[w+y][k+T]=!1)},z=function(){for(var w=0,k=0,y=0;y<8;y+=1){R(!0,y);var T=o.getLostPoint(C);(y==0||w>T)&&(w=T,k=y)}return k},Q=function(){for(var w=8;w<l-8;w+=1)p[w][6]==null&&(p[w][6]=w%2==0);for(var k=8;k<l-8;k+=1)p[6][k]==null&&(p[6][k]=k%2==0)},et=function(){for(var w=o.getPatternPosition(f),k=0;k<w.length;k+=1)for(var y=0;y<w.length;y+=1){var T=w[k],S=w[y];if(p[T][S]==null)for(var D=-2;D<=2;D+=1)for(var K=-2;K<=2;K+=1)D==-2||D==2||K==-2||K==2||D==0&&K==0?p[T+D][S+K]=!0:p[T+D][S+K]=!1}},ot=function(w){for(var k=o.getBCHTypeNumber(f),y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[Math.floor(y/3)][y%3+l-8-3]=T}for(var y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[y%3+l-8-3][Math.floor(y/3)]=T}},it=function(w,k){for(var y=E<<3|k,T=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<6?p[S][8]=D:S<8?p[S+1][8]=D:p[l-15+S][8]=D}for(var S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<8?p[8][l-S-1]=D:S<9?p[8][15-S-1+1]=D:p[8][15-S-1]=D}p[l-8][8]=!w},G=function(w,k){for(var y=-1,T=l-1,S=7,D=0,K=o.getMaskFunction(k),N=l-1;N>0;N-=2)for(N==6&&(N-=1);;){for(var X=0;X<2;X+=1)if(p[T][N-X]==null){var nt=!1;D<w.length&&(nt=(w[D]>>>S&1)==1);var q=K(T,N-X);q&&(nt=!nt),p[T][N-X]=nt,S-=1,S==-1&&(D+=1,S=7)}if(T+=y,T<0||l<=T){T-=y,y=-y;break}}},V=function(w,k){for(var y=0,T=0,S=0,D=new Array(k.length),K=new Array(k.length),N=0;N<k.length;N+=1){var X=k[N].dataCount,nt=k[N].totalCount-X;T=Math.max(T,X),S=Math.max(S,nt),D[N]=new Array(X);for(var q=0;q<D[N].length;q+=1)D[N][q]=255&w.getBuffer()[q+y];y+=X;var gt=o.getErrorCorrectPolynomial(nt),vt=c(D[N],gt.getLength()-1),Dn=vt.mod(gt);K[N]=new Array(gt.getLength()-1);for(var q=0;q<K[N].length;q+=1){var Bn=q+Dn.getLength()-K[N].length;K[N][q]=Bn>=0?Dn.getAt(Bn):0}}for(var Hn=0,q=0;q<k.length;q+=1)Hn+=k[q].totalCount;for(var on=new Array(Hn),Ae=0,q=0;q<T;q+=1)for(var N=0;N<k.length;N+=1)q<D[N].length&&(on[Ae]=D[N][q],Ae+=1);for(var q=0;q<S;q+=1)for(var N=0;N<k.length;N+=1)q<K[N].length&&(on[Ae]=K[N][q],Ae+=1);return on},$t=function(w,k,y){for(var T=g.getRSBlocks(w,k),S=v(),D=0;D<y.length;D+=1){var K=y[D];S.put(K.getMode(),4),S.put(K.getLength(),o.getLengthInBits(K.getMode(),w)),K.write(S)}for(var N=0,D=0;D<T.length;D+=1)N+=T[D].dataCount;if(S.getLengthInBits()>N*8)throw"code length overflow. ("+S.getLengthInBits()+">"+N*8+")";for(S.getLengthInBits()+4<=N*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=N*8||(S.put(s,8),S.getLengthInBits()>=N*8));)S.put(h,8);return V(S,T)};C.addData=function(w,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=u(w);break;case"Alphanumeric":y=M(w);break;case"Byte":y=b(w);break;case"Kanji":y=A(w);break;default:throw"mode:"+k}x.push(y),L=null},C.isDark=function(w,k){if(w<0||l<=w||k<0||l<=k)throw w+","+k;return p[w][k]},C.getModuleCount=function(){return l},C.make=function(){if(f<1){for(var w=1;w<40;w++){for(var k=g.getRSBlocks(w,E),y=v(),T=0;T<x.length;T++){var S=x[T];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),w)),S.write(y)}for(var D=0,T=0;T<k.length;T++)D+=k[T].dataCount;if(y.getLengthInBits()<=D*8)break}f=w}R(!1,z())},C.createTableTag=function(w,k){w=w||2,k=typeof k=="undefined"?w*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var T=0;T<C.getModuleCount();T+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+w+"px;",y+=" height: "+w+"px;",y+=" background-color: ",y+=C.isDark(T,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(w,k,y,T){var S={};typeof arguments[0]=="object"&&(S=arguments[0],w=S.cellSize,k=S.margin,y=S.alt,T=S.title),w=w||2,k=typeof k=="undefined"?w*4:k,y=typeof y=="string"?{text:y}:y||{Line 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%2&&w>0?vt.substring(0,vt.length-y-1)+Array(y+1).join("▀"):vt.substring(0,vt.length-1)};return C.createASCII=function(w,k){if(w=w||1,w<2)return rn(k);w-=1,k=typeof k=="undefined"?w*2:k;var y=C.getModuleCount()*w+k*2,T=k,S=y-k,D,K,N,X,nt=Array(w+1).join("██"),q=Array(w+1).join(" "),gt="",vt="";for(D=0;D<y;D+=1){for(N=Math.floor((D-T)/w),vt="",K=0;K<y;K+=1)X=1,T<=K&&K<S&&T<=D&&D<S&&C.isDark(N,Math.floor((K-T)/w))&&(X=0),vt+=X?nt:q;for(N=0;N<w;N+=1)gt+=vt+`
|
||||||
`}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
|
`}return gt.substring(0,gt.length-1)},C.renderTo2dContext=function(w,k){k=k||2;for(var y=C.getModuleCount(),T=0;T<y;T++)for(var S=0;S<y;S++)w.fillStyle=C.isDark(T,S)?"black":"white",w.fillRect(T*k,S*k,k,k)},C};t.stringToBytesFuncs={default:function(d){for(var m=[],s=0;s<d.length;s+=1){var h=d.charCodeAt(s);m.push(h&255)}return m}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(d,m){var s=(function(){for(var f=P(d),E=function(){var Q=f.read();if(Q==-1)throw"eof";return Q},p=0,l={};;){var L=f.read();if(L==-1)break;var x=E(),C=E(),R=E(),I=String.fromCharCode(L<<8|x),z=C<<8|R;l[I]=z,p+=1}if(p!=m)throw p+" != "+m;return l})(),h=63;return function(f){for(var E=[],p=0;p<f.length;p+=1){var l=f.charCodeAt(p);if(l<128)E.push(l);else{var L=s[f.charAt(p)];typeof L=="number"?(L&255)==L?E.push(L):(E.push(L>>>8),E.push(L&255)):E.push(h)}}return E}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[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]],m=1335,s=7973,h=21522,f={},E=function(p){for(var l=0;p!=0;)l+=1,p>>>=1;return l};return f.getBCHTypeInfo=function(p){for(var l=p<<10;E(l)-E(m)>=0;)l^=m<<E(l)-E(m);return(p<<10|l)^h},f.getBCHTypeNumber=function(p){for(var l=p<<12;E(l)-E(s)>=0;)l^=s<<E(l)-E(s);return p<<12|l},f.getPatternPosition=function(p){return d[p-1]},f.getMaskFunction=function(p){switch(p){case r.PATTERN000:return function(l,L){return(l+L)%2==0};case r.PATTERN001:return function(l,L){return l%2==0};case r.PATTERN010:return function(l,L){return L%3==0};case r.PATTERN011:return function(l,L){return(l+L)%3==0};case r.PATTERN100:return function(l,L){return(Math.floor(l/2)+Math.floor(L/3))%2==0};case r.PATTERN101:return function(l,L){return l*L%2+l*L%3==0};case r.PATTERN110:return function(l,L){return(l*L%2+l*L%3)%2==0};case r.PATTERN111:return function(l,L){return(l*L%3+(l+L)%2)%2==0};default:throw"bad maskPattern:"+p}},f.getErrorCorrectPolynomial=function(p){for(var l=c([1],0),L=0;L<p;L+=1)l=l.multiply(c([1,a.gexp(L)],0));return l},f.getLengthInBits=function(p,l){if(1<=l&&l<10)switch(p){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:"+p}else if(l<27)switch(p){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:"+p}else if(l<41)switch(p){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:"+p}else throw"type:"+l},f.getLostPoint=function(p){for(var l=p.getModuleCount(),L=0,x=0;x<l;x+=1)for(var C=0;C<l;C+=1){for(var R=0,I=p.isDark(x,C),z=-1;z<=1;z+=1)if(!(x+z<0||l<=x+z))for(var Q=-1;Q<=1;Q+=1)C+Q<0||l<=C+Q||z==0&&Q==0||I==p.isDark(x+z,C+Q)&&(R+=1);R>5&&(L+=3+R-5)}for(var x=0;x<l-1;x+=1)for(var C=0;C<l-1;C+=1){var et=0;p.isDark(x,C)&&(et+=1),p.isDark(x+1,C)&&(et+=1),p.isDark(x,C+1)&&(et+=1),p.isDark(x+1,C+1)&&(et+=1),(et==0||et==4)&&(L+=3)}for(var x=0;x<l;x+=1)for(var C=0;C<l-6;C+=1)p.isDark(x,C)&&!p.isDark(x,C+1)&&p.isDark(x,C+2)&&p.isDark(x,C+3)&&p.isDark(x,C+4)&&!p.isDark(x,C+5)&&p.isDark(x,C+6)&&(L+=40);for(var C=0;C<l;C+=1)for(var x=0;x<l-6;x+=1)p.isDark(x,C)&&!p.isDark(x+1,C)&&p.isDark(x+2,C)&&p.isDark(x+3,C)&&p.isDark(x+4,C)&&!p.isDark(x+5,C)&&p.isDark(x+6,C)&&(L+=40);for(var ot=0,C=0;C<l;C+=1)for(var x=0;x<l;x+=1)p.isDark(x,C)&&(ot+=1);var it=Math.abs(100*ot/l/l-50)/5;return L+=it*10,L},f})(),a=(function(){for(var d=new Array(256),m=new Array(256),s=0;s<8;s+=1)d[s]=1<<s;for(var s=8;s<256;s+=1)d[s]=d[s-4]^d[s-5]^d[s-6]^d[s-8];for(var s=0;s<255;s+=1)m[d[s]]=s;var h={};return h.glog=function(f){if(f<1)throw"glog("+f+")";return m[f]},h.gexp=function(f){for(;f<0;)f+=255;for(;f>=256;)f-=255;return d[f]},h})();function c(d,m){if(typeof d.length=="undefined")throw d.length+"/"+m;var s=(function(){for(var f=0;f<d.length&&d[f]==0;)f+=1;for(var E=new Array(d.length-f+m),p=0;p<d.length-f;p+=1)E[p]=d[p+f];return E})(),h={};return h.getAt=function(f){return s[f]},h.getLength=function(){return s.length},h.multiply=function(f){for(var E=new Array(h.getLength()+f.getLength()-1),p=0;p<h.getLength();p+=1)for(var l=0;l<f.getLength();l+=1)E[p+l]^=a.gexp(a.glog(h.getAt(p))+a.glog(f.getAt(l)));return c(E,0)},h.mod=function(
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
|
`),hostName:a,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},g={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(c),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return n.dns[0]&&(g.dns1=n.dns[0]),n.dns[1]&&(g.dns2=n.dns[1]),g}function bi(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wi(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let n=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,t.length,!1),o.set(r,4),o}catch{return null}}async function Ln(t,e,n=!0){let r=new TextEncoder().encode(JSON.stringify(xi(t,e))),o=n?await wi(r):null;return`vpn://${bi(o!=null?o:r)}`}var Zr=t=>t.replace(/^vpn:\/\//,"");var to=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function qt(t,e={}){let n=i("div",{class:`acc${e.inset?" inset":""}`}),r=t.map((u,M)=>{var $;let b=u.body.filter(d=>!!d),A=!b.length,O=[u.icon,i("span",{class:"acc-title"},i("span",{class:"t"},u.title),($=u.tag)!=null?$:null),u.val?i("span",{class:`acc-val${u.valHide?" hide-open":""}`},u.val):null],B=M===e.open&&!A,P=A?i("div",{class:"acc-head"},...O):i("button",{type:"button",class:"acc-head","aria-expanded":String(B),onclick:()=>v(H)},...O,F("chevron","i acc-chev")),H=i("div",{class:`acc-row${A?" still":""}${B?" open":""}`},P,i("div",{class:"acc-body"},...b));return n.appendChild(H),H}),o=u=>u.querySelector(".acc-body"),a=()=>r.forEach((u,M)=>{let b=u.classList.contains("open");u.classList.toggle("rt",M===0||b||r[M-1].classList.contains("open")),u.classList.toggle("rb",M===r.length-1||b||r[M+1].classList.contains("open"))}),c=u=>{let M=getComputedStyle(u),b={};for(let A of to)b[A]=A==="height"?`${u.getBoundingClientRect().height}px`:M[A];return b},g=()=>r.forEach(u=>{var M;return(M=u.querySelector("button.acc-head"))==null?void 0:M.setAttribute("aria-expanded",String(u.classList.contains("open")))});function v(u){var B;let M=r.map(c);r.forEach(P=>P.getAnimations().forEach(H=>H.cancel())),r.forEach(P=>o(P).getAnimations().forEach(H=>H.cancel()));let b=!u.classList.contains("open"),A=r.filter(P=>P.classList.contains("open")&&(P===u||b));r.forEach(P=>{P.classList.remove("closing"),P!==u&&P.classList.remove("open")}),u.classList.toggle("open",b),a();let O=ce();r.forEach((P,H)=>{let $=c(P);to.some(d=>M[H][d]!==$[d])&&(A.includes(P)&&P.classList.add("closing"),_(P,[M[H],$],{duration:Et.duration,easing:Et.easing}).onfinish=()=>P.classList.remove("closing"))}),A.forEach(P=>_(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:J,fill:"forwards"})),b&&_(o(u),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),de(O),g(),(B=e.onToggle)==null||B.call(e,r.indexOf(u),b,!1)}return a(),{el:n,openIndex:()=>r.findIndex(u=>u.classList.contains("open")),setOpen(u){r.forEach((M,b)=>M.classList.toggle("open",b===u&&!M.classList.contains("still"))),a(),g(),r.forEach((M,b)=>{var A;return(A=e.onToggle)==null?void 0:A.call(e,b,M.classList.contains("open"),!0)})}}}function eo(t,e,n){let r=i("span",{class:"seg-pill"}),o=i("div",{class:"seg appseg",role:"tablist"},r),a=t.map(A=>{let O=i("button",{type:"button",class:"seg-b",role:"tab","aria-label":A.label,title:A.label,onclick:()=>b(A.value)},F(A.icon),i("span",{class:"seg-l"},A.label));return O.dataset.v=A.value,o.appendChild(O),O}),c=A=>A.querySelector(".seg-l"),g=()=>a.forEach(A=>{let O=A.dataset.v===e;A.classList.toggle("on",O),A.setAttribute("aria-selected",String(O))}),v=()=>{let A=a.find(O=>O.dataset.v===e);return A&&A.offsetWidth?[A.offsetLeft,o.clientWidth-A.offsetLeft-A.offsetWidth]:null},u=()=>{let A=v();A&&(r.style.left=`${A[0]}px`,r.style.right=`${A[1]}px`)},M=0;function b(A){if(A===e)return;let O=a.findIndex(C=>C.dataset.v===e),B=a.findIndex(C=>C.dataset.v===A),P=getComputedStyle(r),H=parseFloat(P.left)||0,$=parseFloat(P.right)||0,d=a.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),m=c(a[O]),s=m.getBoundingClientRect().width;[...a,...a.map(c)].forEach(C=>C.getAnimations().forEach(R=>R.cancel())),e=A,g(),a.forEach((C,R)=>{let I=R===B?1:0;d[R]!==I&&_(C,[{flexGrow:d[R]},{flexGrow:I}],{duration:U.duration,easing:U.easing})}),_(m,[{opacity:1,maxWidth:`${s}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),_(c(a[B]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:Y,fill:"backwards"});let h=B>O,f=Lt()?U:Fn,E=performance.now(),p=Math.m
Line truncated
|
||||||
`).flatMap((p,k)=>k?[`
|
`).flatMap((u,M)=>M?[`
|
||||||
`,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
|
`,ro(u,e)]:[ro(u,e)]));r();let o=!!Wt(t.filename,t.conf),a=i("button",{type:"button",class:"btn soft sm",onclick:()=>{e=!e,a.replaceChildren(F(e?"x":"key"),i("span",{},e?"Hide key":"Show key")),r(),n.querySelectorAll(".mask, .k").forEach(u=>_(u,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:Y}))}},F("key"),i("span",{},"Show key")),c=i("button",{type:"button",class:"btn soft sm",onclick:u=>pt(t.conf,"Configuration copied",u.currentTarget)},F("copy"),i("span",{class:"lbl"},"Copy")),g=i("div",{class:"filecard"},i("div",{class:"fc-row"},i("span",{class:"filecard-ic"},".conf"),i("span",{class:"t"},i("span",{class:"mono"},t.filename),i("span",{},"For computers and routers"))),i("button",{type:"button",class:"btn accent sm block",onclick:()=>ye(t.filename,t.conf)},F(o?"open":"download"),i("span",{},o?"Share file":"Download"))),v=qt([{icon:j("file"),title:"Configuration",body:[i("div",{class:"confbar"},a,c),n]}],{inset:!0});return i("div",{class:"step-box"},g,v.el)}function fo(t){let e=i("span",{class:"osm-p"},at[t]),n=Dr(me(t,"ios"),me(t,"android"));return{el:i("span",{class:"scanline"},i("span",{},"In ",e,":"),n.el),set(r){Z(e,at[r],void 0,{whole:!0}),n.set(me(r,"ios"),me(r,"android"))}}}function ho(t){let e=i("span",{class:"tt"}),n=i("span",{class:"tt-m"}),r=i("span",{class:"hp-tip","aria-hidden":"true"},e,n),o=i("button",{type:"button",class:"hp-b",onclick:()=>ye(t().file,t().text)},F("download")),a=i("button",{type:"button",class:"hp-b"},F("copy")),c=i("div",{class:"hpill",role:"group","aria-label":"The connection","data-key":"conn"},o,a,r),g=null,v=0,u=0,M=s=>{var h;return s===a&&a.classList.contains("done")?"Copied":(h=s.getAttribute("aria-label"))!=null?h:""},b=(s,h)=>{n.textContent=h;let f=n.offsetWidth+20;return Math.min(s.offsetLeft+s.offsetWidth/2,c.offsetWidth+46-f/2)},A=s=>`translateX(${s}px) translateX(-50%)`,O=s=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(f=>f.cancel()),r.style.transform=A(s),_(r,[{transform:h},{transform:A(s)}],{duration:U.duration,easing:U.easing})},B=s=>Z(e,s),P=s=>{if(clearTimeout(v),g===s&&r.classList.contains("on"))return;if(g=s,r.classList.contains("on")){let f=M(s);return O(b(s,f)),B(f)}let h=()=>{let f=M(s);bt(e,f);let E=b(s,f);r.getAnimations().forEach(p=>p.cancel()),r.style.transform=A(E),r.classList.add("on"),_(r,[{opacity:0,transform:`${A(E)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:A(E),filter:"blur(0px)"}],{duration:220,easing:Y})};performance.now()<u?h():v=window.setTimeout(h,420)},H=()=>{clearTimeout(v),g=null,r.classList.contains("on")&&(u=performance.now()+500,r.classList.remove("on"),_(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let s of[o,a])s.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(s)}),s.addEventListener("focus",()=>{s.matches(":focus-visible")&&P(s)}),s.addEventListener("blur",H);c.addEventListener("pointerleave",H);let $=s=>{let h=F(s);a.querySelector("svg").replaceWith(h),_(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:yt.duration,easing:yt.easing})},d=()=>{if(g!==a||!r.classList.contains("on"))return;let s=M(a);O(b(a,s)),B(s)},m=0;return a.addEventListener("click",()=>{let s=t();pt(s.text,s.msg),clearTimeout(m),a.classList.contains("done")||(a.classList.add("done"),$("check"),d()),m=window.setTimeout(()=>{a.classList.remove("done"),$("copy"),d()},1600)}),{el:c,sync(){let s=t().app;o.setAttribute("aria-label",`Download ${s} config`),a.setAttribute("aria-label",`Copy ${s} config`)}}}function go(t){let e=i("b",{},"Waiting for the connection"),n=i("span",{class:"ws",hidden:!0}),r=i("div",{class:"way",role:"status","aria-live":"polite"},i("div",{class:"way-row"},i("span",{class:"way-end"},F(t.kind)),i("span",{class:"way-track"},i("span",{class:"way-glow"},i("i")),i("span",{class:"way-fill"})),i("span",{class:"way-end home"},F("server"))),i("div",{class:"way-text"},i("span",{class:"t"},e,n)));return{el:r,connected(){r.classList.add("done"),Z(e,`${t.name} connected`)},gaveUp(){r.classList.add("stopped"),Z(e,"No connection yet"),n.textContent="Close this and open it again to keep checking.",n.hidden=!1,_(e.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:Y})}}}function vo(t,e=4){window.setTimeout(async()=>{var n;try{let r=await ut("state");xt(r),be()||Mt(),!((n=r.person.devices.find(o=>o.id===t))!=null&&n.online)&&e>1&&vo(t,e-1)}catch{}},1500)}function yo(t,e,n){let r=te(),o=0,a=0,c=!1,g=Date.now(),v=async()=>{if(o=0,!c){if(Date.now()-g>6e5){c=!0,n();return}if(document.hidden)return u();try{let b=await ut("state");xt(b);let A=b.person.devices.find(O=>O.id===t.id);if(A&&A.handshake>r){c=!0,e(),A.online||vo(t.id);return}}catch(b){if(Oe(b)){c=!0;return}}a++,u()}},u=()=>{!c&&!o&&(o=window.setTimeout(v,a<6?5e3:a<12?15e3:3e4))},M=()=>{!document.hidden&&!c&&!o&&v()};return document.addEventListener("visibilitychange",M),u(),()=>{c=!0,o
Line truncated
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/ucode
|
||||||
|
// Dawnline personal portal as a CGI script: the request handling itself is
|
||||||
|
// dawnline.portal. www/cgi-bin/portal (a shell) runs it for requests shaped
|
||||||
|
// like a personal link and answers the rest itself.
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
import { stdin } from 'fs';
|
||||||
|
import { serve } from 'dawnline.portal';
|
||||||
|
|
||||||
|
let env = {};
|
||||||
|
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
|
||||||
|
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT',
|
||||||
|
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
|
||||||
|
'HTTP_CF_CONNECTING_IP' ])
|
||||||
|
env[k] = getenv(k);
|
||||||
|
|
||||||
|
serve({
|
||||||
|
env,
|
||||||
|
headers: {},
|
||||||
|
read: (n) => stdin.read(n),
|
||||||
|
write: (s) => print(s),
|
||||||
|
});
|
||||||
@@ -1,21 +1,51 @@
|
|||||||
#!/usr/bin/ucode
|
#!/bin/sh
|
||||||
// Dawnline personal portal as a CGI script: the request handling itself is
|
# Dawnline personal portal, the door: uhttpd runs this for every request.
|
||||||
// dawnline.portal.
|
# Anything that is not shaped like a personal link (/<word-code>[/…]) gets
|
||||||
'use strict';
|
# the portal's bare answer from here, in a shell that costs nothing, so a
|
||||||
|
# scanner or a flood on the root never starts ucode (compiling the portal's
|
||||||
|
# module graph is ~140 ms of CPU). Links go on to the portal itself
|
||||||
|
# (/usr/share/dawnline/portal/cgi.uc), which judges the code.
|
||||||
|
#
|
||||||
|
# The answer here is byte for byte the portal's own not_found(): keep both
|
||||||
|
# in step (dawnline.portal headers(), SECURITY_HEADERS, not_found()).
|
||||||
|
|
||||||
import { stdin } from 'fs';
|
path="${REQUEST_URI%%\?*}"
|
||||||
import { serve } from 'dawnline.portal';
|
w='[a-z][a-z][a-z][a-z][a-z][a-z]'
|
||||||
|
# The expansion is meant as a pattern (a word of six letters), not literally.
|
||||||
|
# shellcheck disable=SC2254
|
||||||
|
case "$path" in
|
||||||
|
/$w-$w-$w|/$w-$w-$w/*) exec /usr/bin/ucode /usr/share/dawnline/portal/cgi.uc ;;
|
||||||
|
esac
|
||||||
|
|
||||||
let env = {};
|
# HSTS pins the whole name: only when the visitor is on the standard port.
|
||||||
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
|
hsts=
|
||||||
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT',
|
if [ "$HTTPS" = on ]; then
|
||||||
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
|
port="${HTTP_HOST##*:}"
|
||||||
'HTTP_CF_CONNECTING_IP' ])
|
case "$HTTP_HOST" in *:*) ;; *) port=443 ;; esac
|
||||||
env[k] = getenv(k);
|
case "$HTTP_HOST" in *\]) port=443 ;; esac
|
||||||
|
[ "$port" = 443 ] && hsts=1
|
||||||
|
fi
|
||||||
|
|
||||||
serve({
|
# Files always get the 404: a missing asset must not turn into someone's website.
|
||||||
env,
|
file=
|
||||||
headers: {},
|
case "$path" in
|
||||||
read: (n) => stdin.read(n),
|
/luci-static|/luci-static/*|/cgi-bin|/cgi-bin/*|/ubus|/ubus/*) file=1 ;;
|
||||||
write: (s) => print(s),
|
*) case "${path##*/}" in *.*) file=1 ;; esac ;;
|
||||||
});
|
esac
|
||||||
|
redirect=
|
||||||
|
[ -n "$file" ] || redirect="$(uci -q get dawnline.settings.portal_redirect)"
|
||||||
|
|
||||||
|
if [ -n "$redirect" ]; then
|
||||||
|
printf 'Status: 302 Found\r\n'
|
||||||
|
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
|
||||||
|
printf 'Location: %s\r\nContent-Type: text/plain\r\n' "$redirect"
|
||||||
|
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
|
||||||
|
printf '\r\nMoved\n'
|
||||||
|
else
|
||||||
|
printf 'Status: 404 Not Found\r\n'
|
||||||
|
printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
|
||||||
|
printf 'Content-Type: text/plain\r\n'
|
||||||
|
[ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
|
||||||
|
printf '\r\nNot found\n'
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
@@ -18,6 +18,8 @@
|
|||||||
"settings_get",
|
"settings_get",
|
||||||
"portal_info",
|
"portal_info",
|
||||||
"interfaces",
|
"interfaces",
|
||||||
|
"server_ports",
|
||||||
|
"endpoint_probe",
|
||||||
"events"
|
"events"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ import * as view from 'dawnline.view';
|
|||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
|
|
||||||
const STATE_TEXT = {
|
const STATE_TEXT = {
|
||||||
no_server: 'their server is turned off',
|
no_server: 'they have no server',
|
||||||
|
server_off: 'their server is turned off',
|
||||||
paused: 'they are paused',
|
paused: 'they are paused',
|
||||||
paused_all: 'everyone is paused',
|
|
||||||
expired: 'their access has ended',
|
expired: 'their access has ended',
|
||||||
quota: 'they used up their data',
|
quota: 'they used up their data',
|
||||||
hours: 'it is outside their allowed hours',
|
hours: 'it is outside their allowed hours',
|
||||||
@@ -154,12 +154,20 @@ function from_device(m, d, t, states, dmp, snap) {
|
|||||||
|
|
||||||
// The router itself.
|
// The router itself.
|
||||||
if (index(router_addrs(snap), t.ip) >= 0) {
|
if (index(router_addrs(snap), t.ip) >= 0) {
|
||||||
if (home_access(p))
|
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
|
||||||
push(steps, step(true, `${t.ip} is this router`, 'Home access includes the router.'));
|
if (t.port == 53)
|
||||||
else if (t.port == 53)
|
|
||||||
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
|
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
|
||||||
else
|
else if (portal)
|
||||||
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS on the router.`));
|
push(steps, step(true, `${t.ip} is this router: the personal portal is open to everyone`, ''));
|
||||||
|
else if (!home_access(p))
|
||||||
|
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS and the portal on the router.`));
|
||||||
|
else {
|
||||||
|
// Like any home address: only on the networks the person reaches.
|
||||||
|
let h = core.person_home(srv, p, snap);
|
||||||
|
if (!h.all && !in_nets(t.ip, h.nets))
|
||||||
|
return stop(steps, step(false, `${t.ip} is this router on a network ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
|
||||||
|
push(steps, step(true, `${t.ip} is this router`, h.all ? 'Home access includes the router.' : `On one of the networks ${p.name} reaches.`));
|
||||||
|
}
|
||||||
push(steps, via(t.ip));
|
push(steps, via(t.ip));
|
||||||
return steps;
|
return steps;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,19 +35,17 @@ function log(who, msg, level, detail) {
|
|||||||
|
|
||||||
/* ---------- hostnames ---------- */
|
/* ---------- hostnames ---------- */
|
||||||
|
|
||||||
function host_label(s) {
|
|
||||||
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
|
|
||||||
l = replace(l, /^-+|-+$/g, '');
|
|
||||||
return substr(l, 0, 40) || 'device';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function sync_hosts(m) {
|
export function sync_hosts(m) {
|
||||||
let lines = [];
|
let lines = [];
|
||||||
if (m.settings.hostnames)
|
if (m.settings.hostnames)
|
||||||
for (let id, d in m.devices) {
|
for (let pid, p in m.people) {
|
||||||
let p = m.people[d.person];
|
// One label per device, unique within the person (the UI shows the same).
|
||||||
if (p && ip2int(d.address) != null)
|
let labels = core.device_labels(m, p);
|
||||||
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
|
for (let id in p.devices) {
|
||||||
|
let d = m.devices[id];
|
||||||
|
if (ip2int(d.address) != null)
|
||||||
|
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let ls = loop.status();
|
let ls = loop.status();
|
||||||
if (ls.active)
|
if (ls.active)
|
||||||
@@ -82,37 +80,44 @@ export function access_sets(m, usage, states) {
|
|||||||
return nft.access_sets(m, usage, states);
|
return nft.access_sets(m, usage, states);
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Log an access-table failure once per distinct error; true when the table is in place. */
|
/**
|
||||||
function nft_result(err) {
|
* Log an access-table failure once per distinct error (with what it means
|
||||||
|
* for the devices: none loaded while the table is missing, the previous rules
|
||||||
|
* kept when an older one survived the failed rebuild); the error, or null.
|
||||||
|
*/
|
||||||
|
function nft_result(err, present) {
|
||||||
let was = readfile(NFT_ERR);
|
let was = readfile(NFT_ERR);
|
||||||
if (err == null) {
|
if (err == null) {
|
||||||
if (was != null)
|
if (was != null)
|
||||||
unlink(NFT_ERR);
|
unlink(NFT_ERR);
|
||||||
return true;
|
return null;
|
||||||
}
|
}
|
||||||
if (was != err) {
|
if (was != err) {
|
||||||
log('Access rules', "couldn't load — devices aren't loaded into the tunnels until they do", 'error', err);
|
log('Access rules', present
|
||||||
|
? "couldn't be updated — the previous rules stay, and changes to access wait until they load"
|
||||||
|
: "couldn't load — no device is loaded into the tunnels until they do", 'error', err);
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
writefile(NFT_ERR, err);
|
writefile(NFT_ERR, err);
|
||||||
}
|
}
|
||||||
return false;
|
return err;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
|
* 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 that fails (no table yet at boot, or an older shape). Null, or the
|
||||||
* when the rebuild fails too.
|
* error when the rebuild fails too.
|
||||||
*/
|
*/
|
||||||
function load_table(m, sets, full) {
|
function load_table(m, sets, full) {
|
||||||
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
|
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
|
||||||
if (err != null && !full)
|
if (err != null && !full)
|
||||||
err = nft.rebuild(m, sets);
|
err = nft.rebuild(m, sets);
|
||||||
return nft_result(err);
|
return nft_result(err, err != null && nft.present());
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Full table rebuild (structure changes: servers, LAN subnets). */
|
/** Full table rebuild (structure changes: servers, LAN subnets); true when it loaded. */
|
||||||
export function rebuild_nft(m, sets) {
|
export function rebuild_nft(m, sets) {
|
||||||
return nft_result(nft.rebuild(m, sets));
|
let err = nft.rebuild(m, sets);
|
||||||
|
return nft_result(err, err != null && nft.present()) == null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Atomically replace set contents only. */
|
/** Atomically replace set contents only. */
|
||||||
@@ -131,32 +136,57 @@ export function firewall_drift(m) {
|
|||||||
|
|
||||||
/* ---------- runtime sync ---------- */
|
/* ---------- runtime sync ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What an admin should hear when a sync did not fully take: the access table
|
||||||
|
* failed, or a server did not accept its devices. Null when all went in.
|
||||||
|
*/
|
||||||
|
function sync_warning(m, table, peers) {
|
||||||
|
let out = [];
|
||||||
|
if (table != null)
|
||||||
|
push(out, nft.present()
|
||||||
|
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.`
|
||||||
|
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`);
|
||||||
|
for (let id, r in peers)
|
||||||
|
if (r != 'ok' && r != 'down')
|
||||||
|
push(out, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`);
|
||||||
|
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* With the lock held: access sets first, and devices into the tunnels only
|
* With the lock held: access sets first, then devices into the tunnels.
|
||||||
* once the table that limits them is in place.
|
* Fail closed: without the table the firewall would let every loaded device
|
||||||
|
* reach everything, so while it is missing no device is loaded at all. An
|
||||||
|
* older table that survived a failed rebuild keeps limiting them with the
|
||||||
|
* sets it has, and the devices still follow people's states (a revoked one
|
||||||
|
* leaves).
|
||||||
*/
|
*/
|
||||||
function locked_sync(m, usage, full) {
|
function locked_sync(m, usage, full) {
|
||||||
let states = states_for(m, usage);
|
let states = states_for(m, usage);
|
||||||
let sets = nft.access_sets(m, usage, states);
|
let sets = nft.access_sets(m, usage, states);
|
||||||
let peers = {};
|
let table = load_table(m, sets, full);
|
||||||
if (load_table(m, sets, full))
|
let peers = awg.sync_peers(m, table == null || nft.present() ? states : {});
|
||||||
peers = awg.sync_peers(m, states);
|
|
||||||
sync_hosts(m);
|
sync_hosts(m);
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
write_json(`${RUN_DIR}/states.json`, states, 0o644);
|
write_json(`${RUN_DIR}/states.json`, states, 0o644);
|
||||||
return { peers, states };
|
return { peers, states, table, warning: sync_warning(m, table, peers) };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
|
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
|
||||||
* hostnames. Cheap; safe to call often. The model is always read again under
|
* 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
|
* the lock (`m` is accepted for older callers and not used); `usage` is the
|
||||||
* caller's (the agent holds the live counters).
|
* caller's (the agent holds the live counters). The result carries `warning`
|
||||||
|
* (a sentence for the admin) when the sync did not fully take.
|
||||||
*/
|
*/
|
||||||
export function sync(m, usage) {
|
export function sync(m, usage) {
|
||||||
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
|
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Is the access table loaded (the agent's tick re-syncs when it is not). */
|
||||||
|
export function table_present() {
|
||||||
|
return nft.present();
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Everything on the router that Dawnline's state is derived from: WAN and
|
* Everything on the router that Dawnline's state is derived from: WAN and
|
||||||
* LAN, the home networks and zones of each server, the netns address and the
|
* LAN, the home networks and zones of each server, the netns address and the
|
||||||
@@ -209,10 +239,10 @@ export function apply(opts) {
|
|||||||
let s = locked_sync(m, usage, true);
|
let s = locked_sync(m, usage, true);
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
write_file(NET_SIG, net_signature(m), 0o644);
|
write_file(NET_SIG, net_signature(m), 0o644);
|
||||||
return { network, firewall, lp, peers: s.peers };
|
return { network, firewall, lp, peers: s.peers, warning: s.warning };
|
||||||
});
|
});
|
||||||
loop.remember(r.lp);
|
loop.remember(r.lp);
|
||||||
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers };
|
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning };
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Remove everything Dawnline created (used by the uninstaller). */
|
/** Remove everything Dawnline created (used by the uninstaller). */
|
||||||
|
|||||||
@@ -6,11 +6,13 @@
|
|||||||
|
|
||||||
import { readfile, stat, unlink } from 'fs';
|
import { readfile, stat, unlink } from 'fs';
|
||||||
import {
|
import {
|
||||||
q, sh, sh_out, rand_int, rand_bytes, valid_key, ensure_dir, write_file, read_json, write_json, lock, unlock,
|
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, tunnel_name, ensure_dir, write_file, read_json, write_json, lock, unlock,
|
||||||
slog, iface_status, DATA_DIR, RUN_DIR
|
slog, iface_status, DATA_DIR, RUN_DIR
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
|
import * as pkg from 'dawnline.pkg';
|
||||||
|
import * as builds from 'dawnline.awg_builds';
|
||||||
|
|
||||||
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
|
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
|
||||||
export const OBF_CONF = {
|
export const OBF_CONF = {
|
||||||
@@ -54,6 +56,18 @@ export function state() {
|
|||||||
return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler };
|
return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* state(), after loading an installed module that isn't loaded yet: nothing loads
|
||||||
|
* it before the first tunnel comes up, so "not loaded" alone is no fault.
|
||||||
|
*/
|
||||||
|
export function load() {
|
||||||
|
let s = state();
|
||||||
|
if (!s.kmod || s.loaded)
|
||||||
|
return s;
|
||||||
|
system('modprobe amneziawg >/dev/null 2>&1');
|
||||||
|
return state();
|
||||||
|
};
|
||||||
|
|
||||||
/** The kernel module and the awg tool are on the router. */
|
/** The kernel module and the awg tool are on the router. */
|
||||||
export function installed() {
|
export function installed() {
|
||||||
let s = state();
|
let s = state();
|
||||||
@@ -106,7 +120,9 @@ export function server_keys() {
|
|||||||
|
|
||||||
/* ---------- obfuscation ---------- */
|
/* ---------- obfuscation ---------- */
|
||||||
|
|
||||||
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
|
// Junk packets may be tiny (the 3.1 preset sends 10-50 bytes, as AmneziaVPN
|
||||||
|
// does); the ceiling keeps them under the path MTU.
|
||||||
|
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 0, 1024 ], jmax: [ 0, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
|
||||||
|
|
||||||
function rand_h(used) {
|
function rand_h(used) {
|
||||||
for (let i = 0; i < 50; i++) {
|
for (let i = 0; i < 50; i++) {
|
||||||
@@ -118,31 +134,106 @@ function rand_h(used) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// caps() answers from here while the tool, the protocol script and the module file are the same.
|
||||||
|
const CAPS = `${RUN_DIR}/awg-caps.json`;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What the installed AmneziaWG can do, from the netifd protocol script (the
|
* What the installed AmneziaWG can do: the netifd protocol script (the
|
||||||
* options it passes on) and the `awg` tool (the keys it accepts):
|
* options it passes on) and the `awg` tool (the keys it accepts) say what the
|
||||||
|
* tools know, the kernel module's package version what the kernel runs, and
|
||||||
|
* a feature counts only when both have it (tools 3.1 over a 2.0 module would
|
||||||
|
* configure header protection that the kernel silently lacks):
|
||||||
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
|
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
|
||||||
* v3 — header protection, trailers, padding, timing (AWG 3.1)
|
* v3 — header protection, trailers, padding, timing (AWG 3.1)
|
||||||
|
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
|
||||||
|
* mismatch — the two differ
|
||||||
*/
|
*/
|
||||||
export function caps() {
|
export function caps() {
|
||||||
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? '';
|
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||||
|
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`;
|
||||||
|
let cached = read_json(CAPS, null);
|
||||||
|
if (cached?.key == key && cached.caps)
|
||||||
|
return cached.caps;
|
||||||
|
let script = readfile(PROTO) ?? '';
|
||||||
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
|
let 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 t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
|
||||||
let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
|
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
|
||||||
return { v2, v3 };
|
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
|
||||||
|
// A module installed by hand has no package: then the tools are believed.
|
||||||
|
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
|
||||||
|
let out = {
|
||||||
|
v2: t2 && (kmod == null || kmod != '1.0'),
|
||||||
|
v3: t3 && (kmod == null || kmod == '3.1'),
|
||||||
|
tools, kmod, mismatch: tools != null && kmod != null && tools != kmod,
|
||||||
|
};
|
||||||
|
ensure_dir(RUN_DIR);
|
||||||
|
write_json(CAPS, { key, caps: out }, 0o644);
|
||||||
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */
|
/**
|
||||||
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>';
|
* Why this AmneziaWG cannot run a server's disguise values, or null: a 3.1
|
||||||
|
* preset after a rollback to a 2.0 build would come up without the header
|
||||||
|
* protection every device expects, so such a server is kept down instead
|
||||||
|
* (dawnline.netifd).
|
||||||
|
*/
|
||||||
|
export function obf_unsupported(o) {
|
||||||
|
let c = caps();
|
||||||
|
let has = (keys) => length(filter(keys, (k) => o?.[k] != null && o[k] != '')) > 0;
|
||||||
|
let v3 = [ 'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
|
||||||
|
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
|
||||||
|
let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ];
|
||||||
|
let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0;
|
||||||
|
if (has(v3) && !c.v3)
|
||||||
|
return `its disguise needs AmneziaWG 3.1 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
|
||||||
|
if ((has(v2) || ranged) && !c.v2)
|
||||||
|
return `its disguise needs AmneziaWG 2.0 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signature packets shaped like DNS, made fresh for each server: the same
|
||||||
|
* fixed bytes on every router (AmneziaVPN's own 3.1 default is one constant
|
||||||
|
* answer about icloud.com) would be one rule for a DPI to match. A query and
|
||||||
|
* an answer about a name of this server's own, with its own TTL and address.
|
||||||
|
* <r N> random bytes, <rc N> random letters, <b 0x..> fixed bytes
|
||||||
|
*/
|
||||||
|
function dns_name_hex() {
|
||||||
|
let hex = (s) => {
|
||||||
|
let out = '';
|
||||||
|
for (let i = 0; i < length(s); i++)
|
||||||
|
out += sprintf('%02x', ord(s, i));
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
let tld = [ 'com', 'net', 'org', 'io' ][rand_int(0, 3)];
|
||||||
|
let n = rand_int(5, 9);
|
||||||
|
return { labels: `<b 0x${sprintf('%02x', n)}><rc ${n}><b 0x${sprintf('%02x', length(tld))}${hex(tld)}00>`, len: n + length(tld) + 2 };
|
||||||
|
}
|
||||||
|
|
||||||
|
function dns_query() {
|
||||||
|
let name = dns_name_hex();
|
||||||
|
// id, flags (standard query, recursion desired), 1 question, name, type A, class IN
|
||||||
|
return `<r 2><b 0x01000001000000000000>${name.labels}<b 0x00010001>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function dns_answer() {
|
||||||
|
let name = dns_name_hex();
|
||||||
|
let ttl = sprintf('%08x', rand_int(300, 86400));
|
||||||
|
// id, flags (answer, authoritative, recursion), 1 question, 1 answer, name, A IN, pointer, A IN, ttl, 4 bytes
|
||||||
|
return `<r 2><b 0x85800001000100000000>${name.labels}<b 0x00010001c00c00010001${ttl}0004><r 4>`;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate obfuscation parameters for a method:
|
* Generate obfuscation parameters for a method:
|
||||||
* off plain WireGuard-compatible packets
|
* off plain WireGuard-compatible packets
|
||||||
* standard junk packets and random headers (any AmneziaWG client)
|
* balanced AmneziaWG 2.0: junk packets, random headers, padded cookie and
|
||||||
* strong more and larger junk (any AmneziaWG client)
|
* data packets, DNS-shaped signature packets
|
||||||
* max AmneziaWG 3.1: protected headers, random trailers, padding,
|
* max AmneziaWG 3.1: protected headers, random trailers, padding,
|
||||||
* jittered timers and a DNS-like first packet — the values
|
* jittered timers and a DNS-like first packet — the values
|
||||||
* AmneziaVPN itself uses for 3.1 servers
|
* AmneziaVPN itself uses for 3.1 servers
|
||||||
|
* Servers made before 0.8 may still carry the old "standard" or "strong"
|
||||||
|
* values (1.0-style junk only): they keep running as they are, the picker
|
||||||
|
* offers Balanced or Maximum instead.
|
||||||
*/
|
*/
|
||||||
export function obf_preset(name) {
|
export function obf_preset(name) {
|
||||||
if (name == 'max')
|
if (name == 'max')
|
||||||
@@ -150,7 +241,7 @@ export function obf_preset(name) {
|
|||||||
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
|
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
|
||||||
s1: '12', s2: '12', s3: '12', s4: '12',
|
s1: '12', s2: '12', s3: '12', s4: '12',
|
||||||
h1: '1', h2: '2', h3: '3', h4: '4',
|
h1: '1', h2: '2', h3: '3', h4: '4',
|
||||||
i1: DNS_MIMIC,
|
i1: dns_query(), i2: dns_answer(),
|
||||||
header_protection_key: sh_out('awg genkey'),
|
header_protection_key: sh_out('awg genkey'),
|
||||||
content_padding_addition: '10-100',
|
content_padding_addition: '10-100',
|
||||||
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
|
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
|
||||||
@@ -159,12 +250,11 @@ export function obf_preset(name) {
|
|||||||
};
|
};
|
||||||
if (name == 'off')
|
if (name == 'off')
|
||||||
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
|
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 = {};
|
let o = {};
|
||||||
o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`;
|
o.jc = `${rand_int(4, 8)}`;
|
||||||
let jmin = rand_int(64, strong ? 128 : 96);
|
let jmin = rand_int(64, 128);
|
||||||
o.jmin = `${jmin}`;
|
o.jmin = `${jmin}`;
|
||||||
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
|
o.jmax = `${jmin + rand_int(150, 400)}`;
|
||||||
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
|
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
|
||||||
while (s1 + 56 == s2)
|
while (s1 + 56 == s2)
|
||||||
s2 = rand_int(15, 64);
|
s2 = rand_int(15, 64);
|
||||||
@@ -173,19 +263,25 @@ export function obf_preset(name) {
|
|||||||
let used = {};
|
let used = {};
|
||||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
||||||
o[k] = rand_h(used);
|
o[k] = rand_h(used);
|
||||||
|
// AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept
|
||||||
|
// small: core.tunnel_mtu) and DNS-shaped signature packets before each
|
||||||
|
// handshake — what 1.0 traffic lacks and gets recognised by.
|
||||||
|
o.s3 = `${rand_int(8, 48)}`;
|
||||||
|
o.s4 = `${rand_int(4, 16)}`;
|
||||||
|
o.i1 = dns_query();
|
||||||
|
o.i2 = dns_answer();
|
||||||
return o;
|
return o;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
export function obf_errors(o) {
|
export function obf_errors(o) {
|
||||||
let errs = [];
|
let errs = [];
|
||||||
for (let k, r in OBF_SPEC) {
|
for (let k, r in OBF_SPEC) {
|
||||||
let v = o[k];
|
let v = o[k];
|
||||||
if (v == null || v == '')
|
if (v == null || v == '')
|
||||||
continue;
|
continue;
|
||||||
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1]) {
|
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]})`);
|
||||||
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
||||||
push(errs, 'jmin > jmax');
|
push(errs, 'jmin > jmax');
|
||||||
@@ -240,6 +336,37 @@ export function obf_neutral(o) {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The junk a device sends is its own: within the preset's own ranges, the
|
||||||
|
* count and sizes are shifted a little by the device (deterministic, so the
|
||||||
|
* configuration keeps its fingerprint), so two phones of one family do not
|
||||||
|
* share one profile. Server-side values (headers, padding sizes, the header
|
||||||
|
* protection key) stay the server's.
|
||||||
|
*/
|
||||||
|
function client_obf(srv, dev) {
|
||||||
|
let o = { ...srv.obf };
|
||||||
|
if (obf_neutral(o) || !(+o.jc > 0))
|
||||||
|
return o;
|
||||||
|
let key = `${srv.id}/${dev.id}/${srv.obf.h1 ?? ''}`;
|
||||||
|
let seed = 2166136261;
|
||||||
|
for (let i = 0; i < length(key); i++)
|
||||||
|
seed = ((seed ^ ord(key, i)) * 16777619) & 0x7fffffff;
|
||||||
|
let pick = (n) => {
|
||||||
|
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
|
||||||
|
return seed % n;
|
||||||
|
};
|
||||||
|
let jc = +o.jc, jmin = +o.jmin, jmax = +o.jmax;
|
||||||
|
o.jc = `${max(1, min(10, jc + pick(3) - 1))}`;
|
||||||
|
if (jmax > jmin + 32) {
|
||||||
|
let d = pick(17);
|
||||||
|
o.jmin = `${jmin + d}`;
|
||||||
|
o.jmax = `${jmax - pick(17)}`;
|
||||||
|
if (+o.jmax <= +o.jmin)
|
||||||
|
o.jmax = `${+o.jmin + 32}`;
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
export function client_config(m, dev) {
|
export function client_config(m, dev) {
|
||||||
let p = m.people[dev.person];
|
let p = m.people[dev.person];
|
||||||
let srv = p ? m.servers[p.server] : null;
|
let srv = p ? m.servers[p.server] : null;
|
||||||
@@ -249,37 +376,42 @@ export function client_config(m, dev) {
|
|||||||
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
||||||
let allowed = allowed_ips(m, srv, p);
|
let allowed = allowed_ips(m, srv, p);
|
||||||
let dns = core.client_dns(m, srv, p);
|
let dns = core.client_dns(m, srv, p);
|
||||||
|
let mtu = core.device_mtu(srv, dev);
|
||||||
let lines = [ '[Interface]' ];
|
let lines = [ '[Interface]' ];
|
||||||
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
|
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
|
||||||
push(lines, `Address = ${dev.address}/32`);
|
push(lines, `Address = ${dev.address}/32`);
|
||||||
if (length(dns))
|
if (length(dns))
|
||||||
push(lines, `DNS = ${join(', ', dns)}`);
|
push(lines, `DNS = ${join(', ', dns)}`);
|
||||||
push(lines, `MTU = ${srv.mtu}`);
|
push(lines, `MTU = ${mtu}`);
|
||||||
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
|
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
|
||||||
// out, so any WireGuard app accepts the file.
|
// out, so any WireGuard app accepts the file.
|
||||||
if (!obf_neutral(srv.obf))
|
let obf = client_obf(srv, dev);
|
||||||
|
if (!obf_neutral(obf))
|
||||||
for (let k in core.OBF_KEYS)
|
for (let k in core.OBF_KEYS)
|
||||||
if (srv.obf[k] != null && srv.obf[k] != '')
|
if (obf[k] != null && obf[k] != '')
|
||||||
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
|
push(lines, `${OBF_CONF[k]} = ${obf[k]}`);
|
||||||
push(lines, '', '[Peer]');
|
push(lines, '', '[Peer]');
|
||||||
push(lines, `PublicKey = ${srv.public_key}`);
|
push(lines, `PublicKey = ${srv.public_key}`);
|
||||||
if (dev.preshared_key)
|
if (dev.preshared_key)
|
||||||
push(lines, `PresharedKey = ${dev.preshared_key}`);
|
push(lines, `PresharedKey = ${dev.preshared_key}`);
|
||||||
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
|
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
|
||||||
push(lines, `Endpoint = ${ep}:${srv.port}`);
|
push(lines, `Endpoint = ${ep}:${srv.port}`);
|
||||||
|
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
|
||||||
|
// other timers; a fixed beat would be the one regular thing left.
|
||||||
if (srv.keepalive > 0)
|
if (srv.keepalive > 0)
|
||||||
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
|
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`);
|
||||||
return {
|
return {
|
||||||
name: dev.name,
|
name: dev.name,
|
||||||
person: p.name,
|
person: p.name,
|
||||||
server: srv.name,
|
server: srv.name,
|
||||||
filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`,
|
// The file name is the tunnel's name in WireGuard apps: the server's, in the portal and the admin alike.
|
||||||
|
filename: `${tunnel_name(srv.name)}.conf`,
|
||||||
conf: join('\n', lines) + '\n',
|
conf: join('\n', lines) + '\n',
|
||||||
has_private_key: dev.private_key != '',
|
has_private_key: dev.private_key != '',
|
||||||
amnezia: {
|
amnezia: {
|
||||||
host,
|
host,
|
||||||
port: srv.port,
|
port: srv.port,
|
||||||
mtu: `${srv.mtu}`,
|
mtu: `${mtu}`,
|
||||||
dns,
|
dns,
|
||||||
allowed_ips: allowed,
|
allowed_ips: allowed,
|
||||||
client_ip: dev.address,
|
client_ip: dev.address,
|
||||||
@@ -288,7 +420,7 @@ export function client_config(m, dev) {
|
|||||||
psk_key: dev.preshared_key,
|
psk_key: dev.preshared_key,
|
||||||
server_pub_key: srv.public_key,
|
server_pub_key: srv.public_key,
|
||||||
persistent_keep_alive: `${srv.keepalive}`,
|
persistent_keep_alive: `${srv.keepalive}`,
|
||||||
obfuscation: srv.obf,
|
obfuscation: obf,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -307,13 +439,16 @@ export function netifd_options(srv) {
|
|||||||
private_key: srv.private_key,
|
private_key: srv.private_key,
|
||||||
listen_port: srv.port,
|
listen_port: srv.port,
|
||||||
addresses: [ `${addr}/${prefix}` ],
|
addresses: [ `${addr}/${prefix}` ],
|
||||||
mtu: srv.mtu,
|
mtu: core.tunnel_mtu(srv),
|
||||||
};
|
};
|
||||||
for (let k in core.OBF_KEYS)
|
for (let k in core.OBF_KEYS)
|
||||||
o[`awg_${k}`] = srv.obf[k];
|
o[`awg_${k}`] = srv.obf[k];
|
||||||
return o;
|
return o;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
|
||||||
|
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
|
||||||
|
|
||||||
/** Push the peer list of every server to the kernel without restarting it. */
|
/** Push the peer list of every server to the kernel without restarting it. */
|
||||||
export function sync_peers(m, states) {
|
export function sync_peers(m, states) {
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
@@ -329,7 +464,12 @@ export function sync_peers(m, states) {
|
|||||||
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
||||||
for (let did, d in m.devices) {
|
for (let did, d in m.devices) {
|
||||||
let p = m.people[d.person];
|
let p = m.people[d.person];
|
||||||
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
|
// One malformed line makes syncconf refuse the whole server: such a device
|
||||||
|
// stays out (Health's Data check names it). Over the data limit or
|
||||||
|
// outside the allowed hours the tunnel stays: the access table blocks
|
||||||
|
// everything but the portal, which says why (a silent handshake failure
|
||||||
|
// would look like a broken VPN).
|
||||||
|
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
|
||||||
continue;
|
continue;
|
||||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||||
if (d.preshared_key)
|
if (d.preshared_key)
|
||||||
@@ -349,17 +489,24 @@ export function sync_peers(m, states) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||||
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer
|
* Lines are told apart by their shape, not their length (each AmneziaWG
|
||||||
* lines always have 9. The tool fails when any one interface can't be read,
|
* generation adds fields to the interface line): an interface line carries
|
||||||
* but still prints the others: those are kept and `ok` is false, so only the
|
* its private and public key and a port, a peer line the peer's key, a
|
||||||
* interfaces listed in `ifaces` are known.
|
* preshared key or "(none)" and an endpoint. The tool fails when any one
|
||||||
|
* interface can't be read, but still prints the others: with `wanted` (the
|
||||||
|
* ifnames that matter) `ok` means those were all read, so another tunnel's
|
||||||
|
* trouble is not ours.
|
||||||
*/
|
*/
|
||||||
export function dump() {
|
export function dump(wanted) {
|
||||||
let r = sh('awg show all dump');
|
let r = sh('awg show all dump');
|
||||||
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
|
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
|
||||||
for (let line in split(r.out, '\n')) {
|
for (let line in split(r.out, '\n')) {
|
||||||
let f = split(line, '\t');
|
let f = split(line, '\t');
|
||||||
if (length(f) == 9) {
|
if (length(f) < 5 || !valid_key(f[1]))
|
||||||
|
continue;
|
||||||
|
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
|
||||||
|
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||||
|
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
|
||||||
let ep = f[3] == '(none)' ? '' : f[3];
|
let ep = f[3] == '(none)' ? '' : f[3];
|
||||||
out.peers[f[1]] = {
|
out.peers[f[1]] = {
|
||||||
ifname: f[0],
|
ifname: f[0],
|
||||||
@@ -369,10 +516,9 @@ export function dump() {
|
|||||||
tx: +f[7],
|
tx: +f[7],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
else if (length(f) >= 5) {
|
|
||||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if (!out.ok && type(wanted) == 'array')
|
||||||
|
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
|
||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -462,10 +608,15 @@ function fnv32(str) {
|
|||||||
return sprintf('%08x', h);
|
return sprintf('%08x', h);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What a device holds, minus its private key: changes when it must import again. */
|
/**
|
||||||
|
* What a device holds, minus its private key: changes when it must import
|
||||||
|
* again. The junk count and sizes (Jc, Jmin, Jmax) are the device's own and
|
||||||
|
* never have to match the server, so they are left out: a change there is
|
||||||
|
* no reason to import again.
|
||||||
|
*/
|
||||||
export function config_fingerprint(m, dev) {
|
export function config_fingerprint(m, dev) {
|
||||||
let c = dev ? client_config(m, dev) : null;
|
let c = dev ? client_config(m, dev) : null;
|
||||||
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^PrivateKey/)))) : null;
|
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
||||||
@@ -491,3 +642,33 @@ export function mark_issued(m, id) {
|
|||||||
unlock(l);
|
unlock(l);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* ---------- set up again (Reconnect) ---------- */
|
||||||
|
|
||||||
|
const RECONNECT = `${DATA_DIR}/reconnect.json`;
|
||||||
|
|
||||||
|
/** Device id → when the person asked to set it up again (router clock). */
|
||||||
|
export function reconnects() {
|
||||||
|
return read_json(RECONNECT, {});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The handshake a device counts with: none from before it was set up again,
|
||||||
|
* so it shows "Not set up yet" until it connects after that.
|
||||||
|
*/
|
||||||
|
export function handshake_since(hs, since) {
|
||||||
|
return since && hs <= since ? 0 : hs;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A device is set up again: handshakes up to `at` (router clock) are its old configuration's. */
|
||||||
|
export function mark_reconnect(m, id, at) {
|
||||||
|
let l = lock('reconnect');
|
||||||
|
let all = reconnects();
|
||||||
|
all[id] = at ?? time();
|
||||||
|
for (let k in keys(all))
|
||||||
|
if (!m.devices[k])
|
||||||
|
delete all[k];
|
||||||
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
write_json(RECONNECT, all, 0o600);
|
||||||
|
unlock(l);
|
||||||
|
};
|
||||||
|
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import { readfile } from 'fs';
|
import { readfile } from 'fs';
|
||||||
import { connect } from 'ubus';
|
import { connect } from 'ubus';
|
||||||
|
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
|
||||||
import * as pkg from 'dawnline.pkg';
|
import * as pkg from 'dawnline.pkg';
|
||||||
|
|
||||||
export const SOURCES = {
|
export const SOURCES = {
|
||||||
@@ -28,7 +29,36 @@ export function firmware() {
|
|||||||
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
|
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
|
||||||
if (!rel.version || length(target) != 2 || !arch)
|
if (!rel.version || length(target) != 2 || !arch)
|
||||||
return null;
|
return null;
|
||||||
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext() };
|
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext(),
|
||||||
|
snapshot: match(rel.version, /SNAPSHOT/) != null };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
|
||||||
|
export const RECORD = `${DATA_DIR}/awg.json`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remember which build was installed on which kernel. After a firmware
|
||||||
|
* upgrade the module is gone (it was built for that kernel): Health can then
|
||||||
|
* say so and offer the build for the new one (dawnline.health).
|
||||||
|
*/
|
||||||
|
export function record(source, tag, packages) {
|
||||||
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
write_json(RECORD, {
|
||||||
|
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
|
||||||
|
source, tag, packages, installed: time(),
|
||||||
|
}, 0o600);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The firmware the recorded AmneziaWG build was for, when it is not this one
|
||||||
|
* (and the module is gone): { was, now, tag, source }, else null.
|
||||||
|
*/
|
||||||
|
export function kernel_changed() {
|
||||||
|
let r = read_json(RECORD, null);
|
||||||
|
let now = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||||
|
if (!r?.osrelease || r.osrelease == now)
|
||||||
|
return null;
|
||||||
|
return { was: r.osrelease, now, tag: r.tag, source: r.source };
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The file name of a package in a build. */
|
/** The file name of a package in a build. */
|
||||||
@@ -41,9 +71,21 @@ export function for_tag(fw, tag) {
|
|||||||
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
|
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
|
||||||
};
|
};
|
||||||
|
|
||||||
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
|
/**
|
||||||
|
* AmneziaWG generation of a package version: 3.x packages carry 3.1; 1.0.x
|
||||||
|
* ones are 2.0 (S3/S4, I1-I5, header ranges) from July 2025 on, and the
|
||||||
|
* first generation before that. A kernel module's version carries the kernel
|
||||||
|
* release in front (6.12.94.3.1.20260906): the AmneziaWG part is at the end.
|
||||||
|
*/
|
||||||
export function gen(version) {
|
export function gen(version) {
|
||||||
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
|
if (version == null)
|
||||||
|
return null;
|
||||||
|
let v = match(`${version}`, /([0-9]+\.[0-9]+\.[0-9]{8})(-r?[0-9]+)?$/)?.[1] ?? `${version}`;
|
||||||
|
if (match(v, /^3\./))
|
||||||
|
return '3.1';
|
||||||
|
if (match(v, /^1\.0\.2024/) || match(v, /^1\.0\.20250[1-6]/))
|
||||||
|
return '1.0';
|
||||||
|
return '2.0';
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The installed AmneziaWG packages: { name: version | null }. */
|
/** The installed AmneziaWG packages: { name: version | null }. */
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// only Dawnline's own regular files, and servers that cannot take over one of
|
// only Dawnline's own regular files, and servers that cannot take over one of
|
||||||
// the router's own interfaces or networks.
|
// the router's own interfaces or networks.
|
||||||
|
|
||||||
import { readfile, stat, unlink, lsdir } from 'fs';
|
import { readfile, stat, unlink, lsdir, rename } from 'fs';
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import {
|
import {
|
||||||
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
|
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
|
||||||
@@ -15,24 +15,36 @@ import * as net from 'dawnline.net';
|
|||||||
import * as health from 'dawnline.health';
|
import * as health from 'dawnline.health';
|
||||||
|
|
||||||
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
const BACKUP_DIR = `${DATA_DIR}/backups`;
|
||||||
const KEEP_BACKUPS = 10;
|
/**
|
||||||
|
* How many backups of each kind stay (the newest): the nightly ones must not
|
||||||
|
* push out what the admin made by hand or what a removal left behind.
|
||||||
|
*/
|
||||||
|
const KEEP = { manual: 10, auto: 7, 'pre-delete': 5, 'pre-remove': 3, 'pre-update': 3, 'pre-restore': 3, 'pre-import': 3 };
|
||||||
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
|
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
|
||||||
/** What a backup holds (paths inside the archive, relative to /). */
|
/** What a backup holds (paths inside the archive, relative to /). */
|
||||||
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
|
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
|
||||||
|
/**
|
||||||
|
* Kinds that hold the config alone (about 20 KB): the history can be a
|
||||||
|
* megabyte or more, and these are made often and never to bring history
|
||||||
|
* back. Manual, pre-restore and pre-import backups protect the data that is
|
||||||
|
* about to be replaced, so they take everything.
|
||||||
|
*/
|
||||||
|
const CONFIG_ONLY = [ 'auto', 'pre-delete', 'pre-remove', 'pre-update' ];
|
||||||
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
|
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
|
||||||
const MAX_UNPACKED = 16 * 1024 * 1024;
|
const MAX_UNPACKED = 16 * 1024 * 1024;
|
||||||
|
|
||||||
/* ---------- checking a configuration before it is used ---------- */
|
/* ---------- checking a configuration before it is used ---------- */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What is wrong with the servers of a configuration about to replace the
|
* What is wrong with a configuration about to replace the current one
|
||||||
* current one (cursor `c` holds it): each must have a valid, unique interface
|
* (cursor `c` holds it): each server must have a valid, unique interface
|
||||||
* name that is not one of the router's own interfaces, a free subnet and a
|
* name that is not one of the router's own interfaces, a free subnet and a
|
||||||
* unique port. [] when it can be used.
|
* unique port, and the people and devices must be consistent
|
||||||
|
* (core.model_errors). [] when it can be used.
|
||||||
*/
|
*/
|
||||||
export function config_errors(c) {
|
export function config_errors(c) {
|
||||||
let m = core.load(c);
|
let m = core.load(c);
|
||||||
let errs = [];
|
let errs = core.model_errors(m);
|
||||||
let nc = cursor();
|
let nc = cursor();
|
||||||
nc.load('network');
|
nc.load('network');
|
||||||
let foreign = health.foreign_subnets();
|
let foreign = health.foreign_subnets();
|
||||||
@@ -92,30 +104,41 @@ export function backup_list() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Make a backup now; returns its name. The oldest beyond KEEP_BACKUPS are
|
* Make a backup now; returns its name. Written whole or not at all (a half
|
||||||
* removed, except `keep` (the backup being restored, which must survive the
|
* archive from a full flash never shows up as a backup). Of each kind the
|
||||||
* backup made just before restoring it).
|
* oldest beyond KEEP are removed, except `keep` (the backup being restored,
|
||||||
|
* which must survive the backup made just before restoring it).
|
||||||
*/
|
*/
|
||||||
export function backup_create(reason, keep) {
|
export function backup_create(reason, keep) {
|
||||||
|
let kind = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? reason : 'manual';
|
||||||
|
let config_only = index(CONFIG_ONLY, kind) >= 0;
|
||||||
// Flush live counters first so the backup has current usage.
|
// Flush live counters first so the backup has current usage.
|
||||||
let u = read_json(`${RUN_DIR}/usage.json`, null);
|
if (!config_only) {
|
||||||
if (u)
|
let u = read_json(`${RUN_DIR}/usage.json`, null);
|
||||||
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
|
if (u)
|
||||||
live.persist_events();
|
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
|
||||||
|
live.persist_events();
|
||||||
|
}
|
||||||
ensure_dir(BACKUP_DIR, 0o700);
|
ensure_dir(BACKUP_DIR, 0o700);
|
||||||
let t = localtime();
|
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, kind == 'manual' ? '' : `-${kind}`);
|
||||||
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 want = config_only ? [ FILES[0] ] : FILES;
|
||||||
let files = join(' ', map(filter(FILES, (f) => file_exists(`/${f}`)), q));
|
let files = join(' ', map(filter(want, (f) => file_exists(`/${f}`)), q));
|
||||||
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
|
// Not a NAME until it is complete.
|
||||||
if (r.code != 0)
|
let tmp = `${BACKUP_DIR}/.${name}.tmp`;
|
||||||
die(`Backup failed: ${trim(r.out)}`);
|
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
|
||||||
|
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
|
||||||
|
unlink(tmp);
|
||||||
|
die(`Backup failed: ${trim(r.out) || 'the archive could not be written (is the flash full?)'}`);
|
||||||
|
}
|
||||||
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
|
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
|
||||||
let all = backup_list();
|
let by_kind = {};
|
||||||
let old = filter(all, (b) => b.name != keep && b.name != name);
|
for (let b in backup_list())
|
||||||
let room = KEEP_BACKUPS - 1 - (length(old) < length(all) - 1 ? 1 : 0);
|
if (b.name != keep && b.name != name)
|
||||||
for (let i = room; i < length(old); i++)
|
push(by_kind[b.reason] ??= [], b);
|
||||||
unlink(`${BACKUP_DIR}/${old[i].name}`);
|
for (let k, list in by_kind)
|
||||||
|
for (let i = KEEP[k] ?? 3; i < length(list); i++)
|
||||||
|
unlink(`${BACKUP_DIR}/${list[i].name}`);
|
||||||
return name;
|
return name;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -155,14 +178,24 @@ function check_archive(path) {
|
|||||||
die('Backup is too large.');
|
die('Backup is too large.');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Put the files unpacked in `dir` in place, under the config lock. */
|
/**
|
||||||
|
* Put the files unpacked in `dir` in place, under the config lock. The
|
||||||
|
* config goes first: when it cannot be written nothing else is touched, and
|
||||||
|
* a data file that fails afterwards is reported, not ignored.
|
||||||
|
*/
|
||||||
function install_files(dir) {
|
function install_files(dir) {
|
||||||
ensure_dir(DATA_DIR, 0o700);
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
let l = lock('config');
|
let l = lock('config');
|
||||||
for (let f in FILES) {
|
try {
|
||||||
let data = readfile(`${dir}/${f}`);
|
for (let f in FILES) {
|
||||||
if (data != null)
|
let data = readfile(`${dir}/${f}`);
|
||||||
write_file(`/${f}`, data, 0o600);
|
if (data != null && !write_file(`/${f}`, data, 0o600))
|
||||||
|
die(`Couldn't write /${f}. Is the flash full?`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
unlock(l);
|
||||||
|
die(e.message);
|
||||||
}
|
}
|
||||||
unlock(l);
|
unlock(l);
|
||||||
system('chmod 600 /etc/config/dawnline');
|
system('chmod 600 /etc/config/dawnline');
|
||||||
@@ -185,9 +218,11 @@ export function backup_restore(name, path) {
|
|||||||
die(e.message);
|
die(e.message);
|
||||||
}
|
}
|
||||||
system(`rm -rf ${q(dir)}`);
|
system(`rm -rf ${q(dir)}`);
|
||||||
// Live counters must follow the restored file.
|
// Live counters must follow the restored file: the agent reloads them from
|
||||||
|
// flash on its next tick (its watcher may write the old ones again before).
|
||||||
unlink(`${RUN_DIR}/usage.json`);
|
unlink(`${RUN_DIR}/usage.json`);
|
||||||
unlink(`${RUN_DIR}/events.json`);
|
unlink(`${RUN_DIR}/events.json`);
|
||||||
|
write_file(live.USAGE_RELOAD, `${time()}`, 0o600);
|
||||||
return apply.apply();
|
return apply.apply();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -279,7 +314,9 @@ export function import_json(data) {
|
|||||||
system(`rm -rf ${q(dir)}`);
|
system(`rm -rf ${q(dir)}`);
|
||||||
backup_create('pre-import');
|
backup_create('pre-import');
|
||||||
let l = lock('config');
|
let l = lock('config');
|
||||||
write_file('/etc/config/dawnline', text, 0o600);
|
let ok = write_file('/etc/config/dawnline', text, 0o600);
|
||||||
unlock(l);
|
unlock(l);
|
||||||
|
if (!ok)
|
||||||
|
die("Couldn't write /etc/config/dawnline. Is the flash full?");
|
||||||
return apply.apply();
|
return apply.apply();
|
||||||
};
|
};
|
||||||
@@ -4,10 +4,11 @@
|
|||||||
|
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import {
|
import {
|
||||||
valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, NAME_RULE, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||||
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
|
import * as schema from 'dawnline.schema';
|
||||||
import { policy as updates_policy } from 'dawnline.updates';
|
import { policy as updates_policy } from 'dawnline.updates';
|
||||||
|
|
||||||
export const CONFIG = 'dawnline';
|
export const CONFIG = 'dawnline';
|
||||||
@@ -20,6 +21,8 @@ export const CONFIG = 'dawnline';
|
|||||||
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
|
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
|
||||||
export const ACCESS = [ 'lan', 'internet', 'both' ];
|
export const ACCESS = [ 'lan', 'internet', 'both' ];
|
||||||
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
|
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
|
||||||
|
/** Kinds that mostly live on mobile networks: their configurations carry a smaller MTU. */
|
||||||
|
export const MOBILE_KINDS = [ 'phone', 'tablet' ];
|
||||||
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
|
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
|
||||||
export const MESH = [ 'off', 'all', 'circles' ];
|
export const MESH = [ 'off', 'all', 'circles' ];
|
||||||
/** Circle colours (index into the admin palette). */
|
/** Circle colours (index into the admin palette). */
|
||||||
@@ -66,29 +69,30 @@ export function open_cursor() {
|
|||||||
export function load(c) {
|
export function load(c) {
|
||||||
c ??= open_cursor();
|
c ??= open_cursor();
|
||||||
let s = c.get_all(CONFIG, 'settings') ?? {};
|
let s = c.get_all(CONFIG, 'settings') ?? {};
|
||||||
|
// Types, defaults and ranges of the settings live in dawnline.schema (one
|
||||||
|
// place): what is read here is what settings_update would have accepted.
|
||||||
|
let g = (k) => schema.get(s, k);
|
||||||
let m = {
|
let m = {
|
||||||
settings: {
|
settings: {
|
||||||
portal_enabled: bool(s.portal_enabled, false),
|
portal_enabled: g('portal_enabled'),
|
||||||
portal_port: toint(s.portal_port, 8443),
|
portal_port: g('portal_port'),
|
||||||
portal_host: s.portal_host ?? '',
|
portal_host: g('portal_host'),
|
||||||
// More addresses for the same links (the main one is portal_host).
|
// More addresses for the same links (the main one is portal_host).
|
||||||
portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''),
|
portal_alt: g('portal_alt'),
|
||||||
portal_cert: s.portal_cert ?? '',
|
portal_cert: g('portal_cert'),
|
||||||
portal_key: s.portal_key ?? '',
|
portal_key: g('portal_key'),
|
||||||
portal_title: s.portal_title ?? 'Dawnline',
|
|
||||||
// Where unknown portal links go instead of a bare 404 (empty = 404).
|
// Where unknown portal links go instead of a bare 404 (empty = 404).
|
||||||
portal_redirect: s.portal_redirect ?? '',
|
portal_redirect: g('portal_redirect'),
|
||||||
paused_all: bool(s.paused_all, false),
|
default_device_limit: g('default_device_limit'),
|
||||||
default_device_limit: toint(s.default_device_limit, 3),
|
geo_enabled: g('geo_enabled'),
|
||||||
geo_enabled: bool(s.geo_enabled, true),
|
geo_provider: g('geo_provider'),
|
||||||
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is',
|
hostnames: g('hostnames'),
|
||||||
hostnames: bool(s.hostnames, true),
|
domain: g('domain'),
|
||||||
domain: s.domain ?? 'lan',
|
log_connections: g('log_connections'),
|
||||||
log_connections: bool(s.log_connections, true),
|
|
||||||
// Repair tunnels and services on its own (the agent, every minute).
|
// Repair tunnels and services on its own (the agent, every minute).
|
||||||
watchdog: bool(s.watchdog, true),
|
watchdog: g('watchdog'),
|
||||||
// Second DNS for "home names" devices, used by the device when the tunnel is down.
|
// Second DNS for "home names" devices, used by the device when the tunnel is down.
|
||||||
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'),
|
home_dns_fallback: g('home_dns_fallback'),
|
||||||
// Settings → Updates (automatic checks and updates of the components).
|
// Settings → Updates (automatic checks and updates of the components).
|
||||||
updates: updates_policy(s),
|
updates: updates_policy(s),
|
||||||
// Raw retention values; dawnline.live policy() interprets them.
|
// Raw retention values; dawnline.live policy() interprets them.
|
||||||
@@ -115,7 +119,8 @@ export function load(c) {
|
|||||||
port: toint(r.port, 51820),
|
port: toint(r.port, 51820),
|
||||||
subnet: r.subnet ?? '',
|
subnet: r.subnet ?? '',
|
||||||
endpoint: r.endpoint ?? '',
|
endpoint: r.endpoint ?? '',
|
||||||
mtu: toint(r.mtu, 1380),
|
// 0 = automatic (tunnel_mtu, device_mtu).
|
||||||
|
mtu: toint(r.mtu, 0),
|
||||||
dns: list(r.dns),
|
dns: list(r.dns),
|
||||||
keepalive: toint(r.keepalive, 25),
|
keepalive: toint(r.keepalive, 25),
|
||||||
private_key: r.private_key ?? '',
|
private_key: r.private_key ?? '',
|
||||||
@@ -156,6 +161,8 @@ export function load(c) {
|
|||||||
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
|
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
|
||||||
device_limit: toint(r.device_limit, m.settings.default_device_limit),
|
device_limit: toint(r.device_limit, m.settings.default_device_limit),
|
||||||
code: r.code ?? '',
|
code: r.code ?? '',
|
||||||
|
// When the personal link was last made (0 for links from before this was kept).
|
||||||
|
code_set: toint(r.code_set, 0),
|
||||||
expires: r.expires ?? '',
|
expires: r.expires ?? '',
|
||||||
quota_gb: num(r.quota_gb, 0),
|
quota_gb: num(r.quota_gb, 0),
|
||||||
quota_period: r.quota_period == 'total' ? 'total' : 'month',
|
quota_period: r.quota_period == 'total' ? 'total' : 'month',
|
||||||
@@ -234,23 +241,23 @@ function within_hours(h, ts) {
|
|||||||
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
|
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Bytes used in the person's quota period. */
|
/** Bytes used in the person's quota period (the month of `ts`, default now). */
|
||||||
export function person_usage(p, usage) {
|
export function person_usage(p, usage, ts) {
|
||||||
let u = usage?.people?.[p.id];
|
let u = usage?.people?.[p.id];
|
||||||
if (!u)
|
if (!u)
|
||||||
return 0;
|
return 0;
|
||||||
if (p.quota_period == 'total')
|
if (p.quota_period == 'total')
|
||||||
return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0);
|
return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0);
|
||||||
let mm = u.months?.[month_key()];
|
let mm = u.months?.[month_key(ts)];
|
||||||
return mm ? mm[0] + mm[1] : 0;
|
return mm ? mm[0] + mm[1] : 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Quota in bytes for the current period (base + this month's bonus), 0 = unlimited. */
|
/** Quota in bytes for the period of `ts` (default now): base + that month's bonus, 0 = unlimited. */
|
||||||
export function person_quota(p) {
|
export function person_quota(p, ts) {
|
||||||
if (!(p.quota_gb > 0))
|
if (!(p.quota_gb > 0))
|
||||||
return 0;
|
return 0;
|
||||||
let gb = p.quota_gb;
|
let gb = p.quota_gb;
|
||||||
if (p.bonus_gb > 0 && p.bonus_month == month_key())
|
if (p.bonus_gb > 0 && p.bonus_month == month_key(ts))
|
||||||
gb += p.bonus_gb;
|
gb += p.bonus_gb;
|
||||||
return gb * 1073741824;
|
return gb * 1073741824;
|
||||||
};
|
};
|
||||||
@@ -262,24 +269,16 @@ export function person_expired(p, ts) {
|
|||||||
return end != null && (ts ?? time()) > end;
|
return end != null && (ts ?? time()) > end;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/** The person's state whatever their server is doing (paused, expired, …, or 'active'). */
|
||||||
* Effective state of a person: 'active', or why they are off:
|
export function own_state(m, p, usage, ts) {
|
||||||
* 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'.
|
|
||||||
*/
|
|
||||||
export function person_state(m, p, usage, ts) {
|
|
||||||
ts ??= time();
|
ts ??= time();
|
||||||
let srv = m.servers[p.server];
|
|
||||||
if (!srv || !srv.enabled)
|
|
||||||
return 'no_server';
|
|
||||||
if (p.paused)
|
if (p.paused)
|
||||||
return 'paused';
|
return 'paused';
|
||||||
if (m.settings.paused_all)
|
|
||||||
return 'paused_all';
|
|
||||||
// "notify" keeps access after the end date (shown in Overview and People).
|
// "notify" keeps access after the end date (shown in Overview and People).
|
||||||
if (person_expired(p, ts) && p.expire_action != 'notify')
|
if (person_expired(p, ts) && p.expire_action != 'notify')
|
||||||
return 'expired';
|
return 'expired';
|
||||||
let quota = person_quota(p);
|
let quota = person_quota(p, ts);
|
||||||
if (quota > 0 && person_usage(p, usage) >= quota)
|
if (quota > 0 && person_usage(p, usage, ts) >= quota)
|
||||||
return 'quota';
|
return 'quota';
|
||||||
let h = parse_hours(p.hours);
|
let h = parse_hours(p.hours);
|
||||||
if (h && !within_hours(h, ts))
|
if (h && !within_hours(h, ts))
|
||||||
@@ -287,6 +286,20 @@ export function person_state(m, p, usage, ts) {
|
|||||||
return 'active';
|
return 'active';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Effective state of a person: 'active', or why they are off:
|
||||||
|
* 'paused' (admin), 'expired', 'quota', 'hours', 'no_server',
|
||||||
|
* 'server_off' (their server is turned off: about the server, not the person).
|
||||||
|
*/
|
||||||
|
export function person_state(m, p, usage, ts) {
|
||||||
|
let srv = m.servers[p.server];
|
||||||
|
if (!srv)
|
||||||
|
return 'no_server';
|
||||||
|
if (!srv.enabled)
|
||||||
|
return 'server_off';
|
||||||
|
return own_state(m, p, usage, ts);
|
||||||
|
};
|
||||||
|
|
||||||
export function load_usage() {
|
export function load_usage() {
|
||||||
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
|
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
|
||||||
};
|
};
|
||||||
@@ -344,6 +357,27 @@ export function alloc_address(m, srv) {
|
|||||||
|
|
||||||
/* ---------- what clients get ---------- */
|
/* ---------- what clients get ---------- */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Automatic MTU. A path is assumed to carry 1460 bytes (1500 less PPPoE,
|
||||||
|
* 464XLAT or DS-Lite), the tunnel's own headers take 80 over IPv6, and
|
||||||
|
* AmneziaWG's S4 adds its bytes to every data packet (its padding and random
|
||||||
|
* trailers stay within the largest packet already seen, so they cost
|
||||||
|
* nothing). Phones and tablets get 1280, the IPv6 minimum: mobile paths vary.
|
||||||
|
*/
|
||||||
|
const AUTO_MTU = 1380;
|
||||||
|
const MOBILE_MTU = 1280;
|
||||||
|
|
||||||
|
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
|
||||||
|
export function tunnel_mtu(srv) {
|
||||||
|
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
|
||||||
|
export function device_mtu(srv, dev) {
|
||||||
|
let mtu = tunnel_mtu(srv);
|
||||||
|
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
|
||||||
|
};
|
||||||
|
|
||||||
export function endpoint_host(m, srv) {
|
export function endpoint_host(m, srv) {
|
||||||
return srv.endpoint || m.settings.portal_host || '';
|
return srv.endpoint || m.settings.portal_host || '';
|
||||||
};
|
};
|
||||||
@@ -447,7 +481,7 @@ export function new_code() {
|
|||||||
|
|
||||||
export function create_person(c, m, a) {
|
export function create_person(c, m, a) {
|
||||||
if (!valid_name(a.name))
|
if (!valid_name(a.name))
|
||||||
fail('Enter a name (up to 48 characters).');
|
fail(NAME_RULE);
|
||||||
// The id is a UCI section name: letters, digits and underscores only (a dash
|
// The id is a UCI section name: letters, digits and underscores only (a dash
|
||||||
// makes uci drop the section). Repeated names get _2, _3, …
|
// makes uci drop the section). Repeated names get _2, _3, …
|
||||||
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
|
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
|
||||||
@@ -483,6 +517,7 @@ export function create_person(c, m, a) {
|
|||||||
c.set(CONFIG, slug, 'access', access);
|
c.set(CONFIG, slug, 'access', access);
|
||||||
c.set(CONFIG, slug, 'device_limit', `${limit}`);
|
c.set(CONFIG, slug, 'device_limit', `${limit}`);
|
||||||
c.set(CONFIG, slug, 'code', new_code());
|
c.set(CONFIG, slug, 'code', new_code());
|
||||||
|
c.set(CONFIG, slug, 'code_set', `${time()}`);
|
||||||
c.set(CONFIG, slug, 'created', `${time()}`);
|
c.set(CONFIG, slug, 'created', `${time()}`);
|
||||||
if (a.expires)
|
if (a.expires)
|
||||||
c.set(CONFIG, slug, 'expires', a.expires);
|
c.set(CONFIG, slug, 'expires', a.expires);
|
||||||
@@ -504,7 +539,7 @@ export function update_person(c, m, id, a) {
|
|||||||
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
|
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
|
||||||
if (a.name != null) {
|
if (a.name != null) {
|
||||||
if (!valid_name(a.name))
|
if (!valid_name(a.name))
|
||||||
fail('Enter a name (up to 48 characters).');
|
fail(NAME_RULE);
|
||||||
set('name', trim(a.name));
|
set('name', trim(a.name));
|
||||||
}
|
}
|
||||||
if (a.access != null) {
|
if (a.access != null) {
|
||||||
@@ -563,7 +598,7 @@ export function update_person(c, m, id, a) {
|
|||||||
set('hours', a.hours);
|
set('hours', a.hours);
|
||||||
}
|
}
|
||||||
if (a.note != null)
|
if (a.note != null)
|
||||||
set('note', substr(trim(a.note), 0, 500));
|
set('note', ucut(trim(a.note), 500));
|
||||||
if (type(a.services) == 'array') {
|
if (type(a.services) == 'array') {
|
||||||
for (let sid in a.services)
|
for (let sid in a.services)
|
||||||
if (!m.services[sid])
|
if (!m.services[sid])
|
||||||
@@ -579,6 +614,24 @@ export function update_person(c, m, id, a) {
|
|||||||
fail('Unknown circle.');
|
fail('Unknown circle.');
|
||||||
set('circle', a.circle);
|
set('circle', a.circle);
|
||||||
}
|
}
|
||||||
|
// Another server: every device gets an address in its tunnel (so each
|
||||||
|
// needs its configuration again); circles and home networks are the old
|
||||||
|
// server's and go.
|
||||||
|
if (a.server != null && a.server != '' && a.server != p.server) {
|
||||||
|
if (!m.servers[a.server])
|
||||||
|
fail('Unknown server.');
|
||||||
|
set('server', a.server);
|
||||||
|
p.server = a.server;
|
||||||
|
for (let did in p.devices) {
|
||||||
|
let addr = alloc_address(m, m.servers[a.server]);
|
||||||
|
if (!addr)
|
||||||
|
fail(`No free address left on ${m.servers[a.server].name}.`);
|
||||||
|
m.devices[did].address = addr;
|
||||||
|
c.set(CONFIG, did, 'address', addr);
|
||||||
|
}
|
||||||
|
c.delete(CONFIG, id, 'circle');
|
||||||
|
c.delete(CONFIG, id, 'home_net');
|
||||||
|
}
|
||||||
if (type(a.home_nets) == 'array') {
|
if (type(a.home_nets) == 'array') {
|
||||||
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
|
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
|
||||||
if (length(nets))
|
if (length(nets))
|
||||||
@@ -690,6 +743,16 @@ export function delete_person(c, m, id) {
|
|||||||
c.delete(CONFIG, id);
|
c.delete(CONFIG, id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const PRIVATE_NETS = map([ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
||||||
|
|
||||||
|
/** The parsed subnet lies inside one of the private ranges. */
|
||||||
|
export function private_cidr(c) {
|
||||||
|
for (let p in PRIVATE_NETS)
|
||||||
|
if (c.net >= p.net && c.net + c.size <= p.net + p.size)
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
/** Validate a server definition (as loaded) against the rest of the router. */
|
/** Validate a server definition (as loaded) against the rest of the router. */
|
||||||
export function server_errors(m, srv, others_subnets) {
|
export function server_errors(m, srv, others_subnets) {
|
||||||
let errs = [];
|
let errs = [];
|
||||||
@@ -711,21 +774,135 @@ export function server_errors(m, srv, others_subnets) {
|
|||||||
return errs;
|
return errs;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */
|
/**
|
||||||
export function wan_port_taken(port) {
|
* What is wrong inside a model as a whole, beyond each server: devices with
|
||||||
|
* an address outside their server's subnet, the server's own address, a
|
||||||
|
* prefix on it or one shared with another device (the access sets are keyed
|
||||||
|
* by address, and one bad peer line makes `awg syncconf` refuse the whole
|
||||||
|
* server), malformed keys, people and devices pointing at servers, people,
|
||||||
|
* circles or services that do not exist, and two people with one link. [] when
|
||||||
|
* it is consistent. Import, restore and Health check it; the runtime sync
|
||||||
|
* skips what it would reject (dawnline.awg, dawnline.nft).
|
||||||
|
*/
|
||||||
|
export function model_errors(m) {
|
||||||
|
let errs = [];
|
||||||
|
let codes = {}, addrs = {};
|
||||||
|
for (let id, p in m.people) {
|
||||||
|
let who = `Person ${p.name}`;
|
||||||
|
if (p.server != '' && !m.servers[p.server])
|
||||||
|
push(errs, `${who}: server ${p.server} does not exist.`);
|
||||||
|
if (p.circle != '' && !m.circles[p.circle])
|
||||||
|
push(errs, `${who}: circle ${p.circle} does not exist.`);
|
||||||
|
for (let sid in p.services)
|
||||||
|
if (!m.services[sid])
|
||||||
|
push(errs, `${who}: home service ${sid} does not exist.`);
|
||||||
|
if (p.code != '') {
|
||||||
|
if (codes[p.code])
|
||||||
|
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`);
|
||||||
|
codes[p.code] = p.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let id, d in m.devices) {
|
||||||
|
let p = m.people[d.person];
|
||||||
|
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
|
||||||
|
if (!p) {
|
||||||
|
push(errs, `${who}: person ${d.person} does not exist.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!valid_key(d.public_key))
|
||||||
|
push(errs, `${who}: the public key is not a key.`);
|
||||||
|
if (d.private_key != '' && !valid_key(d.private_key))
|
||||||
|
push(errs, `${who}: the private key is not a key.`);
|
||||||
|
if (d.preshared_key != '' && !valid_key(d.preshared_key))
|
||||||
|
push(errs, `${who}: the preshared key is not a key.`);
|
||||||
|
let n = ip2int(d.address);
|
||||||
|
if (n == null) {
|
||||||
|
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let srv = m.servers[p.server];
|
||||||
|
let t = srv ? parse_cidr(srv.subnet) : null;
|
||||||
|
if (t && (n < t.first || n > t.last))
|
||||||
|
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`);
|
||||||
|
else if (t && n == t.first)
|
||||||
|
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`);
|
||||||
|
let key = `${p.server} ${d.address}`;
|
||||||
|
if (addrs[key])
|
||||||
|
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`);
|
||||||
|
addrs[key] = who;
|
||||||
|
}
|
||||||
|
for (let id, ci in m.circles)
|
||||||
|
if (!m.servers[ci.server])
|
||||||
|
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`);
|
||||||
|
return errs;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give every device on a server an address in `subnet` (the server's new
|
||||||
|
* tunnel network), lowest first: used by server_update when the network
|
||||||
|
* changes. Each device then needs its configuration again (the address is
|
||||||
|
* in it). Fails when the subnet cannot hold them.
|
||||||
|
*/
|
||||||
|
export function renumber_server(c, m, srv, subnet) {
|
||||||
|
srv.subnet = subnet;
|
||||||
|
for (let pid, p in m.people)
|
||||||
|
if (p.server == srv.id)
|
||||||
|
for (let did in p.devices)
|
||||||
|
m.devices[did].address = '';
|
||||||
|
for (let pid, p in m.people)
|
||||||
|
if (p.server == srv.id)
|
||||||
|
for (let did in p.devices) {
|
||||||
|
let addr = alloc_address(m, srv);
|
||||||
|
if (!addr)
|
||||||
|
fail(`${subnet} has no room for every device on ${srv.name}.`);
|
||||||
|
m.devices[did].address = addr;
|
||||||
|
c.set(CONFIG, did, 'address', addr);
|
||||||
|
}
|
||||||
|
c.set(CONFIG, srv.id, 'subnet', subnet);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The DNS labels of a person's devices, { device id: label }, unique within
|
||||||
|
* the person: two devices whose names give one label ("iPhone" and
|
||||||
|
* "iPhone!", or two Cyrillic names) get -2, -3 by age. Hostnames in
|
||||||
|
* /tmp/hosts (dawnline.apply) and the ones the UI shows (dawnline.view) both
|
||||||
|
* come from here, so what is shown resolves.
|
||||||
|
*/
|
||||||
|
export function device_labels(m, p) {
|
||||||
|
let out = {}, used = {};
|
||||||
|
let devs = sort(map(p.devices, (id) => m.devices[id]), (a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||||
|
for (let d in devs) {
|
||||||
|
let base = host_label(d.name), l = base;
|
||||||
|
for (let n = 2; used[l]; n++)
|
||||||
|
l = `${substr(base, 0, 37)}-${n}`;
|
||||||
|
used[l] = true;
|
||||||
|
out[d.id] = l;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
|
||||||
|
* A forwarded port never reaches the router itself, so nothing here can listen on it.
|
||||||
|
*/
|
||||||
|
export function wan_forwards(zone, proto) {
|
||||||
let c = cursor();
|
let c = cursor();
|
||||||
c.load('firewall');
|
c.load('firewall');
|
||||||
let taken = false;
|
let out = [];
|
||||||
c.foreach('firewall', 'redirect', (r) => {
|
c.foreach('firewall', 'redirect', (r) => {
|
||||||
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT')
|
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
|
||||||
|
return;
|
||||||
|
// fw4's default is "tcp udp".
|
||||||
|
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
|
||||||
|
if (index(protos, proto) < 0 && index(protos, 'all') < 0 && index(protos, 'any') < 0)
|
||||||
return;
|
return;
|
||||||
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
|
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
|
||||||
let m = match(p, /^(\d+)([-:](\d+))?$/);
|
let m = match(p, /^(\d+)([-:](\d+))?$/);
|
||||||
if (m && +m[1] <= port && port <= +(m[3] || m[1]))
|
if (m)
|
||||||
taken = true;
|
push(out, { from: +m[1], to: +(m[3] || m[1]), name: r.name ?? r['.name'] });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return taken;
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Every address the links use, the main one first. */
|
/** Every address the links use, the main one first. */
|
||||||
@@ -767,7 +944,9 @@ export function portal_link(m, p, host) {
|
|||||||
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
|
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
|
||||||
}
|
}
|
||||||
let pp = portal_public_port(m);
|
let pp = portal_public_port(m);
|
||||||
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
|
// An IPv6 address needs its brackets in a URL.
|
||||||
|
let h = index(host, ':') >= 0 && !match(host, /^\[/) ? `[${host}]` : host;
|
||||||
|
return `https://${h}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The main link (QR, invite card, Copy link). */
|
/** The main link (QR, invite card, Copy link). */
|
||||||
|
|||||||
@@ -42,11 +42,11 @@ export function add(person, name, kind, opts) {
|
|||||||
opts ??= {};
|
opts ??= {};
|
||||||
let by = opts.by ?? 'admin';
|
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) }));
|
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
|
||||||
apply.sync();
|
let s = apply.sync();
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
|
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
|
||||||
awg.mark_issued(m, id);
|
awg.mark_issued(m, id);
|
||||||
return { id, config: awg.client_config(m, m.devices[id]) };
|
return { id, config: awg.client_config(m, m.devices[id]), warning: s.warning };
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -89,15 +89,34 @@ export function rotate(id, opts) {
|
|||||||
});
|
});
|
||||||
// The device a portal page came through would lose its tunnel before the
|
// The device a portal page came through would lose its tunnel before the
|
||||||
// answer gets out: load the new key a moment after answering.
|
// answer gets out: load the new key a moment after answering.
|
||||||
|
let s = null;
|
||||||
if (opts.defer)
|
if (opts.defer)
|
||||||
sh_bg('sleep 3; /usr/bin/dawnline sync');
|
sh_bg('sleep 3; /usr/bin/dawnline sync');
|
||||||
else
|
else
|
||||||
apply.sync();
|
s = apply.sync();
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let d = m.devices[id];
|
let d = m.devices[id];
|
||||||
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
|
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
|
||||||
awg.mark_issued(m, id);
|
awg.mark_issued(m, id);
|
||||||
return awg.client_config(m, d);
|
let cfg = awg.client_config(m, d);
|
||||||
|
if (s?.warning)
|
||||||
|
cfg.warning = s.warning;
|
||||||
|
return cfg;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a device up from scratch (a new phone, the app reinstalled, settings
|
||||||
|
* the admin changed): new keys, so the configuration it holds stops working
|
||||||
|
* with the sync, and it counts as not set up until it connects with the new
|
||||||
|
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
|
||||||
|
* it. Returns the new configuration, as rotate.
|
||||||
|
*/
|
||||||
|
export function reconnect(id, opts) {
|
||||||
|
opts ??= {};
|
||||||
|
let cfg = rotate(id, opts);
|
||||||
|
// A deferred sync (the page came through this device) lets the old keys live a few seconds more.
|
||||||
|
awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0));
|
||||||
|
return cfg;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Remove a device. Returns the runtime sync. */
|
/** Remove a device. Returns the runtime sync. */
|
||||||
|
|||||||
@@ -5,11 +5,12 @@
|
|||||||
// named dawnline_* are ever changed.
|
// named dawnline_* are ever changed.
|
||||||
|
|
||||||
import { readfile, unlink } from 'fs';
|
import { readfile, unlink } from 'fs';
|
||||||
import { q, sh, sh_out, uniq, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
|
import { q, sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
import * as nft from 'dawnline.nft';
|
import * as nft from 'dawnline.nft';
|
||||||
|
import * as loop from 'dawnline.loop';
|
||||||
|
|
||||||
const LOOP_ZONE = 'dl_loop';
|
const LOOP_ZONE = 'dl_loop';
|
||||||
/*
|
/*
|
||||||
@@ -42,12 +43,33 @@ export function sync(m, dry) {
|
|||||||
|
|
||||||
let snap = net.snapshot(true);
|
let snap = net.snapshot(true);
|
||||||
let portal_zone = null, want_loop = false;
|
let portal_zone = null, want_loop = false;
|
||||||
|
// Where tunnel DNS is sent (dawnline.nft): into the netns for home names
|
||||||
|
// while any server runs "like a home device", and to the LAN's DNS for
|
||||||
|
// everyone else. A server that does not forward to those zones on its own
|
||||||
|
// gets a rule for port 53 alone.
|
||||||
|
let any_loop = length(filter(values(m.servers), (s) => s.lan_like && length(core.tunnels(s)))) > 0;
|
||||||
|
let lan_dns = loop.lan_dns();
|
||||||
|
let lan_dns_zone = null;
|
||||||
|
if (lan_dns)
|
||||||
|
for (let dev, d in snap.devices)
|
||||||
|
if (d.zone && in_nets(lan_dns, d.nets ?? []))
|
||||||
|
lan_dns_zone ??= d.zone;
|
||||||
for (let id, srv in m.servers) {
|
for (let id, srv in m.servers) {
|
||||||
if (!length(core.tunnels(srv)))
|
if (!length(core.tunnels(srv)))
|
||||||
continue;
|
continue;
|
||||||
let z = `dawnline_${id}`;
|
let z = `dawnline_${id}`;
|
||||||
let sn = net.server_net(srv, snap);
|
let sn = net.server_net(srv, snap);
|
||||||
portal_zone ??= sn.wan.zone;
|
portal_zone ??= sn.wan.zone;
|
||||||
|
if (!srv.lan_like && any_loop)
|
||||||
|
sec(`${z}_loopdns`, 'rule', {
|
||||||
|
name: `Dawnline-${srv.ifname}-names`, src: srv.ifname, dest: LOOP_ZONE,
|
||||||
|
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
|
||||||
|
});
|
||||||
|
if (lan_dns_zone && lan_dns_zone != srv.ifname && index(sn.zones, lan_dns_zone) < 0)
|
||||||
|
sec(`${z}_landns`, 'rule', {
|
||||||
|
name: `Dawnline-${srv.ifname}-dns`, src: srv.ifname, dest: lan_dns_zone, dest_ip: lan_dns,
|
||||||
|
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
|
||||||
|
});
|
||||||
sec(`${z}_zone`, 'zone', {
|
sec(`${z}_zone`, 'zone', {
|
||||||
// Forward within the zone (device to device) is decided by the inet dawnline table.
|
// Forward within the zone (device to device) is decided by the inet dawnline table.
|
||||||
name: srv.ifname, network: [ srv.ifname ],
|
name: srv.ifname, network: [ srv.ifname ],
|
||||||
|
|||||||
@@ -1,14 +1,21 @@
|
|||||||
// Dawnline — city-level locations for the admin map.
|
// Dawnline — city-level locations for the admin map.
|
||||||
//
|
//
|
||||||
// Client addresses are looked up once with a third-party service (ipwho.is,
|
// Client addresses are looked up once with a third-party service (ipwho.is,
|
||||||
// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent
|
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
|
||||||
// performs lookups, a few per minute at most; the UI reads the cache.
|
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
|
||||||
|
// counters. Only the agent performs lookups, in a child process (the network
|
||||||
|
// may take seconds; neither its watcher nor its tick waits for them) and
|
||||||
|
// merges them into the cache itself; the UI reads the cache.
|
||||||
|
|
||||||
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util';
|
import { stat } from 'fs';
|
||||||
|
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
|
||||||
|
|
||||||
const CACHE = `${DATA_DIR}/geo.json`;
|
const CACHE = `${RUN_DIR}/geo.json`;
|
||||||
|
const SAVED = `${DATA_DIR}/geo.json`;
|
||||||
const TTL = 30 * 86400;
|
const TTL = 30 * 86400;
|
||||||
const RETRY = 86400;
|
const RETRY = 86400;
|
||||||
|
// Entries kept at least; addresses still shown are never pushed out (merge).
|
||||||
|
const CAP = 500;
|
||||||
|
|
||||||
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
||||||
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
|
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
|
||||||
@@ -30,16 +37,30 @@ export function is_public(ip) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export function load() {
|
export function load() {
|
||||||
return read_json(CACHE, null) ?? { ips: {}, home: null };
|
return read_json(CACHE, null) ?? read_json(SAVED, null) ?? { ips: {}, home: null };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The live copy (tmpfs); flush() puts it on flash. */
|
||||||
export function save(cache) {
|
export function save(cache) {
|
||||||
ensure_dir(DATA_DIR, 0o700);
|
ensure_dir(RUN_DIR);
|
||||||
write_json(CACHE, cache, 0o600);
|
write_json(CACHE, cache, 0o600);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Copy the live cache to flash when it is newer (the agent, about hourly and on a clean stop). */
|
||||||
|
export function flush() {
|
||||||
|
let live = stat(CACHE);
|
||||||
|
if (!live || live.mtime <= (stat(SAVED)?.mtime ?? 0))
|
||||||
|
return false;
|
||||||
|
let c = read_json(CACHE, null);
|
||||||
|
if (!c)
|
||||||
|
return false;
|
||||||
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
write_json(SAVED, c, 0o600);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
function fetch_json(url) {
|
function fetch_json(url) {
|
||||||
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`);
|
let out = sh_out(`uclient-fetch -q -T 5 -O - ${q(url)}`);
|
||||||
if (!out)
|
if (!out)
|
||||||
return null;
|
return null;
|
||||||
try {
|
try {
|
||||||
@@ -79,36 +100,69 @@ export function lookup(provider, ip) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve up to `max` addresses that are missing or stale. Returns true when
|
* The public addresses of `ips` the cache does not know or knows from too
|
||||||
* the cache changed (the caller saves it).
|
* long ago (a failed lookup is retried after a day), once each and in order.
|
||||||
|
* Returns an empty array when there is nothing to look up.
|
||||||
*/
|
*/
|
||||||
export function resolve(settings, cache, ips, max) {
|
export function stale(cache, ips, ts) {
|
||||||
let now = time(), changed = false, done = 0;
|
let now = ts ?? time(), out = [], seen = {};
|
||||||
for (let ip in ips) {
|
for (let ip in ips) {
|
||||||
if (done >= max)
|
if (seen[ip] || !is_public(ip))
|
||||||
break;
|
|
||||||
if (!is_public(ip))
|
|
||||||
continue;
|
continue;
|
||||||
|
seen[ip] = true;
|
||||||
let c = cache.ips[ip];
|
let c = cache.ips[ip];
|
||||||
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
||||||
continue;
|
continue;
|
||||||
let r = lookup(settings.geo_provider, ip);
|
push(out, ip);
|
||||||
done++;
|
|
||||||
changed = true;
|
|
||||||
if (r) {
|
|
||||||
delete r.ip;
|
|
||||||
r.ts = now;
|
|
||||||
cache.ips[ip] = r;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
cache.ips[ip] = { fail: now };
|
|
||||||
}
|
}
|
||||||
// Keep the cache bounded: drop the oldest entries beyond 500.
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
|
||||||
|
* wait on the network). Returns { ip: place, or false when the services had
|
||||||
|
* nothing } for the ones tried. Network only, no cache: the agent runs it in
|
||||||
|
* a child process and merges the result itself.
|
||||||
|
*/
|
||||||
|
export function lookup_all(provider, ips, max, budget) {
|
||||||
|
let started = time(), out = {}, done = 0;
|
||||||
|
for (let ip in ips) {
|
||||||
|
if (done >= max || (budget != null && time() - started >= budget))
|
||||||
|
break;
|
||||||
|
let r = lookup(provider, ip);
|
||||||
|
done++;
|
||||||
|
if (r)
|
||||||
|
delete r.ip;
|
||||||
|
out[ip] = r ?? false;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Put lookup_all() results into the cache. Returns true when the cache
|
||||||
|
* changed (the caller saves it). `shown` is what is still on the map: the
|
||||||
|
* cache is kept bounded by dropping other entries only, oldest first, so a
|
||||||
|
* lookup is never repeated for an address that is still on the map.
|
||||||
|
*/
|
||||||
|
export function merge(cache, found, shown, ts) {
|
||||||
|
let now = ts ?? time(), changed = false;
|
||||||
|
for (let ip, r in found) {
|
||||||
|
if (!is_public(ip))
|
||||||
|
continue;
|
||||||
|
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
let keep = {};
|
||||||
|
for (let ip in shown)
|
||||||
|
keep[ip] = true;
|
||||||
let all = keys(cache.ips);
|
let all = keys(cache.ips);
|
||||||
if (length(all) > 500) {
|
if (length(all) > CAP) {
|
||||||
all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
let other = sort(filter(all, (ip) => !keep[ip]),
|
||||||
for (let i = 0; i < length(all) - 500; i++)
|
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
||||||
delete cache.ips[all[i]];
|
for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
|
||||||
|
delete cache.ips[other[i]];
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return changed;
|
return changed;
|
||||||
};
|
};
|
||||||
@@ -130,6 +184,13 @@ export function place(cache, ip) {
|
|||||||
return (c && !c.fail) ? c : null;
|
return (c && !c.fail) ? c : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** "City · ISP" for the activity log; null for no place. */
|
||||||
|
export function label(pl) {
|
||||||
|
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
||||||
|
};
|
||||||
|
|
||||||
export function clear() {
|
export function clear() {
|
||||||
save({ ips: {}, home: null });
|
save({ ips: {}, home: null });
|
||||||
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
write_json(SAVED, { ips: {}, home: null }, 0o600);
|
||||||
};
|
};
|
||||||
@@ -11,6 +11,7 @@ import * as fw from 'dawnline.fw';
|
|||||||
import * as loop from 'dawnline.loop';
|
import * as loop from 'dawnline.loop';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
|
import * as builds from 'dawnline.awg_builds';
|
||||||
import * as lookup from 'dawnline.lookup';
|
import * as lookup from 'dawnline.lookup';
|
||||||
import * as pc from 'dawnline.portalcert';
|
import * as pc from 'dawnline.portalcert';
|
||||||
|
|
||||||
@@ -42,12 +43,51 @@ export function needs() {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export function udp_listening(port) {
|
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
|
||||||
let hex = sprintf(':%04X ', port);
|
export function udp_bound() {
|
||||||
|
let out = {};
|
||||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||||
if (index(readfile(f) ?? '', hex) >= 0)
|
for (let line in split(readfile(f) ?? '', '\n')) {
|
||||||
return true;
|
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
|
||||||
return false;
|
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
|
||||||
|
if (m)
|
||||||
|
out[hex(m[1])] = true;
|
||||||
|
}
|
||||||
|
return map(keys(out), (k) => +k);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
|
||||||
|
* Kernel sockets (a tunnel's) have no name.
|
||||||
|
*/
|
||||||
|
function port_programs(proto) {
|
||||||
|
let out = {};
|
||||||
|
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
|
||||||
|
let f = split(trim(line), /[ \t]+/);
|
||||||
|
if (f[0] != proto && f[0] != `${proto}6`)
|
||||||
|
continue;
|
||||||
|
let m = match(f[3] ?? '', /:([0-9]+)$/);
|
||||||
|
let owner = split(f[length(f) - 1], '/');
|
||||||
|
if (!m || !owner[1] || out[m[1]])
|
||||||
|
continue;
|
||||||
|
// Our own portal runs as a dedicated uhttpd instance.
|
||||||
|
if (index(readfile(`/proc/${+owner[0]}/cmdline`) ?? '', '/usr/share/dawnline/portal') >= 0)
|
||||||
|
continue;
|
||||||
|
out[m[1]] = owner[1];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function udp_port_programs() {
|
||||||
|
return port_programs('udp');
|
||||||
|
};
|
||||||
|
|
||||||
|
export function tcp_port_programs() {
|
||||||
|
return port_programs('tcp');
|
||||||
|
};
|
||||||
|
|
||||||
|
export function udp_listening(port) {
|
||||||
|
return index(udp_bound(), +port) >= 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function tcp_listening(port) {
|
export function tcp_listening(port) {
|
||||||
@@ -116,6 +156,11 @@ function other_subnets(srv_id) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** Subnets in use on the router except the given server's (null: all of them). */
|
/** Subnets in use on the router except the given server's (null: all of them). */
|
||||||
|
/** The router's IPv4 networks, Dawnline's tunnels included: [{ iface, cidr }]. */
|
||||||
|
export function networks() {
|
||||||
|
return other_subnets(null);
|
||||||
|
};
|
||||||
|
|
||||||
export function used_subnets(except_srv) {
|
export function used_subnets(except_srv) {
|
||||||
return map(other_subnets(except_srv), (x) => x.cidr);
|
return map(other_subnets(except_srv), (x) => x.cidr);
|
||||||
};
|
};
|
||||||
@@ -188,35 +233,104 @@ function reply_check(id, title, proto, port, r) {
|
|||||||
|
|
||||||
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
||||||
|
|
||||||
|
/** What kind of IPv4 the WAN has: public, cgnat (100.64/10), private (behind another router), or none. */
|
||||||
|
export function wan_kind(wan) {
|
||||||
|
let wc = wan ? ip2int(wan) : null;
|
||||||
|
if (wc == null)
|
||||||
|
return 'none';
|
||||||
|
if (in_cidr(wc, PRIVATE[0]))
|
||||||
|
return 'cgnat';
|
||||||
|
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a public address points at, for Health and the "as you type" check on
|
||||||
|
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
|
||||||
|
* here (an IPv4 of it is this router's WAN), v6_only }.
|
||||||
|
*/
|
||||||
|
export function endpoint_facts(srv, host) {
|
||||||
|
let ips = host ? lookup.resolve(host) : [];
|
||||||
|
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
|
||||||
|
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
|
||||||
|
return {
|
||||||
|
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
|
||||||
|
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
|
||||||
|
here: wan != null && index(ips4, wan) >= 0,
|
||||||
|
v6_only: !length(ips4) && length(ips6) > 0,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The facts in words: { status: ok|warn|error, text }. `proto_note` names what must get through ("UDP 4500"). */
|
||||||
|
export function endpoint_words(f, proto_note) {
|
||||||
|
if (!f.host)
|
||||||
|
return { status: 'error', text: 'No public address: devices will not know where to connect.' };
|
||||||
|
if (!length(f.ips))
|
||||||
|
return { status: 'error', text: `${f.host} does not resolve.` };
|
||||||
|
if (f.cloudflare)
|
||||||
|
return { status: 'error', text: `${f.host} → ${join(', ', f.ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.` };
|
||||||
|
if (f.v6_only)
|
||||||
|
return { status: f.kind == 'public' ? 'warn' : 'ok', text: `${f.host} → ${join(', ', f.ips6)}: IPv6 only, so only devices with IPv6 connect${f.kind == 'public' ? ` (the router's IPv4 ${f.wan} has no name)` : ''}.` };
|
||||||
|
if (f.kind == 'cgnat' || f.kind == 'private')
|
||||||
|
return { status: 'warn', text: f.kind == 'cgnat'
|
||||||
|
? `The WAN address ${f.wan} is CGNAT (shared by the ISP): ${proto_note} cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.`
|
||||||
|
: `The WAN address ${f.wan} is private: this router is behind another one. Forward ${proto_note} on it, or devices cannot connect.` };
|
||||||
|
if (f.wan && !f.here)
|
||||||
|
return { status: 'warn', text: `${f.host} points at ${join(', ', f.ips4)}, not this router (WAN ${f.wan}). Check your DNS / DDNS.` };
|
||||||
|
return { status: 'ok', text: f.here ? `${f.host} points at this router (${f.wan}).` : `${f.host} → ${join(', ', f.ips)}` };
|
||||||
|
};
|
||||||
|
|
||||||
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
|
/** 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) {
|
function endpoint_check(id, title, srv, host, proto_note) {
|
||||||
if (!host)
|
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
|
||||||
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
|
return check(id, title, w.status, w.text);
|
||||||
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;
|
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
|
||||||
if (!length(ips))
|
* Dawnline's (pref < 5205) whose table has a default route of its own sends
|
||||||
return check(id, title, 'error', `${host} does not resolve.`);
|
* marked tunnel traffic straight out, past "like a home device". Reported,
|
||||||
if (cgnat)
|
* since those marks belong to that package. [] when none.
|
||||||
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))))
|
function policy_routing() {
|
||||||
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.`);
|
let out = [];
|
||||||
if (wan && index(ips, wan) < 0)
|
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||||
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`);
|
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
|
||||||
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`);
|
if (!mm || +mm[1] >= 5205)
|
||||||
|
continue;
|
||||||
|
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
|
||||||
|
let def = match(routes, /(^|\n)default [^\n]*/)?.[0] ?? '';
|
||||||
|
if (def == '' || match(def, /local default/) || index(def, `dev ${net.INTERNAL.transit}`) >= 0)
|
||||||
|
continue;
|
||||||
|
push(out, `pref ${mm[1]} fwmark 0x${mm[2]} → table ${mm[4]}`);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
|
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
|
||||||
|
|
||||||
|
/** Free space on the overlay in KB (null when unknown). */
|
||||||
|
function overlay_free_kb() {
|
||||||
|
let out = sh('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
|
||||||
|
let m = match(out ?? '', /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
|
||||||
|
return m ? +m[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
|
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
|
||||||
function awg_check() {
|
function awg_check() {
|
||||||
let st = awg.state();
|
let st = awg.load();
|
||||||
let title = 'AmneziaWG installed';
|
let title = 'AmneziaWG installed';
|
||||||
if (length(st.missing ?? []))
|
if (length(st.missing ?? [])) {
|
||||||
|
// The module was built for the kernel of the firmware it was installed on.
|
||||||
|
let kc = builds.kernel_changed();
|
||||||
|
if (kc && index(st.missing, 'kmod-amneziawg') >= 0)
|
||||||
|
return check('awg', title, 'error',
|
||||||
|
`The firmware changed (kernel ${kc.was} → ${kc.now}): the AmneziaWG build installed for it is gone. Install the build for this firmware.`,
|
||||||
|
'install:awg', 'AmneziaWG needs a build for the new firmware');
|
||||||
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
|
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
|
||||||
'AmneziaWG isn’t installed');
|
'AmneziaWG isn’t installed');
|
||||||
|
}
|
||||||
if (!st.loaded) {
|
if (!st.loaded) {
|
||||||
|
// load() tried it: the second modprobe only repeats why.
|
||||||
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
|
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
|
||||||
return check('awg', title, 'error',
|
return check('awg', title, 'error',
|
||||||
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
|
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
|
||||||
@@ -241,19 +355,30 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
|||||||
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
|
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
|
||||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
||||||
if (up) {
|
if (up) {
|
||||||
let expected = 0;
|
// By key, not by count: a stale peer standing in for a missing one would
|
||||||
|
// make the numbers match.
|
||||||
let states = apply.states_for(m, core.load_usage());
|
let states = apply.states_for(m, core.load_usage());
|
||||||
|
let wanted = {}, expected = 0;
|
||||||
for (let did, d in m.devices) {
|
for (let did, d in m.devices) {
|
||||||
let p = m.people[d.person];
|
let p = m.people[d.person];
|
||||||
if (p?.server == id && !d.disabled && states[d.person] == 'active')
|
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
|
||||||
|
wanted[d.public_key] = true;
|
||||||
expected++;
|
expected++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let actual = 0;
|
let loaded = {}, actual = 0;
|
||||||
for (let k, p in dmp.peers)
|
for (let k, p in dmp.peers)
|
||||||
if (p.ifname == srv.ifname)
|
if (p.ifname == srv.ifname) {
|
||||||
|
loaded[k] = true;
|
||||||
actual++;
|
actual++;
|
||||||
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn',
|
}
|
||||||
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
|
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
|
||||||
|
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
|
||||||
|
let same = !missing && !extra;
|
||||||
|
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, same ? 'ok' : 'warn',
|
||||||
|
same ? `${actual} device${actual == 1 ? ' is' : 's are'} loaded in the tunnel.` :
|
||||||
|
`${missing} of ${expected} device${expected == 1 ? '' : 's'} missing${extra ? `, ${extra} loaded that should not be` : ''}.`,
|
||||||
|
same ? null : 'sync'));
|
||||||
}
|
}
|
||||||
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
||||||
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
||||||
@@ -351,6 +476,15 @@ export function health(m) {
|
|||||||
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
|
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
|
||||||
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart'));
|
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart'));
|
||||||
|
|
||||||
|
// A full overlay fails every config write on the router, Dawnline's and
|
||||||
|
// OpenWrt's own; backups and history are what Dawnline adds to it.
|
||||||
|
let free = overlay_free_kb();
|
||||||
|
if (free != null)
|
||||||
|
push(out, check('flash', 'Free space on the router', free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
|
||||||
|
free < 2048 ? `${int(free / 1024 * 10) / 10} MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.`
|
||||||
|
: `${int(free / 1024)} MB free on the overlay.`,
|
||||||
|
null, 'The router is running out of flash'));
|
||||||
|
|
||||||
if (!length(m.servers)) {
|
if (!length(m.servers)) {
|
||||||
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
|
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
|
||||||
return out;
|
return out;
|
||||||
@@ -358,9 +492,24 @@ export function health(m) {
|
|||||||
|
|
||||||
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
|
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',
|
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
|
||||||
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
|
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.'
|
||||||
|
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.',
|
||||||
nft_ok ? null : 'apply'));
|
nft_ok ? null : 'apply'));
|
||||||
|
|
||||||
|
if (length(filter(values(m.servers), (s) => s.lan_like && s.enabled))) {
|
||||||
|
let pr = policy_routing();
|
||||||
|
push(out, check('policy', 'Internet like a home device not bypassed', length(pr) ? 'warn' : 'ok',
|
||||||
|
length(pr) ? `Policy routing on the router (${join('; ', pr)}) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters.`
|
||||||
|
: 'No other policy routing ahead of the tunnel rules.',
|
||||||
|
null, 'Other policy routing bypasses the home-device path'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A device the sync has to leave out (a merged import, a hand-edited config).
|
||||||
|
let data = core.model_errors(m);
|
||||||
|
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok',
|
||||||
|
length(data) ? `${join(' ', slice(data, 0, 4))}${length(data) > 4 ? ` (${length(data) - 4} more)` : ''} Such devices are left out of the tunnels: fix or remove them.`
|
||||||
|
: 'Every device has a key and an address of its own inside its server.'));
|
||||||
|
|
||||||
let fwc = cursor();
|
let fwc = cursor();
|
||||||
fwc.load('firewall');
|
fwc.load('firewall');
|
||||||
|
|
||||||
@@ -385,10 +534,16 @@ export function health(m) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (length(filter(values(m.servers), (x) => x.private_key))) {
|
// While every server is off the resolver only idles on loopback: nothing to check.
|
||||||
|
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key))) {
|
||||||
let rt = loop.resolver_target();
|
let rt = loop.resolver_target();
|
||||||
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
|
let conf = stat(loop.RESOLVER.conf);
|
||||||
|
let running = conf != null && loop.resolver_running();
|
||||||
|
// A new config (a server turned on, the home link up) restarts it: give it a few seconds.
|
||||||
|
let restarting = !running && conf != null && time() - conf.mtime < 10;
|
||||||
|
let ok = running || restarting;
|
||||||
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
|
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
|
||||||
|
restarting ? 'Restarting with the new settings.' :
|
||||||
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
|
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'));
|
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
|
||||||
}
|
}
|
||||||
@@ -414,6 +569,10 @@ export function fix(id) {
|
|||||||
}
|
}
|
||||||
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
|
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
|
||||||
if (m) {
|
if (m) {
|
||||||
|
// Only Dawnline's own tunnels: never another interface of the router.
|
||||||
|
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
|
||||||
|
if (!length(mine))
|
||||||
|
die(`${m[1]} is not one of Dawnline's tunnels.`);
|
||||||
system(`ifup ${q(m[1])}`);
|
system(`ifup ${q(m[1])}`);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,14 +11,14 @@ import {
|
|||||||
iface_status as util_iface_status, RUN_DIR, DATA_DIR
|
iface_status as util_iface_status, RUN_DIR, DATA_DIR
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
|
import * as schema from 'dawnline.schema';
|
||||||
|
|
||||||
// Online while the WireGuard session lives: it is dropped 180 s after its
|
// 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
|
// 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.
|
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
|
||||||
export const ONLINE_WINDOW = 190;
|
export const ONLINE_WINDOW = 190;
|
||||||
const KEEP_DAYS = 62;
|
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
|
||||||
const KEEP_MONTHS = 24;
|
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
|
||||||
const KEEP_EVENTS = 2000;
|
|
||||||
|
|
||||||
/* ---------- retention policy ---------- */
|
/* ---------- retention policy ---------- */
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ export const CATEGORY = {
|
|||||||
device_added: 'people', device_removed: 'people', devices_removed: 'people',
|
device_added: 'people', device_removed: 'people', devices_removed: 'people',
|
||||||
device_changed: 'people', device_keys: 'people', link_changed: 'people',
|
device_changed: 'people', device_keys: 'people', link_changed: 'people',
|
||||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||||
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people',
|
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
|
||||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||||
};
|
};
|
||||||
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
||||||
@@ -38,9 +38,6 @@ export function category_of(type) {
|
|||||||
return CATEGORY[type] ?? 'problems';
|
return CATEGORY[type] ?? 'problems';
|
||||||
};
|
};
|
||||||
|
|
||||||
function int_or(v, d) {
|
|
||||||
return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Log and history retention from /etc/config/dawnline (read fresh, the
|
* Log and history retention from /etc/config/dawnline (read fresh, the
|
||||||
@@ -62,13 +59,14 @@ export function policy(s) {
|
|||||||
else if (type(cats) != 'array')
|
else if (type(cats) != 'array')
|
||||||
cats = split(cats, /[ ,]+/);
|
cats = split(cats, /[ ,]+/);
|
||||||
cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
|
cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
|
||||||
|
// Defaults and ranges come from dawnline.schema, like every other setting.
|
||||||
return {
|
return {
|
||||||
keep_days: int_or(s.log_keep_days, 30),
|
keep_days: schema.get(s, 'log_keep_days'),
|
||||||
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000),
|
max: schema.get(s, 'log_max'),
|
||||||
categories: cats,
|
categories: cats,
|
||||||
persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly',
|
persist: schema.get(s, 'log_persist'),
|
||||||
usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830),
|
usage_days: schema.get(s, 'usage_keep_days'),
|
||||||
usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120),
|
usage_months: schema.get(s, 'usage_keep_months'),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -110,7 +108,10 @@ export function presence() {
|
|||||||
* handshake, rx, tx } }, presence }. See dawnline.awg.
|
* handshake, rx, tx } }, presence }. See dawnline.awg.
|
||||||
*/
|
*/
|
||||||
export function dump(m) {
|
export function dump(m) {
|
||||||
let d = awg.dump();
|
// Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on
|
||||||
|
// the router that cannot be read is not our trouble.
|
||||||
|
let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null;
|
||||||
|
let d = awg.dump(mine);
|
||||||
d.presence = presence();
|
d.presence = presence();
|
||||||
return d;
|
return d;
|
||||||
};
|
};
|
||||||
@@ -134,8 +135,13 @@ function empty_usage() {
|
|||||||
return { devices: {}, people: {}, updated: 0, flushed: 0 };
|
return { devices: {}, people: {}, updated: 0, flushed: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function load_usage() {
|
/**
|
||||||
let u = read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
* The usage counters: the live copy in RUN_DIR, else what flash holds. With
|
||||||
|
* `from_flash` only flash counts (a restore put new counters there, and the
|
||||||
|
* watcher may have written the old live ones again since).
|
||||||
|
*/
|
||||||
|
export function load_usage(from_flash) {
|
||||||
|
let u = (from_flash ? null : read_json(`${RUN_DIR}/usage.json`, null)) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
|
||||||
// Per-app counters of earlier test builds are not kept.
|
// Per-app counters of earlier test builds are not kept.
|
||||||
delete u.clients;
|
delete u.clients;
|
||||||
return u;
|
return u;
|
||||||
@@ -389,6 +395,35 @@ export function add_event_merged(e, window) {
|
|||||||
unlock(l);
|
unlock(l);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Places for connections logged before their address was located (the
|
||||||
|
* lookup finishes after the event): connect events since `since` from an
|
||||||
|
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
|
||||||
|
* Returns true when `ev` changed.
|
||||||
|
*/
|
||||||
|
export function fill_places(ev, where, since) {
|
||||||
|
let changed = false;
|
||||||
|
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
|
||||||
|
let e = ev[i];
|
||||||
|
if (e.type == 'connect' && !e.where && where[e.detail]) {
|
||||||
|
e.where = where[e.detail];
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** fill_places() on the live log, written only when something changed. */
|
||||||
|
export function set_places(where, since) {
|
||||||
|
let l = lock('events');
|
||||||
|
let ev = load_events();
|
||||||
|
if (fill_places(ev, where, since)) {
|
||||||
|
ensure_dir(RUN_DIR);
|
||||||
|
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||||
|
}
|
||||||
|
unlock(l);
|
||||||
|
};
|
||||||
|
|
||||||
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
||||||
export function persist_events(pol) {
|
export function persist_events(pol) {
|
||||||
pol ??= policy();
|
pol ??= policy();
|
||||||
@@ -397,6 +432,10 @@ export function persist_events(pol) {
|
|||||||
unlink(`${DATA_DIR}/events.json`);
|
unlink(`${DATA_DIR}/events.json`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Only when something was logged since the last copy: flash is written rarely.
|
||||||
|
let live_st = stat(`${RUN_DIR}/events.json`);
|
||||||
|
if (!live_st || live_st.mtime <= (stat(`${DATA_DIR}/events.json`)?.mtime ?? 0))
|
||||||
|
return;
|
||||||
let ev = read_json(`${RUN_DIR}/events.json`, null);
|
let ev = read_json(`${RUN_DIR}/events.json`, null);
|
||||||
if (ev != null) {
|
if (ev != null) {
|
||||||
ensure_dir(DATA_DIR, 0o700);
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// time, so a slow DNS server must not hold up the whole admin UI.
|
// time, so a slow DNS server must not hold up the whole admin UI.
|
||||||
|
|
||||||
import { readfile } from 'fs';
|
import { readfile } from 'fs';
|
||||||
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util';
|
import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
|
|
||||||
@@ -23,9 +23,10 @@ function valid_name(h) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not
|
* Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
|
||||||
* resolve). IP addresses map to themselves. Every uncached name is asked of
|
* does not resolve). IP addresses map to themselves. Every uncached name is
|
||||||
* every server at once; the first server (in SERVERS order) that answers wins.
|
* asked of every server at once, A and AAAA; the first server (in SERVERS
|
||||||
|
* order) that answers wins.
|
||||||
*/
|
*/
|
||||||
export function resolve_all(hosts) {
|
export function resolve_all(hosts) {
|
||||||
let out = {}, now = time(), todo = [];
|
let out = {}, now = time(), todo = [];
|
||||||
@@ -33,7 +34,7 @@ export function resolve_all(hosts) {
|
|||||||
for (let h in hosts) {
|
for (let h in hosts) {
|
||||||
if (h == null || out[h] != null)
|
if (h == null || out[h] != null)
|
||||||
continue;
|
continue;
|
||||||
if (ip2int(h) != null) {
|
if (ip2int(h) != null || is_ip6(h)) {
|
||||||
out[h] = [ h ];
|
out[h] = [ h ];
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -55,14 +56,17 @@ export function resolve_all(hosts) {
|
|||||||
let cmds = [];
|
let cmds = [];
|
||||||
for (let i = 0; i < length(todo); i++)
|
for (let i = 0; i < length(todo); i++)
|
||||||
for (let j = 0; j < length(SERVERS); j++)
|
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} ) &`);
|
for (let t in [ 'a', 'aaaa' ])
|
||||||
|
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
|
||||||
|
push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
|
||||||
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
|
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
|
||||||
for (let i = 0; i < length(todo); i++) {
|
for (let i = 0; i < length(todo); i++) {
|
||||||
let ips = [];
|
let ips = [];
|
||||||
for (let j = 0; j < length(SERVERS) && !length(ips); j++) {
|
for (let j = 0; j < length(SERVERS) && !length(ips); j++)
|
||||||
let r = readfile(`${dir}/${i}.${j}`) ?? '';
|
for (let t in [ 'a', 'aaaa' ]) {
|
||||||
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null);
|
let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
|
||||||
}
|
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
|
||||||
|
}
|
||||||
out[todo[i]] = ips;
|
out[todo[i]] = ips;
|
||||||
cache[todo[i]] = { ts: now, ips };
|
cache[todo[i]] = { ts: now, ips };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,8 +57,57 @@ export function uhttpd() {
|
|||||||
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
|
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The portal names itself after the server now (the breadcrumb, the tab): its own title setting is gone. */
|
||||||
|
function portal_title() {
|
||||||
|
let c = cursor();
|
||||||
|
c.load('dawnline');
|
||||||
|
if (c.get('dawnline', 'settings', 'portal_title') != null)
|
||||||
|
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_title'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Steps that cannot tell from the config whether they ran are recorded in
|
||||||
|
* `settings.migrated` (a list), so they run exactly once.
|
||||||
|
*/
|
||||||
|
function migrated(c, name) {
|
||||||
|
let done = c.get('dawnline', 'settings', 'migrated') ?? [];
|
||||||
|
return index(type(done) == 'array' ? done : [ done ], name) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mark_migrated(w, name) {
|
||||||
|
let done = w.get('dawnline', 'settings', 'migrated') ?? [];
|
||||||
|
w.set('dawnline', 'settings', 'migrated', [ ...(type(done) == 'array' ? done : [ done ]), name ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 1380 was every server's stored MTU before it became automatic (by device
|
||||||
|
* type and disguise). Once only: an admin may choose 1380 again on purpose.
|
||||||
|
*/
|
||||||
|
function auto_mtu() {
|
||||||
|
let c = cursor();
|
||||||
|
c.load('dawnline');
|
||||||
|
if (migrated(c, 'auto_mtu'))
|
||||||
|
return;
|
||||||
|
let any = false;
|
||||||
|
c.foreach('dawnline', 'server', (s) => {
|
||||||
|
if (s.mtu == '1380')
|
||||||
|
any = true;
|
||||||
|
});
|
||||||
|
store.transact((w, m) => {
|
||||||
|
w.foreach('dawnline', 'server', (s) => {
|
||||||
|
if (s.mtu == '1380')
|
||||||
|
w.delete('dawnline', s['.name'], 'mtu');
|
||||||
|
});
|
||||||
|
mark_migrated(w, 'auto_mtu');
|
||||||
|
});
|
||||||
|
if (any)
|
||||||
|
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers');
|
||||||
|
}
|
||||||
|
|
||||||
/** All of them, in order. */
|
/** All of them, in order. */
|
||||||
export function run() {
|
export function run() {
|
||||||
word_codes();
|
word_codes();
|
||||||
uhttpd();
|
uhttpd();
|
||||||
|
auto_mtu();
|
||||||
|
portal_title();
|
||||||
};
|
};
|
||||||
@@ -9,8 +9,8 @@
|
|||||||
// lan_device extra interfaces that count as the home network (list)
|
// lan_device extra interfaces that count as the home network (list)
|
||||||
//
|
//
|
||||||
// Home access is enforced by destination: the networks routed out of the
|
// Home access is enforced by destination: the networks routed out of the
|
||||||
// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall
|
// chosen interfaces form the server's nft `home_<id>` set, and the tunnel's
|
||||||
// zone gets a forwarding to each of their zones.
|
// firewall zone gets a forwarding to each of their zones.
|
||||||
|
|
||||||
import { readfile, readlink, lsdir, stat } from 'fs';
|
import { readfile, readlink, lsdir, stat } from 'fs';
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
|
|||||||
@@ -68,6 +68,15 @@ export function sync(m) {
|
|||||||
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
|
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// A disguise this build cannot run (a 3.1 preset after a rollback to
|
||||||
|
// 2.0): the kernel would drop those options silently and run a tunnel
|
||||||
|
// no device can reach. Down, and said so, until the build or the
|
||||||
|
// disguise is changed.
|
||||||
|
let why = tools ? awg.obf_unsupported(srv.obf) : null;
|
||||||
|
if (why) {
|
||||||
|
block(srv, `is kept down: ${why}`, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
delete srv.blocked;
|
delete srv.blocked;
|
||||||
want[ifn] = true;
|
want[ifn] = true;
|
||||||
if (!tools)
|
if (!tools)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
// changes often (update, one atomic transaction).
|
// changes often (update, one atomic transaction).
|
||||||
|
|
||||||
import { unlink } from 'fs';
|
import { unlink } from 'fs';
|
||||||
import { sh, ensure_dir, write_file, rand_hex, ip2int, RUN_DIR } from 'dawnline.util';
|
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
import * as loop from 'dawnline.loop';
|
import * as loop from 'dawnline.loop';
|
||||||
@@ -74,17 +74,33 @@ export function access_sets(m, usage, states) {
|
|||||||
return sets;
|
return sets;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Duplicate members (two devices with one address) would make the whole load fail.
|
||||||
function set_elems(arr) {
|
function set_elems(arr) {
|
||||||
|
arr = uniq(arr);
|
||||||
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The portal's TCP ports people may reach through the tunnel (never SSH, DNS or LuCI, whatever is stored). */
|
||||||
|
function portal_ports(m) {
|
||||||
|
if (!m.settings.portal_enabled)
|
||||||
|
return [];
|
||||||
|
let ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
|
||||||
|
let ports = filter([ m.settings.portal_port ], ok);
|
||||||
|
if (core.portal_http(m) && ok(core.portal_http_port(m)))
|
||||||
|
push(ports, core.portal_http_port(m));
|
||||||
|
return ports;
|
||||||
|
}
|
||||||
|
|
||||||
function table(m, sets) {
|
function table(m, sets) {
|
||||||
let ifs = [], lan = [], tun = [];
|
let ifs = [], tun = [];
|
||||||
let dns_addr = loop.client_dns();
|
let dns_addr = loop.client_dns();
|
||||||
if (!ip4(dns_addr))
|
if (!ip4(dns_addr))
|
||||||
dns_addr = null;
|
dns_addr = null;
|
||||||
let rt = loop.resolver_target();
|
let rt = loop.resolver_target();
|
||||||
let snap = net.snapshot();
|
let snap = net.snapshot();
|
||||||
|
// Each server's home networks are its own: with several servers, "all
|
||||||
|
// home" on one never reaches the other's networks (set lan_<id>).
|
||||||
|
let homes = {};
|
||||||
for (let id, srv in m.servers) {
|
for (let id, srv in m.servers) {
|
||||||
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
|
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
|
||||||
let tns = core.tunnels(srv);
|
let tns = core.tunnels(srv);
|
||||||
@@ -93,13 +109,13 @@ function table(m, sets) {
|
|||||||
push(tun, t.subnet);
|
push(tun, t.subnet);
|
||||||
}
|
}
|
||||||
if (length(tns))
|
if (length(tns))
|
||||||
push(lan, ...net.server_net(srv, snap).nets);
|
homes[id] = net.collapse(net.server_net(srv, snap).nets);
|
||||||
}
|
}
|
||||||
lan = net.collapse(lan);
|
|
||||||
tun = net.collapse(tun);
|
tun = net.collapse(tun);
|
||||||
let t = [];
|
let t = [];
|
||||||
push(t, 'table inet dawnline {');
|
push(t, 'table inet dawnline {');
|
||||||
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
|
for (let id, nets in homes)
|
||||||
|
push(t, ` set home_${id} { type ipv4_addr; flags interval; auto-merge; ${set_elems(nets)} }`);
|
||||||
// Tunnel subnets are never "home", even inside a wider route to the LAN.
|
// 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 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_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
|
||||||
@@ -118,15 +134,30 @@ function table(m, sets) {
|
|||||||
push(t, ' }');
|
push(t, ' }');
|
||||||
push(t, ' chain guard {');
|
push(t, ' chain guard {');
|
||||||
push(t, ' meta nfproto ipv6 drop');
|
push(t, ' meta nfproto ipv6 drop');
|
||||||
push(t, ' ct state established,related accept');
|
// Every packet is judged by the rules below, not only the first of a
|
||||||
push(t, ' icmp type echo-request fib daddr type local accept');
|
// connection: a change of access cuts open connections too, instead of
|
||||||
|
// letting a session or a long UDP flow run on for days. Only what has no
|
||||||
|
// rule of its own passes on its connection: errors and the like, answers
|
||||||
|
// to the admin's port forwards, and the router's own pings.
|
||||||
|
push(t, ' ct state related accept');
|
||||||
|
push(t, ' ct status dnat accept');
|
||||||
|
push(t, ' icmp type { echo-request, echo-reply } fib daddr type local accept');
|
||||||
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
|
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
|
||||||
push(t, ' fib daddr type local ip saddr @lan_ok accept');
|
let pp = portal_ports(m);
|
||||||
|
if (length(pp))
|
||||||
|
// Their own portal, also with the VPN on (the address may be this router's).
|
||||||
|
push(t, ` fib daddr type local tcp dport { ${join(', ', pp)} } accept`);
|
||||||
|
// The router itself is part of home: for everyone with all of it, and for
|
||||||
|
// people limited to some networks only on the addresses in those.
|
||||||
|
push(t, ' fib daddr type local ip saddr @lan_all accept');
|
||||||
|
push(t, ' fib daddr type local ip saddr . ip daddr @lan_part accept');
|
||||||
push(t, ' fib daddr type local counter drop');
|
push(t, ' fib daddr type local counter drop');
|
||||||
if (dns_addr)
|
if (dns_addr)
|
||||||
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
|
// 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 ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
|
||||||
push(t, ' ip daddr @lan_nets ip daddr != @tun_nets ip saddr @lan_all accept');
|
for (let id, nets in homes)
|
||||||
|
for (let tn in core.tunnels(m.servers[id]))
|
||||||
|
push(t, ` iifname "${tn.ifname}" ip daddr @home_${id} ip daddr != @tun_nets ip saddr @lan_all accept`);
|
||||||
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
|
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
|
// 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
|
// server allows it (everyone, or within circles). Within one server: the
|
||||||
@@ -155,7 +186,9 @@ function table(m, sets) {
|
|||||||
push(t, ' chain to_device {');
|
push(t, ' chain to_device {');
|
||||||
push(t, ' meta nfproto ipv6 drop');
|
push(t, ' meta nfproto ipv6 drop');
|
||||||
push(t, ' ct status dnat accept');
|
push(t, ' ct status dnat accept');
|
||||||
push(t, ' ip saddr @lan_nets ip saddr != @tun_nets ip daddr @lan_all accept');
|
for (let id, nets in homes)
|
||||||
|
for (let tn in core.tunnels(m.servers[id]))
|
||||||
|
push(t, ` oifname "${tn.ifname}" ip saddr @home_${id} ip saddr != @tun_nets ip daddr @lan_all accept`);
|
||||||
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
|
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
|
||||||
push(t, ' counter reject with icmpx admin-prohibited');
|
push(t, ' counter reject with icmpx admin-prohibited');
|
||||||
push(t, ' }');
|
push(t, ' }');
|
||||||
@@ -195,6 +228,11 @@ export function load(script) {
|
|||||||
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. */
|
||||||
|
export function render(m, sets) {
|
||||||
|
return table(m, sets);
|
||||||
|
};
|
||||||
|
|
||||||
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
||||||
export function rebuild(m, sets) {
|
export function rebuild(m, sets) {
|
||||||
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
|
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
|
||||||
@@ -208,9 +246,10 @@ export function rebuild(m, sets) {
|
|||||||
export function update(sets) {
|
export function update(sets) {
|
||||||
let s = '';
|
let s = '';
|
||||||
for (let name in SETS) {
|
for (let name in SETS) {
|
||||||
|
let members = uniq(sets[name]);
|
||||||
s += `flush set inet dawnline ${name}\n`;
|
s += `flush set inet dawnline ${name}\n`;
|
||||||
if (length(sets[name]))
|
if (length(members))
|
||||||
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
|
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
|
||||||
}
|
}
|
||||||
return load(s);
|
return load(s);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
|
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
|
||||||
// callback, which gets their output line by line.
|
// callback, which gets their output line by line.
|
||||||
|
|
||||||
import { access, popen } from 'fs';
|
import { access, popen, stat } from 'fs';
|
||||||
import { q } from 'dawnline.util';
|
import { q } from 'dawnline.util';
|
||||||
|
|
||||||
function run(cmd) {
|
function run(cmd) {
|
||||||
@@ -79,20 +79,56 @@ export function refresh(log) {
|
|||||||
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
|
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Free space on the overlay in KB (null when unknown). */
|
||||||
|
function overlay_free_kb() {
|
||||||
|
let out = run('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
|
||||||
|
let m = match(out, /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
|
||||||
|
return m ? +m[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Room for `files` (or `need_kb` from the feeds): the package manager
|
||||||
|
* unpacks before it removes, so a full flash leaves half an install behind.
|
||||||
|
* Dies with the numbers.
|
||||||
|
*/
|
||||||
|
function preflight(files, need_kb, log) {
|
||||||
|
let free = overlay_free_kb();
|
||||||
|
if (free == null)
|
||||||
|
return;
|
||||||
|
let need = need_kb ?? 512;
|
||||||
|
for (let f in files ?? [])
|
||||||
|
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
|
||||||
|
if (free < need)
|
||||||
|
die(`Not enough free space on the router: ${int(free / 1024)} MB free, about ${int(need / 1024) + 1} MB needed. Remove old backups or packages first`);
|
||||||
|
log?.(` ${int(free / 1024)} MB free on the overlay`);
|
||||||
|
}
|
||||||
|
|
||||||
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
|
/** 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) {
|
export function install_files(files, force, log) {
|
||||||
|
preflight(files, 0, log);
|
||||||
let args = join(' ', map(files, q));
|
let args = join(' ', map(files, q));
|
||||||
return logged(is_apk()
|
if (!is_apk())
|
||||||
? `apk add --allow-untrusted ${args}`
|
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
|
||||||
: `opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
|
// apk leaves an installed version alone, whatever the file: a reinstall
|
||||||
|
// that changed nothing is a failure, not a silent "done".
|
||||||
|
let marker = '/usr/share/ucode/dawnline/util.uc';
|
||||||
|
let before = force ? stat(marker)?.mtime : null;
|
||||||
|
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
|
||||||
|
if (ok && force && before != null && stat(marker)?.mtime == before) {
|
||||||
|
log?.(' apk did not reinstall the version that is already installed');
|
||||||
|
die("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router");
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Packages by name from the feeds. */
|
/** Packages by name from the feeds. */
|
||||||
export function add(names, log) {
|
export function add(names, log) {
|
||||||
|
preflight(null, 2048, log);
|
||||||
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
|
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function upgrade(names, log) {
|
export function upgrade(names, log) {
|
||||||
|
preflight(null, 2048, log);
|
||||||
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
|
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -105,7 +141,9 @@ export function upgradable() {
|
|||||||
let up = {};
|
let up = {};
|
||||||
if (is_apk()) {
|
if (is_apk()) {
|
||||||
for (let line in split(run('apk version -l "<"').out, '\n')) {
|
for (let line in split(run('apk version -l "<"').out, '\n')) {
|
||||||
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
|
// "name-version-rN < newer": the version is what follows the last dash
|
||||||
|
// before the release suffix (a name may hold digits, a version no dash).
|
||||||
|
let m = match(line, /^(\S+)-([^- ]+-r[0-9]+)\s+<\s+(\S+)/);
|
||||||
if (m)
|
if (m)
|
||||||
up[m[1]] = m[3];
|
up[m[1]] = m[3];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,8 +19,14 @@
|
|||||||
// other sites' logs. The portal can only manage the person's own devices
|
// 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).
|
// within their limits, and not those the admin turned off (dawnline.devices).
|
||||||
//
|
//
|
||||||
|
// Changes through a link are limited too (a link is not a terminal: a few
|
||||||
|
// dozen every quarter hour), and the configurations themselves (keys, the
|
||||||
|
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
|
||||||
|
// shows the page, but gets them from its HTTPS twin.
|
||||||
|
//
|
||||||
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
|
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
|
||||||
// CGI script (www/cgi-bin/portal) is its wrapper.
|
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
|
||||||
|
// that answers anything not shaped like a link (its not_found() twin).
|
||||||
|
|
||||||
import { stat, readfile } from 'fs';
|
import { stat, readfile } from 'fs';
|
||||||
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
|
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
|
||||||
@@ -41,6 +47,8 @@ const SHARED_LIMIT = FAIL_LIMIT * 25;
|
|||||||
const SHARED_KEY = 'cloudflare';
|
const SHARED_KEY = 'cloudflare';
|
||||||
// Clients remembered at most (the oldest go first).
|
// Clients remembered at most (the oldest go first).
|
||||||
const RATE_MAX = 2000;
|
const RATE_MAX = 2000;
|
||||||
|
// Changes one link may make within FAIL_WINDOW (each one writes flash and syncs the tunnels).
|
||||||
|
const ACTION_LIMIT = 40;
|
||||||
const BODY_MAX = 8192;
|
const BODY_MAX = 8192;
|
||||||
// The early end of a request (a response was written).
|
// The early end of a request (a response was written).
|
||||||
const DONE = '__dawnline_done__';
|
const DONE = '__dawnline_done__';
|
||||||
@@ -54,6 +62,12 @@ const SECURITY_HEADERS = {
|
|||||||
|
|
||||||
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
|
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
|
||||||
|
|
||||||
|
// States the admin stopped the person in: the portal only shows, it changes nothing.
|
||||||
|
const LOCKED = {
|
||||||
|
paused: 'Your access is paused.',
|
||||||
|
expired: 'Your access has ended.',
|
||||||
|
};
|
||||||
|
|
||||||
function html_escape(s) {
|
function html_escape(s) {
|
||||||
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||||
}
|
}
|
||||||
@@ -210,13 +224,33 @@ function rate_fail(r) {
|
|||||||
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
|
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** One more change through this link; refused beyond ACTION_LIMIT per window. */
|
||||||
|
function rate_action(r) {
|
||||||
|
let key = `act:${r.person.id}`;
|
||||||
|
let l = lock('portal-rate');
|
||||||
|
let st = rate_state();
|
||||||
|
let v = st[key] ?? { first: time(), count: 0 };
|
||||||
|
v.count++;
|
||||||
|
st[key] = v;
|
||||||
|
ensure_dir(RUN_DIR);
|
||||||
|
write_json(RATE, st, 0o600);
|
||||||
|
unlock(l);
|
||||||
|
if (v.count > ACTION_LIMIT)
|
||||||
|
fail(r, '429 Too Many Requests', 'Too many changes in a short time. Try again in a few minutes.');
|
||||||
|
}
|
||||||
|
|
||||||
/* ---------- pages ---------- */
|
/* ---------- pages ---------- */
|
||||||
|
|
||||||
|
/** What the page is called (the tab, the first crumb): the person's server, or Dawnline. */
|
||||||
|
function place(r) {
|
||||||
|
return r.person ? r.m.servers[r.person.server]?.name || 'Dawnline' : 'Dawnline';
|
||||||
|
}
|
||||||
|
|
||||||
/** The app shell; it reads the code from its own URL and sends it along. */
|
/** The app shell; it reads the code from its own URL and sends it along. */
|
||||||
function shell(r) {
|
function shell(r) {
|
||||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
// 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 v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||||
let base = r.base, title = r.title;
|
let base = r.base, title = place(r);
|
||||||
headers(r, '200 OK', {
|
headers(r, '200 OK', {
|
||||||
'Content-Type': 'text/html; charset=utf-8',
|
'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'; " +
|
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
||||||
@@ -263,30 +297,90 @@ function reload(r) {
|
|||||||
not_found(r);
|
not_found(r);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The person's state for the page: a stop by the admin (pause, end of access)
|
||||||
|
* wins over their server being off, so they learn that their access is stopped.
|
||||||
|
*/
|
||||||
|
function person_state(m, p, usage) {
|
||||||
|
let st = core.person_state(m, p, usage);
|
||||||
|
if (st == 'server_off') {
|
||||||
|
let own = core.own_state(m, p, usage);
|
||||||
|
if (LOCKED[own])
|
||||||
|
return own;
|
||||||
|
}
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Why the person can't change anything right now, or null. */
|
||||||
|
function locked(r) {
|
||||||
|
return LOCKED[person_state(r.m, r.person, core.load_usage())] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refuses a change (or a config) while the person is stopped. */
|
||||||
|
function need_open(r) {
|
||||||
|
let why = locked(r);
|
||||||
|
if (why)
|
||||||
|
fail(r, '403 Forbidden', why);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The same link over HTTPS (for a plain-HTTP visitor), or null when this is it. */
|
||||||
|
function https_url(r) {
|
||||||
|
if (r.https)
|
||||||
|
return null;
|
||||||
|
let host = r.host;
|
||||||
|
let h = match(host, /^\[/) ? match(host, /^(\[[^\]]*\])/)?.[1] : split(host, ':')[0];
|
||||||
|
let port = r.m.settings.portal_port;
|
||||||
|
return `https://${h}${port == 443 ? '' : `:${port}`}${r.base}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keys and the disguise never travel in the clear: over plain HTTP a
|
||||||
|
* configuration is refused, and the answer names the HTTPS link to use.
|
||||||
|
*/
|
||||||
|
function need_https(r) {
|
||||||
|
let u = https_url(r);
|
||||||
|
if (u)
|
||||||
|
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The router's offset from UTC in minutes: the admin sets hours in its time, the page shows the visitor's. */
|
||||||
|
function tz_offset() {
|
||||||
|
let t = time();
|
||||||
|
return int((timegm(localtime(t)) - t) / 60);
|
||||||
|
}
|
||||||
|
|
||||||
/** Everything the page shows. */
|
/** Everything the page shows. */
|
||||||
function state(r) {
|
function state(r) {
|
||||||
let m = r.m, person = r.person;
|
let m = r.m, person = r.person;
|
||||||
let usage = core.load_usage();
|
let usage = core.load_usage();
|
||||||
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
||||||
|
v.state = person_state(m, person, usage);
|
||||||
|
// Day by day this month, for the page's chart (the admin's views have no use for it).
|
||||||
|
v.month_days = view.month_days(usage.people?.[person.id]);
|
||||||
let srv = m.servers[person.server];
|
let srv = m.servers[person.server];
|
||||||
// The device this page was opened from, when it came through the tunnel.
|
// The device this page was opened from, through the tunnel or beside it.
|
||||||
let here = null;
|
let here = view.device_here(v.devices, r.peer);
|
||||||
for (let id, d in m.devices)
|
|
||||||
if (d.person == person.id && d.address == r.peer)
|
|
||||||
here = id;
|
|
||||||
return {
|
return {
|
||||||
title: r.title,
|
|
||||||
person: v,
|
person: v,
|
||||||
here,
|
here,
|
||||||
server: {
|
server: {
|
||||||
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
|
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).
|
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
|
||||||
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
||||||
|
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
|
||||||
|
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
|
||||||
},
|
},
|
||||||
can_add: length(person.devices) < person.device_limit,
|
can_add: length(person.devices) < person.device_limit,
|
||||||
|
locked: LOCKED[v.state] != null,
|
||||||
|
// Over plain HTTP: where the configurations are (keys only travel encrypted).
|
||||||
|
https_url: https_url(r),
|
||||||
kinds: core.KINDS,
|
kinds: core.KINDS,
|
||||||
// The router's day: access ends and usage days follow its clock, not the browser's.
|
// The router's day: access ends and usage days follow its clock, not the browser's.
|
||||||
today: today(),
|
today: today(),
|
||||||
|
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
|
||||||
|
now: time(),
|
||||||
|
// And its time zone: hours are set in the router's time, shown in the visitor's.
|
||||||
|
tz_offset: tz_offset(),
|
||||||
version: VERSION,
|
version: VERSION,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -304,9 +398,12 @@ function api_state(r) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function api_add(r) {
|
function api_add(r) {
|
||||||
|
need_open(r);
|
||||||
|
need_https(r);
|
||||||
let b = body(r);
|
let b = body(r);
|
||||||
if (!devices.ready())
|
if (!devices.ready())
|
||||||
fail(r, '503 Service Unavailable', NOT_READY);
|
fail(r, '503 Service Unavailable', NOT_READY);
|
||||||
|
rate_action(r);
|
||||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
|
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
|
||||||
reload(r);
|
reload(r);
|
||||||
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
|
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
|
||||||
@@ -314,6 +411,8 @@ function api_add(r) {
|
|||||||
|
|
||||||
function api_config(r, id) {
|
function api_config(r, id) {
|
||||||
let d = own_device(r, id);
|
let d = own_device(r, id);
|
||||||
|
need_open(r);
|
||||||
|
need_https(r);
|
||||||
awg.mark_issued(r.m, d.id);
|
awg.mark_issued(r.m, d.id);
|
||||||
send_json(r, '200 OK', awg.client_config(r.m, d));
|
send_json(r, '200 OK', awg.client_config(r.m, d));
|
||||||
}
|
}
|
||||||
@@ -324,10 +423,12 @@ const ACTIONS = {
|
|||||||
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
|
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
|
||||||
return {};
|
return {};
|
||||||
},
|
},
|
||||||
rotate: (r, d, b) => {
|
// Set up from scratch: new keys and the new configuration, which the set-up sheet takes in.
|
||||||
|
reconnect: (r, d, b) => {
|
||||||
|
need_https(r);
|
||||||
if (!devices.ready())
|
if (!devices.ready())
|
||||||
fail(r, '503 Service Unavailable', NOT_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 }));
|
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
|
||||||
return { config };
|
return { config };
|
||||||
},
|
},
|
||||||
'delete': (r, d, b) => {
|
'delete': (r, d, b) => {
|
||||||
@@ -338,10 +439,12 @@ const ACTIONS = {
|
|||||||
|
|
||||||
function api_device(r, id) {
|
function api_device(r, id) {
|
||||||
let d = own_device(r, id);
|
let d = own_device(r, id);
|
||||||
|
need_open(r);
|
||||||
let b = body(r);
|
let b = body(r);
|
||||||
let act = ACTIONS[b.action];
|
let act = ACTIONS[b.action];
|
||||||
if (!act)
|
if (!act)
|
||||||
fail(r, '400 Bad Request', 'Unknown action.');
|
fail(r, '400 Bad Request', 'Unknown action.');
|
||||||
|
rate_action(r);
|
||||||
let res = act(r, d, b);
|
let res = act(r, d, b);
|
||||||
reload(r);
|
reload(r);
|
||||||
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
|
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
|
||||||
@@ -388,11 +491,10 @@ export function handle(io) {
|
|||||||
let host = header('host') ?? '';
|
let host = header('host') ?? '';
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let r = {
|
let r = {
|
||||||
io, env, m, path, https,
|
io, env, m, path, https, host,
|
||||||
method: env.REQUEST_METHOD ?? 'GET',
|
method: env.REQUEST_METHOD ?? 'GET',
|
||||||
peer: env.REMOTE_ADDR ?? '',
|
peer: env.REMOTE_ADDR ?? '',
|
||||||
buckets: buckets(env),
|
buckets: buckets(env),
|
||||||
title: m.settings.portal_title || 'Dawnline',
|
|
||||||
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
|
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
|
||||||
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
||||||
person: null,
|
person: null,
|
||||||
@@ -415,12 +517,13 @@ export function handle(io) {
|
|||||||
if (p.code == code)
|
if (p.code == code)
|
||||||
r.person = p;
|
r.person = p;
|
||||||
|
|
||||||
// A wrong code or a blocked client: indistinguishable from a path that does
|
// A wrong code is indistinguishable from a path that does not exist. Only
|
||||||
// not exist. Only well-formed guesses count towards the limit.
|
// well-formed guesses count towards the limit, and a client over it is just
|
||||||
if (rate_blocked(r))
|
// no longer counted: a valid link always opens, so guesses from a shared
|
||||||
not_found(r);
|
// address (every Cloudflare visitor) cannot lock its owner out.
|
||||||
if (r.person == null) {
|
if (r.person == null) {
|
||||||
rate_fail(r);
|
if (!rate_blocked(r))
|
||||||
|
rate_fail(r);
|
||||||
not_found(r);
|
not_found(r);
|
||||||
}
|
}
|
||||||
r.base = `/${code}`;
|
r.base = `/${code}`;
|
||||||
|
|||||||
@@ -54,10 +54,12 @@ export function running() {
|
|||||||
*/
|
*/
|
||||||
export function sync(m, target, lan) {
|
export function sync(m, target, lan) {
|
||||||
ensure_dir('/var/etc');
|
ensure_dir('/var/etc');
|
||||||
|
// Servers that are on: with none, the resolver idles on loopback.
|
||||||
let ifs = [];
|
let ifs = [];
|
||||||
for (let id, s in m.servers)
|
for (let id, s in m.servers)
|
||||||
for (let t in core.tunnels(s))
|
if (s.enabled)
|
||||||
push(ifs, t.ifname);
|
for (let t in core.tunnels(s))
|
||||||
|
push(ifs, t.ifname);
|
||||||
let lines = [
|
let lines = [
|
||||||
`# mode=${target.mode}`,
|
`# mode=${target.mode}`,
|
||||||
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
|
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
|
||||||
@@ -76,7 +78,7 @@ export function sync(m, target, lan) {
|
|||||||
push(lines, `server=${a}@${target.address}`);
|
push(lines, `server=${a}@${target.address}`);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// No tunnel yet: loopback only (without any interface= line dnsmasq would answer everywhere).
|
// No tunnel on: 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}`);
|
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`));
|
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
|
||||||
if ((readfile(RESOLV) ?? '') != resolv) {
|
if ((readfile(RESOLV) ?? '') != resolv) {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import * as core from 'dawnline.core';
|
|||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
import * as health from 'dawnline.health';
|
import * as health from 'dawnline.health';
|
||||||
import * as schema from 'dawnline.schema';
|
import * as schema from 'dawnline.schema';
|
||||||
|
import { uniq } from 'dawnline.util';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An rpcd handler from fn(args): an object result is passed on, anything else
|
* An rpcd handler from fn(args): an object result is passed on, anything else
|
||||||
@@ -33,16 +34,27 @@ export function clamp_days(v) {
|
|||||||
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
|
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const METHODS = [ 'off', 'standard', 'strong', 'max' ];
|
export const METHODS = [ 'off', 'balanced', 'max' ];
|
||||||
|
|
||||||
|
/** The disguise a new server gets: the strongest this router can run. */
|
||||||
|
export function default_method() {
|
||||||
|
let c = awg.caps();
|
||||||
|
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
|
||||||
|
};
|
||||||
|
|
||||||
/** A disguise method the installed AmneziaWG can run. */
|
/** A disguise method the installed AmneziaWG can run. */
|
||||||
export function check_method(name) {
|
export function check_method(name) {
|
||||||
if (index(METHODS, name) < 0)
|
if (index(METHODS, name) < 0)
|
||||||
die('Unknown disguise method.');
|
die('Unknown disguise method.');
|
||||||
if (name == 'max' && !awg.caps().v3)
|
let c = awg.caps();
|
||||||
|
if (name == 'max' && !c.v3)
|
||||||
die(awg.installed()
|
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.'
|
? '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.');
|
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.');
|
||||||
|
if (name == 'balanced' && !c.v2)
|
||||||
|
die(awg.installed()
|
||||||
|
? 'Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.'
|
||||||
|
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.');
|
||||||
return name;
|
return name;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -52,6 +64,36 @@ export function check_method(name) {
|
|||||||
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
|
* 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.
|
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
|
||||||
*/
|
*/
|
||||||
|
/** TCP port forwards from the servers' WAN zones: [{ from, to, name }]. */
|
||||||
|
function tcp_forwards(m) {
|
||||||
|
let out = [];
|
||||||
|
for (let z in uniq([ 'wan', ...map(values(m.servers), (s) => s.wan_zone) ]))
|
||||||
|
push(out, ...core.wan_forwards(z, 'tcp'));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TCP ports the portal can't take, and who holds them: [{ from, to, who }].
|
||||||
|
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
|
||||||
|
*/
|
||||||
|
export function tcp_taken(m) {
|
||||||
|
let out = [];
|
||||||
|
let held = {};
|
||||||
|
let hold = (p, who) => {
|
||||||
|
if (!held[p]) {
|
||||||
|
held[p] = true;
|
||||||
|
push(out, { from: p, to: p, who });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (let p in schema.RESERVED_PORTS)
|
||||||
|
hold(p, 'the router itself');
|
||||||
|
for (let p, name in health.tcp_port_programs())
|
||||||
|
hold(+p, `${name} on this router`);
|
||||||
|
for (let f in tcp_forwards(m))
|
||||||
|
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
export function check_portal(m, was) {
|
export function check_portal(m, was) {
|
||||||
let s = m.settings;
|
let s = m.settings;
|
||||||
if (!s.portal_enabled)
|
if (!s.portal_enabled)
|
||||||
@@ -80,4 +122,9 @@ export function check_portal(m, was) {
|
|||||||
if (length(owners))
|
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.`);
|
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.`);
|
||||||
}
|
}
|
||||||
|
// A forwarded port never reaches the router: the portal would be unreachable.
|
||||||
|
for (let p in ports)
|
||||||
|
for (let f in tcp_forwards(m))
|
||||||
|
if (f.from <= p && p <= f.to)
|
||||||
|
die(`TCP ${p} is sent on by port forward “${f.name}”. Choose another portal port.`);
|
||||||
};
|
};
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
import { readfile } from 'fs';
|
import { readfile } from 'fs';
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util';
|
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength, NAME_RULE } from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as apply from 'dawnline.apply';
|
import * as apply from 'dawnline.apply';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
@@ -27,8 +27,8 @@ function new_id(m, make) {
|
|||||||
|
|
||||||
function service_set(a) {
|
function service_set(a) {
|
||||||
let name = str(a.name);
|
let name = str(a.name);
|
||||||
if (name == '' || length(name) > 48)
|
if (!valid_name(name))
|
||||||
die('Enter a service name.');
|
die(`Service: ${NAME_RULE}`);
|
||||||
let address = str(a.address);
|
let address = str(a.address);
|
||||||
if (!schema.ipv4(address))
|
if (!schema.ipv4(address))
|
||||||
die('Address must be an IPv4 address.');
|
die('Address must be an IPv4 address.');
|
||||||
@@ -54,8 +54,8 @@ function service_set(a) {
|
|||||||
c.delete(core.CONFIG, id, 'port');
|
c.delete(core.CONFIG, id, 'port');
|
||||||
return id;
|
return id;
|
||||||
});
|
});
|
||||||
apply.sync();
|
let s = apply.sync();
|
||||||
return { id };
|
return { id, warning: s.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
function service_delete(a) {
|
function service_delete(a) {
|
||||||
@@ -72,8 +72,8 @@ function service_delete(a) {
|
|||||||
c.delete(core.CONFIG, pid, 'service');
|
c.delete(core.CONFIG, pid, 'service');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
apply.sync();
|
let s = apply.sync();
|
||||||
return { ok: true };
|
return { ok: true, warning: s.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- circles ---------- */
|
/* ---------- circles ---------- */
|
||||||
@@ -81,8 +81,8 @@ function service_delete(a) {
|
|||||||
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
||||||
function circle_set(a) {
|
function circle_set(a) {
|
||||||
let name = str(a.name);
|
let name = str(a.name);
|
||||||
if (name == '' || length(name) > 32)
|
if (!valid_name(name) || ulength(name) > 32)
|
||||||
die('Enter a circle name (up to 32 characters).');
|
die('Enter a circle name: up to 32 characters, without < > " or \\.');
|
||||||
let res = store.transact((c, m) => {
|
let res = store.transact((c, m) => {
|
||||||
let ci = a.id ? m.circles[a.id] : null;
|
let ci = a.id ? m.circles[a.id] : null;
|
||||||
if (a.id && !ci)
|
if (a.id && !ci)
|
||||||
@@ -112,9 +112,9 @@ function circle_set(a) {
|
|||||||
}
|
}
|
||||||
return { id, edit: !!ci, server: m.servers[server].name };
|
return { id, edit: !!ci, server: m.servers[server].name };
|
||||||
});
|
});
|
||||||
apply.sync();
|
let s = apply.sync();
|
||||||
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
|
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
|
||||||
return { id: res.id, circles: values(core.load().circles) };
|
return { id: res.id, circles: values(core.load().circles), warning: s.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
function circle_delete(a) {
|
function circle_delete(a) {
|
||||||
@@ -128,9 +128,9 @@ function circle_delete(a) {
|
|||||||
c.delete(core.CONFIG, pid, 'circle');
|
c.delete(core.CONFIG, pid, 'circle');
|
||||||
return { name: ci.name, server: m.servers[ci.server]?.name };
|
return { name: ci.name, server: m.servers[ci.server]?.name };
|
||||||
});
|
});
|
||||||
apply.sync();
|
let s = apply.sync();
|
||||||
admin_log('awg', 'removed', 'circle', res.name, res.server);
|
admin_log('awg', 'removed', 'circle', res.name, res.server);
|
||||||
return { circles: values(core.load().circles) };
|
return { circles: values(core.load().circles), warning: s.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- devices at home ---------- */
|
/* ---------- devices at home ---------- */
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import * as devices from 'dawnline.devices';
|
|||||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
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',
|
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
|
||||||
'bonus_gb', 'hours', 'note', 'dns_mode' ];
|
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
|
||||||
|
|
||||||
/* ---------- people ---------- */
|
/* ---------- people ---------- */
|
||||||
|
|
||||||
@@ -39,19 +39,23 @@ function person_update(a) {
|
|||||||
fields.circle = a.circle;
|
fields.circle = a.circle;
|
||||||
if (type(a.home_nets) == 'array')
|
if (type(a.home_nets) == 'array')
|
||||||
fields.home_nets = a.home_nets;
|
fields.home_nets = a.home_nets;
|
||||||
|
let m0 = null;
|
||||||
let before = store.transact((c, m) => {
|
let before = store.transact((c, m) => {
|
||||||
let p = m.people[a.id];
|
let p = m.people[a.id];
|
||||||
|
m0 = m;
|
||||||
core.update_person(c, m, a.id, fields);
|
core.update_person(c, m, a.id, fields);
|
||||||
return p;
|
return p;
|
||||||
});
|
});
|
||||||
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
|
// "moved to Test" says more than "server".
|
||||||
|
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
|
||||||
|
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
|
||||||
if (changes)
|
if (changes)
|
||||||
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
|
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
|
||||||
// Access changes affect the nft sets and client AllowedIPs.
|
// Access changes affect the nft sets and client AllowedIPs.
|
||||||
apply.sync();
|
let s = apply.sync();
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let u = core.load_usage();
|
let u = core.load_usage();
|
||||||
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access };
|
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
function person_pause(a) {
|
function person_pause(a) {
|
||||||
@@ -67,16 +71,34 @@ function person_pause(a) {
|
|||||||
return apply.sync();
|
return apply.sync();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A new personal link: the old one stops working at once (every portal request carries the code). */
|
/**
|
||||||
|
* A new personal link: the old one stops working at once (every portal
|
||||||
|
* request carries the code). What the old link already handed out stays
|
||||||
|
* unless asked: `remove` lists the person's devices to take away with it.
|
||||||
|
*/
|
||||||
function person_regen(a) {
|
function person_regen(a) {
|
||||||
store.transact((c, m) => {
|
let gone = store.transact((c, m) => {
|
||||||
if (!m.people[a.id])
|
if (!m.people[a.id])
|
||||||
die('Unknown person.');
|
die('Unknown person.');
|
||||||
c.set(core.CONFIG, a.id, 'code', core.new_code());
|
c.set(core.CONFIG, a.id, 'code', core.new_code());
|
||||||
|
c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
|
||||||
|
let gone = [];
|
||||||
|
for (let id in (type(a.remove) == 'array' ? a.remove : []))
|
||||||
|
if (m.devices[id]?.person == a.id) {
|
||||||
|
push(gone, m.devices[id]);
|
||||||
|
core.delete_device(c, m, id);
|
||||||
|
}
|
||||||
|
return gone;
|
||||||
});
|
});
|
||||||
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
|
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
|
||||||
|
let s = null;
|
||||||
|
if (length(gone)) {
|
||||||
|
for (let d in gone)
|
||||||
|
live.add_event({ type: 'device_removed', person: a.id, device: d.id, detail: d.name, dname: d.name, dkind: d.kind, by: 'admin' });
|
||||||
|
s = apply.sync();
|
||||||
|
}
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
return { link: core.portal_url(m, m.people[a.id]) };
|
return { link: core.portal_url(m, m.people[a.id]), removed: length(gone), warning: s?.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
|
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
|
||||||
@@ -111,15 +133,6 @@ function person_usage(a) {
|
|||||||
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
|
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 ---------- */
|
/* ---------- devices ---------- */
|
||||||
|
|
||||||
function device_create(a) {
|
function device_create(a) {
|
||||||
@@ -147,15 +160,14 @@ export const methods = {
|
|||||||
},
|
},
|
||||||
person_update: {
|
person_update: {
|
||||||
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
|
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
|
||||||
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
|
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
|
||||||
call: wrap(person_update),
|
call: wrap(person_update),
|
||||||
},
|
},
|
||||||
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
|
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
|
||||||
person_regen: { args: { id: '' }, call: wrap(person_regen) },
|
person_regen: { args: { id: '', remove: [] }, call: wrap(person_regen) },
|
||||||
person_links: { args: { id: '' }, call: wrap(person_links) },
|
person_links: { args: { id: '' }, call: wrap(person_links) },
|
||||||
person_delete: { args: { id: '' }, call: wrap(person_delete) },
|
person_delete: { args: { id: '' }, call: wrap(person_delete) },
|
||||||
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
|
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_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
|
||||||
device_config: { args: { id: '' }, call: wrap(device_config) },
|
device_config: { args: { id: '' }, call: wrap(device_config) },
|
||||||
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
|
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// Interfaces settings, its disguise, and removing it.
|
// Interfaces settings, its disguise, and removing it.
|
||||||
|
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util';
|
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, NAME_RULE, rand_int, uniq, admin_log } from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
import * as apply from 'dawnline.apply';
|
import * as apply from 'dawnline.apply';
|
||||||
@@ -14,7 +14,7 @@ import * as schema from 'dawnline.schema';
|
|||||||
import * as health from 'dawnline.health';
|
import * as health from 'dawnline.health';
|
||||||
import * as backup from 'dawnline.backup';
|
import * as backup from 'dawnline.backup';
|
||||||
import * as devices from 'dawnline.devices';
|
import * as devices from 'dawnline.devices';
|
||||||
import { wrap, str, check_method, check_portal } from 'dawnline.rpc.common';
|
import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
|
||||||
|
|
||||||
/** Server ids that would shadow a portal path. */
|
/** Server ids that would shadow a portal path. */
|
||||||
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
|
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
|
||||||
@@ -23,27 +23,63 @@ const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other',
|
|||||||
|
|
||||||
/* ---------- free names, ports and subnets ---------- */
|
/* ---------- free names, ports and subnets ---------- */
|
||||||
|
|
||||||
function free_port(m) {
|
/**
|
||||||
let used = {};
|
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
|
||||||
|
* Other servers, tunnel interfaces, programs on the router and port forwards
|
||||||
|
* from its WAN zone. `srv` is the server being edited: its own port isn't counted.
|
||||||
|
*/
|
||||||
|
function udp_taken(m, srv, wan_zone) {
|
||||||
|
let out = [];
|
||||||
|
let held = {};
|
||||||
|
let hold = (p, who) => {
|
||||||
|
if (p > 0 && !held[p]) {
|
||||||
|
held[p] = true;
|
||||||
|
push(out, { from: p, to: p, who });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (let id, o in m.servers)
|
||||||
|
if (id != srv?.id)
|
||||||
|
hold(o.port, `server “${o.name}”`);
|
||||||
let nc = cursor();
|
let nc = cursor();
|
||||||
nc.load('network');
|
nc.load('network');
|
||||||
nc.foreach('network', 'interface', (s) => {
|
nc.foreach('network', 'interface', (s) => {
|
||||||
if (s.listen_port)
|
if (s.listen_port && s['.name'] != srv?.ifname)
|
||||||
used[+s.listen_port] = true;
|
hold(+s.listen_port, `interface ${s['.name']}`);
|
||||||
});
|
});
|
||||||
for (let id, srv in m.servers)
|
let progs = health.udp_port_programs();
|
||||||
used[srv.port] = true;
|
for (let p in health.udp_bound())
|
||||||
|
if (p != srv?.port)
|
||||||
|
hold(p, progs[`${p}`] ? `${progs[`${p}`]} on this router` : 'another program on this router');
|
||||||
|
for (let f in core.wan_forwards(wan_zone, 'udp'))
|
||||||
|
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function check_udp_port(port, taken) {
|
||||||
|
for (let t in taken)
|
||||||
|
if (t.from <= port && port <= t.to)
|
||||||
|
die(`UDP ${port} is used by ${t.who}. Choose another port.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The usual AmneziaWG port when free, otherwise a random high one. */
|
||||||
|
const DEFAULT_PORT = 4500;
|
||||||
|
|
||||||
|
function free_port(taken) {
|
||||||
|
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
|
||||||
|
if (!used(DEFAULT_PORT))
|
||||||
|
return DEFAULT_PORT;
|
||||||
for (let i = 0; i < 50; i++) {
|
for (let i = 0; i < 50; i++) {
|
||||||
let p = rand_int(40000, 60000);
|
let p = rand_int(40000, 60000);
|
||||||
if (!used[p])
|
if (!used(p))
|
||||||
return p;
|
return p;
|
||||||
}
|
}
|
||||||
return 51830;
|
return 51830;
|
||||||
}
|
}
|
||||||
|
|
||||||
function free_subnet(taken) {
|
function free_subnet(taken) {
|
||||||
for (let i = 0; i < 200; i++) {
|
for (let i = 0; i < 300; i++) {
|
||||||
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)));
|
// 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
|
||||||
|
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
|
||||||
let bad = false;
|
let bad = false;
|
||||||
for (let t in taken) {
|
for (let t in taken) {
|
||||||
let tc = parse_cidr(t);
|
let tc = parse_cidr(t);
|
||||||
@@ -58,9 +94,14 @@ function free_subnet(taken) {
|
|||||||
return '10.77.0.0/24';
|
return '10.77.0.0/24';
|
||||||
}
|
}
|
||||||
|
|
||||||
function free_portal_port(cur) {
|
/**
|
||||||
for (let p in uniq([ cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
|
* A portal port free together with the next one (plain HTTP for IP links):
|
||||||
if (!length(health.tcp_port_owners(p)) && !length(health.tcp_port_owners(p + 1)))
|
* `first` (the server's UDP number, TCP is another port) before the usual ones.
|
||||||
|
*/
|
||||||
|
function free_portal_port(first, cur, taken) {
|
||||||
|
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
|
||||||
|
for (let p in uniq([ first, cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
|
||||||
|
if (!used(p) && !used(p + 1))
|
||||||
return p;
|
return p;
|
||||||
return 9443;
|
return 9443;
|
||||||
}
|
}
|
||||||
@@ -97,66 +138,113 @@ function free_server_id(m) {
|
|||||||
return `server${n}`;
|
return `server${n}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Subnets a new server must not overlap: the router's networks and the other servers. */
|
/** Networks a new server must not overlap, by name: the router's and the other servers'. */
|
||||||
function taken_subnets(m) {
|
function taken_networks(m) {
|
||||||
let taken = health.used_subnets(null);
|
let out = [];
|
||||||
|
let seen = {};
|
||||||
|
let add = (name, cidr) => {
|
||||||
|
let c = parse_cidr(cidr);
|
||||||
|
if (c && !seen[cidr_str(c)]) {
|
||||||
|
seen[cidr_str(c)] = true;
|
||||||
|
push(out, { name, cidr: cidr_str(c) });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (let n in health.networks())
|
||||||
|
add(n.iface, n.cidr);
|
||||||
for (let id, s in m.servers)
|
for (let id, s in m.servers)
|
||||||
push(taken, s.subnet);
|
add(s.name, s.subnet);
|
||||||
return taken;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- setup ---------- */
|
/* ---------- setup ---------- */
|
||||||
|
|
||||||
function setup_defaults(a) {
|
function setup_defaults(a) {
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let taken = taken_subnets(m);
|
let networks = taken_networks(m);
|
||||||
let zones = [];
|
let zones = [];
|
||||||
let fc = cursor();
|
let fc = cursor();
|
||||||
fc.load('firewall');
|
fc.load('firewall');
|
||||||
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
|
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
|
||||||
let host = m.settings.portal_host;
|
let snap = net.snapshot(true);
|
||||||
|
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
|
||||||
|
let kind = health.wan_kind(wan_ip || null);
|
||||||
|
let host = m.settings.portal_host, from = host ? 'portal' : '';
|
||||||
if (!host) {
|
if (!host) {
|
||||||
// Prefer a DDNS name, then an ACME certificate's, then the WAN address.
|
// Prefer a DDNS name, then an ACME certificate's, then the WAN address —
|
||||||
|
// but never a private or CGNAT one: nobody on the internet reaches it.
|
||||||
let dc = cursor();
|
let dc = cursor();
|
||||||
if (dc.load('ddns'))
|
if (dc.load('ddns'))
|
||||||
dc.foreach('ddns', 'service', (s) => {
|
dc.foreach('ddns', 'service', (s) => {
|
||||||
if (!host && s.lookup_host && s.enabled == '1')
|
if (!host && s.lookup_host && s.enabled == '1') {
|
||||||
host = s.lookup_host;
|
host = s.lookup_host;
|
||||||
|
from = 'ddns';
|
||||||
|
}
|
||||||
});
|
});
|
||||||
if (!host)
|
if (!host) {
|
||||||
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
|
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
|
||||||
if (!host)
|
from = host ? 'cert' : '';
|
||||||
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
|
}
|
||||||
|
if (!host && kind == 'public') {
|
||||||
|
host = wan_ip;
|
||||||
|
from = 'wan';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
// The zones the WAN and LAN devices are in, whatever they are called.
|
||||||
|
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
|
||||||
|
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
|
||||||
|
let udp = udp_taken(m, null, wan_zone);
|
||||||
|
let tcp = tcp_taken(m);
|
||||||
|
let port = free_port(udp);
|
||||||
return {
|
return {
|
||||||
id: free_server_id(m),
|
id: free_server_id(m),
|
||||||
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
|
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
|
||||||
ifname: free_ifname(m),
|
ifname: free_ifname(m),
|
||||||
port: free_port(m),
|
port,
|
||||||
subnet: free_subnet(taken),
|
subnet: free_subnet(map(networks, (n) => n.cidr)),
|
||||||
endpoint: host,
|
endpoint: host,
|
||||||
mtu: 1380,
|
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
|
||||||
|
endpoint_from: from,
|
||||||
|
wan_kind: kind,
|
||||||
|
wan_ip: wan_ip || null,
|
||||||
|
// Automatic.
|
||||||
|
mtu: 0,
|
||||||
zones,
|
zones,
|
||||||
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
|
lan_zone,
|
||||||
wan_zone: index(zones, 'wan') >= 0 ? 'wan' : zones[1],
|
wan_zone,
|
||||||
portal_port: free_portal_port(m.settings.portal_port),
|
// A portal already on keeps its port; a new one takes the server's number when it can.
|
||||||
|
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
|
||||||
awg: awg.caps(),
|
awg: awg.caps(),
|
||||||
awg_state: awg.state(),
|
awg_state: awg.load(),
|
||||||
taken,
|
networks,
|
||||||
|
udp_taken: udp,
|
||||||
|
tcp_taken: tcp,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a public address points, as the admin types it (debounced in the
|
||||||
|
* UI): the same facts Health uses, in words. `id` names the server whose WAN
|
||||||
|
* to compare with (a new one: the default WAN).
|
||||||
|
*/
|
||||||
|
function endpoint_probe(a) {
|
||||||
|
let host = str(a.host);
|
||||||
|
if (host != '' && !valid_host(host))
|
||||||
|
die('Public address must be a hostname or IP address.');
|
||||||
|
let m = core.load();
|
||||||
|
let srv = m.servers[str(a.id)] ?? null;
|
||||||
|
let f = health.endpoint_facts(srv, host);
|
||||||
|
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
|
||||||
|
return { ...f, status: w.status, text: w.text };
|
||||||
|
}
|
||||||
|
|
||||||
/** AmneziaWG can run a server: installed, and its kernel module loads. */
|
/** AmneziaWG can run a server: installed, and its kernel module loads. */
|
||||||
function need_awg_loaded() {
|
function need_awg_loaded() {
|
||||||
devices.need_awg();
|
devices.need_awg();
|
||||||
if (awg.state().loaded)
|
if (!awg.load().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.");
|
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. */
|
/** An MTU as typed: '' (automatic) or 1280-1500. */
|
||||||
function check_mtu(v) {
|
function check_mtu(v) {
|
||||||
let s = str(v);
|
let s = str(v);
|
||||||
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
|
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
|
||||||
@@ -180,21 +268,24 @@ function server_create(a) {
|
|||||||
let ifname = str(a.ifname) || free_ifname(m);
|
let ifname = str(a.ifname) || free_ifname(m);
|
||||||
if (!ifname_free(m, nc, ifname))
|
if (!ifname_free(m, nc, ifname))
|
||||||
die(`Network interface ${ifname} already exists.`);
|
die(`Network interface ${ifname} already exists.`);
|
||||||
let port = free_port(m);
|
let udp = udp_taken(m, null, str(a.wan_zone) || 'wan');
|
||||||
|
let port = free_port(udp);
|
||||||
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
|
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
|
||||||
if (!schema.valid_port(a.port))
|
if (!schema.valid_port(a.port))
|
||||||
die('UDP port must be 1-65535.');
|
die('UDP port must be 1-65535.');
|
||||||
port = +str(a.port);
|
port = +str(a.port);
|
||||||
}
|
}
|
||||||
for (let sid, o in m.servers)
|
check_udp_port(port, udp);
|
||||||
if (o.port == port)
|
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
|
||||||
die(`UDP ${port} is used by ${o.name}.`);
|
let preset = str(a.preset) || default_method();
|
||||||
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 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);
|
let pc = parse_cidr(srv.subnet);
|
||||||
if (pc)
|
if (pc)
|
||||||
srv.subnet = cidr_str(pc);
|
srv.subnet = cidr_str(pc);
|
||||||
|
// Public addresses inside the tunnel would hide the real hosts behind them.
|
||||||
|
// New servers only: a restored backup keeps what it had.
|
||||||
|
if (pc && !core.private_cidr(pc))
|
||||||
|
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
|
||||||
let taken = [ ...router_subnets ];
|
let taken = [ ...router_subnets ];
|
||||||
for (let sid, o in m.servers)
|
for (let sid, o in m.servers)
|
||||||
push(taken, o.subnet);
|
push(taken, o.subnet);
|
||||||
@@ -206,13 +297,16 @@ function server_create(a) {
|
|||||||
let set = (k, v) => c.set(core.CONFIG, id, k, v);
|
let set = (k, v) => c.set(core.CONFIG, id, k, v);
|
||||||
c.set(core.CONFIG, 'settings', 'settings');
|
c.set(core.CONFIG, 'settings', 'settings');
|
||||||
c.set(core.CONFIG, id, 'server');
|
c.set(core.CONFIG, id, 'server');
|
||||||
|
if (!valid_name(str(a.name) || 'Home'))
|
||||||
|
die(`Server: ${NAME_RULE}`);
|
||||||
set('name', str(a.name) || 'Home');
|
set('name', str(a.name) || 'Home');
|
||||||
set('ifname', ifname);
|
set('ifname', ifname);
|
||||||
set('port', `${port}`);
|
set('port', `${port}`);
|
||||||
set('subnet', srv.subnet);
|
set('subnet', srv.subnet);
|
||||||
if (srv.endpoint)
|
if (srv.endpoint)
|
||||||
set('endpoint', srv.endpoint);
|
set('endpoint', srv.endpoint);
|
||||||
set('mtu', mtu);
|
if (mtu)
|
||||||
|
set('mtu', mtu);
|
||||||
set('keepalive', '25');
|
set('keepalive', '25');
|
||||||
let kp = awg.server_keys();
|
let kp = awg.server_keys();
|
||||||
set('private_key', kp.private_key);
|
set('private_key', kp.private_key);
|
||||||
@@ -249,8 +343,11 @@ function server_create(a) {
|
|||||||
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
|
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
|
||||||
let made = core.load().servers[id];
|
let made = core.load().servers[id];
|
||||||
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
|
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
|
||||||
sh_bg('/etc/init.d/dawnline restart');
|
// netifd reads its protocol handlers when it starts: AmneziaWG installed
|
||||||
return { id, applied: r };
|
// after that (by hand, or by an older installer) needs a network restart.
|
||||||
|
let network_restart = !awg.state().handler;
|
||||||
|
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
|
||||||
|
return { id, applied: r, network_restart, warning: r.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- interfaces ---------- */
|
/* ---------- interfaces ---------- */
|
||||||
@@ -403,12 +500,13 @@ function server_update(a) {
|
|||||||
die('Unknown server.');
|
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);
|
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 (v.name != null) {
|
||||||
if (str(v.name) == '')
|
if (!valid_name(str(v.name)))
|
||||||
die('Name cannot be empty.');
|
die(`Server: ${NAME_RULE}`);
|
||||||
set('name', str(v.name));
|
set('name', str(v.name));
|
||||||
}
|
}
|
||||||
|
// Empty = the portal's address (core.endpoint_host), as at creation.
|
||||||
if (v.endpoint != null) {
|
if (v.endpoint != null) {
|
||||||
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint)))
|
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
|
||||||
die('Public address must be a hostname or IP address.');
|
die('Public address must be a hostname or IP address.');
|
||||||
set('endpoint', str(v.endpoint));
|
set('endpoint', str(v.endpoint));
|
||||||
}
|
}
|
||||||
@@ -416,9 +514,8 @@ function server_update(a) {
|
|||||||
if (!schema.valid_port(v.port))
|
if (!schema.valid_port(v.port))
|
||||||
die('UDP port must be 1-65535.');
|
die('UDP port must be 1-65535.');
|
||||||
let n = +str(v.port);
|
let n = +str(v.port);
|
||||||
for (let id, o in m.servers)
|
if (n != srv.port)
|
||||||
if (id != srv.id && o.port == n)
|
check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
|
||||||
die(`UDP ${n} is used by ${o.name}.`);
|
|
||||||
set('port', `${n}`);
|
set('port', `${n}`);
|
||||||
}
|
}
|
||||||
if (v.enabled != null)
|
if (v.enabled != null)
|
||||||
@@ -443,15 +540,28 @@ function server_update(a) {
|
|||||||
else
|
else
|
||||||
c.delete(core.CONFIG, srv.id, 'dns');
|
c.delete(core.CONFIG, srv.id, 'dns');
|
||||||
}
|
}
|
||||||
|
// A new tunnel network: private, free, and every device renumbered into it.
|
||||||
|
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
|
||||||
|
let pc = parse_cidr(str(v.subnet));
|
||||||
|
if (!pc)
|
||||||
|
die('Subnet must look like 10.77.0.0/24.');
|
||||||
|
if (!core.private_cidr(pc))
|
||||||
|
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
|
||||||
|
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
|
||||||
|
for (let t in taken)
|
||||||
|
if (cidr_overlaps(pc, parse_cidr(t)))
|
||||||
|
die(`Subnet overlaps ${t}.`);
|
||||||
|
core.renumber_server(c, m, srv, cidr_str(pc));
|
||||||
|
}
|
||||||
return srv;
|
return srv;
|
||||||
});
|
});
|
||||||
// For the log: what changed, in words. Turning on or off is its own line.
|
// For the log: what changed, in words. Turning on or off is its own line.
|
||||||
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
|
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
|
||||||
let what = [];
|
let what = [];
|
||||||
for (let k, label in labels) {
|
for (let k, label in labels) {
|
||||||
if (v[k] == null)
|
if (v[k] == null)
|
||||||
continue;
|
continue;
|
||||||
let was = k == 'dns' ? join(' ', srv.dns ?? []) : `${srv[k] ?? ''}`;
|
let was = k == 'dns' ? join(' ', srv.dns ?? []) : k == 'mtu' && !srv.mtu ? '' : `${srv[k] ?? ''}`;
|
||||||
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
|
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
|
||||||
if (trim(was) != trim(now))
|
if (trim(was) != trim(now))
|
||||||
push(what, label);
|
push(what, label);
|
||||||
@@ -468,8 +578,19 @@ function server_update(a) {
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
|
||||||
|
function server_ports(a) {
|
||||||
|
let m = core.load();
|
||||||
|
let srv = m.servers[a.id];
|
||||||
|
if (!srv)
|
||||||
|
die('Unknown server.');
|
||||||
|
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
|
||||||
|
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
|
||||||
|
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
|
||||||
|
}
|
||||||
|
|
||||||
function server_obfuscation(a) {
|
function server_obfuscation(a) {
|
||||||
let preset = str(a.preset) || 'standard';
|
let preset = str(a.preset) || default_method();
|
||||||
let o = awg.obf_preset(check_method(preset));
|
let o = awg.obf_preset(check_method(preset));
|
||||||
let srv = store.transact((c, m) => {
|
let srv = store.transact((c, m) => {
|
||||||
let srv = m.servers[a.id];
|
let srv = m.servers[a.id];
|
||||||
@@ -520,6 +641,8 @@ export const methods = {
|
|||||||
lan_like: true, portal_enabled: false, portal_port: 0 },
|
lan_like: true, portal_enabled: false, portal_port: 0 },
|
||||||
call: wrap(server_create),
|
call: wrap(server_create),
|
||||||
},
|
},
|
||||||
|
server_ports: { args: { id: '' }, call: wrap(server_ports) },
|
||||||
|
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
|
||||||
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
|
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
|
||||||
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
|
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
|
||||||
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
|
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import * as store from 'dawnline.store';
|
|||||||
import * as schema from 'dawnline.schema';
|
import * as schema from 'dawnline.schema';
|
||||||
import * as health from 'dawnline.health';
|
import * as health from 'dawnline.health';
|
||||||
import * as pc from 'dawnline.portalcert';
|
import * as pc from 'dawnline.portalcert';
|
||||||
import { wrap, check_portal } from 'dawnline.rpc.common';
|
import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common';
|
||||||
|
|
||||||
/** The portal's own checks from Health, shown next to its settings. */
|
/** The portal's own checks from Health, shown next to its settings. */
|
||||||
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
|
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
|
||||||
@@ -65,7 +65,7 @@ function settings_get(a) {
|
|||||||
services: values(m.services),
|
services: values(m.services),
|
||||||
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
|
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,
|
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),
|
tcp_taken: tcp_taken(m),
|
||||||
portal_public_port: core.portal_public_port(m),
|
portal_public_port: core.portal_public_port(m),
|
||||||
geo_cached: length(keys(geo.load().ips)),
|
geo_cached: length(keys(geo.load().ips)),
|
||||||
logs: logs_info(m),
|
logs: logs_info(m),
|
||||||
@@ -115,10 +115,11 @@ function settings_update(a) {
|
|||||||
check_portal(core.load(c), m);
|
check_portal(core.load(c), m);
|
||||||
return { restart, was: m.settings };
|
return { restart, was: m.settings };
|
||||||
});
|
});
|
||||||
|
let s = null;
|
||||||
if (res.restart)
|
if (res.restart)
|
||||||
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
|
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
|
||||||
else
|
else
|
||||||
apply.sync();
|
s = apply.sync();
|
||||||
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
|
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
|
||||||
let now = core.load().settings, was = res.was;
|
let now = core.load().settings, was = res.was;
|
||||||
if (now.portal_enabled != was.portal_enabled)
|
if (now.portal_enabled != was.portal_enabled)
|
||||||
@@ -140,7 +141,10 @@ function settings_update(a) {
|
|||||||
}
|
}
|
||||||
if (now.watchdog != was.watchdog)
|
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');
|
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
|
||||||
return settings_get({});
|
let out = settings_get({});
|
||||||
|
if (s?.warning)
|
||||||
|
out.warning = s.warning;
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const methods = {
|
export const methods = {
|
||||||
|
|||||||
@@ -10,7 +10,29 @@ import * as geo from 'dawnline.geo';
|
|||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
import * as loop from 'dawnline.loop';
|
import * as loop from 'dawnline.loop';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
import { wrap, clamp_days } from 'dawnline.rpc.common';
|
import * as lookup from 'dawnline.lookup';
|
||||||
|
import * as health from 'dawnline.health';
|
||||||
|
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||||
|
|
||||||
|
/** The router's public IPv4 (null when none or private). */
|
||||||
|
function wan_public(m) {
|
||||||
|
let w = lookup.router_wan(m);
|
||||||
|
return w && health.wan_kind(w) == 'public' ? w : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
|
||||||
|
function own_addresses(m) {
|
||||||
|
let own = {};
|
||||||
|
for (let id, srv in m.servers) {
|
||||||
|
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
||||||
|
if (a)
|
||||||
|
own[a] = true;
|
||||||
|
}
|
||||||
|
let wan = lookup.wan_ipv4('wan');
|
||||||
|
if (wan)
|
||||||
|
own[wan] = true;
|
||||||
|
return own;
|
||||||
|
}
|
||||||
|
|
||||||
/** Router location plus one point per (device, recent client address). */
|
/** Router location plus one point per (device, recent client address). */
|
||||||
function geo_view(m, usage, dmp) {
|
function geo_view(m, usage, dmp) {
|
||||||
@@ -19,14 +41,25 @@ function geo_view(m, usage, dmp) {
|
|||||||
let cache = geo.load();
|
let cache = geo.load();
|
||||||
let points = [];
|
let points = [];
|
||||||
let now = time();
|
let now = time();
|
||||||
|
// The router's own public addresses: a device at home that reaches the server through the
|
||||||
|
// WAN address (NAT loopback) shows up from there. Home is not a place people connect from.
|
||||||
|
let own = {};
|
||||||
|
for (let id, srv in m.servers) {
|
||||||
|
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
||||||
|
if (a)
|
||||||
|
own[a] = true;
|
||||||
|
}
|
||||||
|
let wan = lookup.wan_ipv4('wan');
|
||||||
|
if (wan)
|
||||||
|
own[wan] = true;
|
||||||
for (let id, d in m.devices) {
|
for (let id, d in m.devices) {
|
||||||
let rec = usage.devices?.[id];
|
let rec = usage.devices?.[id];
|
||||||
let peer = dmp.peers[d.public_key];
|
let peer = dmp.peers[d.public_key];
|
||||||
let cur = live.endpoint_ip(peer?.endpoint);
|
let cur = live.endpoint_ip(peer?.endpoint);
|
||||||
let online = live.online(dmp, id, peer);
|
let online = live.online(dmp, id, peer);
|
||||||
for (let ip, ts in rec?.ips ?? {}) {
|
for (let ip, ts in rec?.ips ?? {}) {
|
||||||
// Local (LAN / CGNAT) client addresses are not shown on the map.
|
// Local (LAN / CGNAT) client addresses and the router's own are not shown on the map.
|
||||||
let pl = geo.is_public(ip) ? geo.place(cache, ip) : null;
|
let pl = geo.is_public(ip) && !own[ip] ? geo.place(cache, ip) : null;
|
||||||
if (!pl)
|
if (!pl)
|
||||||
continue;
|
continue;
|
||||||
push(points, {
|
push(points, {
|
||||||
@@ -72,10 +105,21 @@ function server_view(m, srv, usage, dmp, rates, days) {
|
|||||||
online++;
|
online++;
|
||||||
}
|
}
|
||||||
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
||||||
|
// The newest handshake from a public address that is not the router's own:
|
||||||
|
// proof that the port is reachable from the internet.
|
||||||
|
let own = own_addresses(m);
|
||||||
|
let reached = 0;
|
||||||
|
for (let id, d in m.devices)
|
||||||
|
if (m.people[d.person]?.server == srv.id)
|
||||||
|
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
|
||||||
|
if (geo.is_public(ip) && !own[ip] && ts > reached)
|
||||||
|
reached = ts;
|
||||||
return {
|
return {
|
||||||
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
|
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
|
||||||
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
|
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,
|
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
|
||||||
|
// What devices get now, by kind (mtu 0 = automatic).
|
||||||
|
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
|
||||||
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
|
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.
|
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
|
||||||
blocked: srv.blocked ?? null,
|
blocked: srv.blocked ?? null,
|
||||||
@@ -142,7 +186,7 @@ function status(a) {
|
|||||||
settings: {
|
settings: {
|
||||||
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
|
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
|
||||||
portal_public_port: core.portal_public_port(m),
|
portal_public_port: core.portal_public_port(m),
|
||||||
paused_all: s.paused_all, default_device_limit: s.default_device_limit, domain: s.domain,
|
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,
|
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
|
||||||
},
|
},
|
||||||
servers,
|
servers,
|
||||||
@@ -155,12 +199,18 @@ function status(a) {
|
|||||||
like_home: loop.status(),
|
like_home: loop.status(),
|
||||||
awg: awg.caps(),
|
awg: awg.caps(),
|
||||||
awg_state: awg.state(),
|
awg_state: awg.state(),
|
||||||
|
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
|
||||||
|
wan: wan_public(m),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
|
||||||
function events_list(a) {
|
function events_list(a) {
|
||||||
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
|
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
|
||||||
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up');
|
let person = str(a.person), since = +a.since || 0;
|
||||||
|
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up' &&
|
||||||
|
(!person || e.person == person) && (!since || (e.ts ?? 0) > since));
|
||||||
let n = +a.limit || 300;
|
let n = +a.limit || 300;
|
||||||
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
|
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
|
||||||
}
|
}
|
||||||
@@ -225,14 +275,15 @@ function usage_clear(a) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
|
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
|
||||||
|
/** The live revision, and the version answering (a page notices an update under it). */
|
||||||
function rev() {
|
function rev() {
|
||||||
return { rev: +(live.presence()?.rev ?? 0) };
|
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
|
||||||
}
|
}
|
||||||
|
|
||||||
export const methods = {
|
export const methods = {
|
||||||
rev: { call: wrap(rev) },
|
rev: { call: wrap(rev) },
|
||||||
status: { args: { days: 30 }, call: wrap(status) },
|
status: { args: { days: 30 }, call: wrap(status) },
|
||||||
events: { args: { limit: 300 }, call: wrap(events_list) },
|
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
|
||||||
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
||||||
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
|
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
|
||||||
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
|
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// config_get_bool does, so the service and the code never disagree.
|
// config_get_bool does, so the service and the code never disagree.
|
||||||
|
|
||||||
import { stat } from 'fs';
|
import { stat } from 'fs';
|
||||||
import { ip2int, valid_host } from 'dawnline.util';
|
import { ip2int, valid_host, ulength } from 'dawnline.util';
|
||||||
import { INTERVALS, TARGETS } from 'dawnline.updates';
|
import { INTERVALS, TARGETS } from 'dawnline.updates';
|
||||||
|
|
||||||
/* ---------- addresses ---------- */
|
/* ---------- addresses ---------- */
|
||||||
@@ -107,24 +107,24 @@ export function to_int(v, dflt, lo, hi) {
|
|||||||
/* ---------- the settings section ---------- */
|
/* ---------- the settings section ---------- */
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets
|
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | targets
|
||||||
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
|
* 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.
|
* min/max: ints; values: enums; msg: the error for a bad value.
|
||||||
*/
|
*/
|
||||||
export const SETTINGS = {
|
export const SETTINGS = {
|
||||||
portal_enabled: { type: 'bool', dflt: false, restart: true },
|
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_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
|
||||||
portal_alt: { type: 'hosts', dflt: [], restart: true },
|
portal_alt: { type: 'hosts', dflt: [], restart: true, msg: 'Other addresses must be hostnames or IP addresses.' },
|
||||||
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
|
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).' },
|
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_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
|
||||||
portal_cert: { type: 'file', dflt: '', restart: true },
|
portal_cert: { type: 'file', dflt: '', restart: true },
|
||||||
portal_key: { 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.' },
|
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' },
|
||||||
hostnames: { type: 'bool', dflt: true },
|
hostnames: { type: 'bool', dflt: true },
|
||||||
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
|
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
|
||||||
geo_enabled: { type: 'bool', dflt: true },
|
// Off until the admin turns it on: lookups send people's addresses to a third party.
|
||||||
|
geo_enabled: { type: 'bool', dflt: false },
|
||||||
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
|
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
|
||||||
log_connections: { type: 'bool', dflt: true },
|
log_connections: { type: 'bool', dflt: true },
|
||||||
watchdog: { type: 'bool', dflt: true },
|
watchdog: { type: 'bool', dflt: true },
|
||||||
@@ -164,9 +164,13 @@ export function validate(key, val) {
|
|||||||
let t = spec.type;
|
let t = spec.type;
|
||||||
if (t == 'hosts') {
|
if (t == 'hosts') {
|
||||||
let lst = [];
|
let lst = [];
|
||||||
for (let x in (type(val) == 'array' ? val : []))
|
for (let x in (type(val) == 'array' ? val : [])) {
|
||||||
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0)
|
// A typo must not vanish on Save: refused, like the main address.
|
||||||
|
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
|
||||||
|
bad(spec, key);
|
||||||
|
if (trim(x) != '' && index(lst, trim(x)) < 0)
|
||||||
push(lst, trim(x));
|
push(lst, trim(x));
|
||||||
|
}
|
||||||
return length(lst) ? lst : null;
|
return length(lst) ? lst : null;
|
||||||
}
|
}
|
||||||
if (t == 'targets') {
|
if (t == 'targets') {
|
||||||
@@ -221,10 +225,6 @@ export function validate(key, val) {
|
|||||||
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
|
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
|
||||||
bad(spec, key);
|
bad(spec, key);
|
||||||
}
|
}
|
||||||
else if (t == 'text') {
|
|
||||||
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
|
|
||||||
bad(spec, key);
|
|
||||||
}
|
|
||||||
return val;
|
return val;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,14 @@ import * as core from 'dawnline.core';
|
|||||||
/** Section names that are never ids of people, devices, servers, services or circles. */
|
/** Section names that are never ids of people, devices, servers, services or circles. */
|
||||||
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
|
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
|
||||||
|
|
||||||
/** Commit the dawnline config and keep it readable by root only. */
|
/**
|
||||||
|
* Commit the dawnline config and keep it readable by root only. A commit
|
||||||
|
* that did not reach flash (full or read-only overlay) is an error: the
|
||||||
|
* caller's change never happened, and nothing downstream may act on it.
|
||||||
|
*/
|
||||||
export function commit(c) {
|
export function commit(c) {
|
||||||
c.commit(core.CONFIG);
|
if (!c.commit(core.CONFIG))
|
||||||
|
die(`Couldn't save /etc/config/dawnline: ${c.error() ?? 'the write failed'}. Is the flash full?`);
|
||||||
system('chmod 600 /etc/config/dawnline');
|
system('chmod 600 /etc/config/dawnline');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -115,8 +115,11 @@ export function install(ctx, arg) {
|
|||||||
out.to = replace(tag, /^v/, '');
|
out.to = replace(tag, /^v/, '');
|
||||||
ctx.versions(VERSION, out.to);
|
ctx.versions(VERSION, out.to);
|
||||||
let f = fetch(ctx, tag, ctx.work);
|
let f = fetch(ctx, tag, ctx.work);
|
||||||
// The version being replaced, for Roll back (downloaded again: opkg keeps no package files).
|
// The version being replaced, for Roll back (downloaded again: opkg keeps
|
||||||
if (ctx.pol.keep && out.to != VERSION && upd.kept('app')?.version != VERSION) {
|
// no package files). Always for an automatic run: nobody is there to
|
||||||
|
// recover a router whose new version does not come up (postupdate rolls
|
||||||
|
// back to it on its own).
|
||||||
|
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
|
||||||
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
|
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
|
||||||
try {
|
try {
|
||||||
system(`mkdir -p '${ctx.work}/keep'`);
|
system(`mkdir -p '${ctx.work}/keep'`);
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ export function check(ctx) {
|
|||||||
if (!fw)
|
if (!fw)
|
||||||
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
|
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
|
||||||
note: 'Cannot detect the firmware target' };
|
note: 'Cannot detect the firmware target' };
|
||||||
|
if (fw.snapshot)
|
||||||
|
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
|
||||||
|
note: 'This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only' };
|
||||||
let dir = `${ctx.work}/check`;
|
let dir = `${ctx.work}/check`;
|
||||||
system(`mkdir -p '${dir}'`);
|
system(`mkdir -p '${dir}'`);
|
||||||
let sources = {};
|
let sources = {};
|
||||||
@@ -114,8 +117,14 @@ function reload_module(ctx, before, after) {
|
|||||||
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
||||||
sh(`ifdown '${i}'`);
|
sh(`ifdown '${i}'`);
|
||||||
}
|
}
|
||||||
sh('rmmod amneziawg');
|
// Both steps must really happen: the new tools against the old module (or
|
||||||
|
// no module at all) leave every tunnel down while the job says "done".
|
||||||
|
ctx.run('rmmod amneziawg');
|
||||||
|
if (stat('/sys/module/amneziawg'))
|
||||||
|
die('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update');
|
||||||
ctx.run('modprobe amneziawg');
|
ctx.run('modprobe amneziawg');
|
||||||
|
if (!stat('/sys/module/amneziawg'))
|
||||||
|
die("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)");
|
||||||
for (let i in ifaces)
|
for (let i in ifaces)
|
||||||
sh(`ifup '${i}'`);
|
sh(`ifup '${i}'`);
|
||||||
}
|
}
|
||||||
@@ -227,5 +236,6 @@ export function install(ctx, arg) {
|
|||||||
pkg.remove([ builds.RU ], ctx.log);
|
pkg.remove([ builds.RU ], ctx.log);
|
||||||
out.after = builds.installed();
|
out.after = builds.installed();
|
||||||
settle(ctx, before, out.after);
|
settle(ctx, before, out.after);
|
||||||
|
builds.record(id, fw.tag, out.after);
|
||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||||
|
|
||||||
export const VERSION = '0.4.2';
|
export const VERSION = '0.10.0';
|
||||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||||
export const REPO = 'tickcount/luci-app-dawnline';
|
export const REPO = 'tickcount/luci-app-dawnline';
|
||||||
export const RUN_DIR = '/var/run/dawnline';
|
export const RUN_DIR = '/var/run/dawnline';
|
||||||
@@ -273,19 +273,31 @@ const INTENT = `${RUN_DIR}/iface-intent.json`;
|
|||||||
|
|
||||||
export function iface_intent(ifname, reason, name) {
|
export function iface_intent(ifname, reason, name) {
|
||||||
let all = read_json(INTENT, {});
|
let all = read_json(INTENT, {});
|
||||||
all[ifname] = { reason, name, ts: time() };
|
let now = time();
|
||||||
|
for (let k, v in all)
|
||||||
|
if (now - v.ts >= 120)
|
||||||
|
delete all[k];
|
||||||
|
all[ifname] = { reason, name, ts: now };
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
write_json(INTENT, all, 0o600);
|
write_json(INTENT, all, 0o600);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The note for a stop of `ifname`, or null. netifd may report one stop more
|
||||||
|
* than once (the interface, then its device): the note covers every report
|
||||||
|
* within 15 s of the first, then it is spent.
|
||||||
|
*/
|
||||||
export function take_iface_intent(ifname) {
|
export function take_iface_intent(ifname) {
|
||||||
let all = read_json(INTENT, {});
|
let all = read_json(INTENT, {});
|
||||||
let it = all[ifname];
|
let it = all[ifname];
|
||||||
if (!it)
|
let now = time();
|
||||||
|
if (!it || now - it.ts >= 120 || (it.used && now - it.used >= 15))
|
||||||
return null;
|
return null;
|
||||||
delete all[ifname];
|
if (!it.used) {
|
||||||
write_json(INTENT, all, 0o600);
|
it.used = now;
|
||||||
return time() - it.ts < 120 ? it : null;
|
write_json(INTENT, all, 0o600);
|
||||||
|
}
|
||||||
|
return it;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Newest first. */
|
/** Newest first. */
|
||||||
@@ -443,38 +455,151 @@ export function in_cidr(ip, c) {
|
|||||||
return n != null && n >= c.net && n < c.net + c.size;
|
return n != null && n >= c.net && n < c.net + c.size;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* ---------- text ---------- */
|
||||||
|
|
||||||
|
/** Characters in a UTF-8 string (length() counts bytes: "Мама" is 8 of them). */
|
||||||
|
export function ulength(s) {
|
||||||
|
let n = 0;
|
||||||
|
for (let i = 0; i < length(s); i++)
|
||||||
|
if ((ord(s, i) & 0xc0) != 0x80)
|
||||||
|
n++;
|
||||||
|
return n;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The first `n` characters of a UTF-8 string, never cut inside one. */
|
||||||
|
export function ucut(s, n) {
|
||||||
|
let i = 0, c = 0;
|
||||||
|
while (i < length(s)) {
|
||||||
|
if ((ord(s, i) & 0xc0) != 0x80) {
|
||||||
|
if (c == n)
|
||||||
|
break;
|
||||||
|
c++;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return substr(s, 0, i);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cyrillic (Russian, Ukrainian) to Latin: а-я by code point from U+0430, then
|
||||||
|
// ё, і, ї, є, ґ; the rest of a string passes as it is.
|
||||||
|
const CYR_A = 0x430;
|
||||||
|
const CYRILLIC = [ 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
|
||||||
|
'f', 'kh', 'ts', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya' ];
|
||||||
|
const CYRILLIC_MORE = { '1105': 'yo', '1110': 'i', '1111': 'yi', '1108': 'ye', '1169': 'g' };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cyrillic letters written in Latin ("Мама" → "mama", "Юля" → "yulya"):
|
||||||
|
* ids, hostnames and file names are ASCII, and a person should recognise
|
||||||
|
* their own in them. Other characters are left alone.
|
||||||
|
*/
|
||||||
|
export function translit(s) {
|
||||||
|
let out = '', i = 0, n = length(s);
|
||||||
|
while (i < n) {
|
||||||
|
let b = ord(s, i);
|
||||||
|
if (b < 0x80) {
|
||||||
|
out += substr(s, i, 1);
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let cp = 0, len = 1;
|
||||||
|
if ((b & 0xe0) == 0xc0 && i + 1 < n) {
|
||||||
|
cp = ((b & 0x1f) << 6) | (ord(s, i + 1) & 0x3f);
|
||||||
|
len = 2;
|
||||||
|
}
|
||||||
|
else if ((b & 0xf0) == 0xe0 && i + 2 < n) {
|
||||||
|
cp = ((b & 0x0f) << 12) | ((ord(s, i + 1) & 0x3f) << 6) | (ord(s, i + 2) & 0x3f);
|
||||||
|
len = 3;
|
||||||
|
}
|
||||||
|
else if ((b & 0xf8) == 0xf0 && i + 3 < n)
|
||||||
|
len = 4;
|
||||||
|
// Upper case to lower: А-Я, Ё, І, Ї, Є, Ґ.
|
||||||
|
if (cp >= 0x410 && cp <= 0x42f)
|
||||||
|
cp += 0x20;
|
||||||
|
else if (cp == 0x401)
|
||||||
|
cp = 0x451;
|
||||||
|
else if (cp == 0x406)
|
||||||
|
cp = 0x456;
|
||||||
|
else if (cp == 0x407)
|
||||||
|
cp = 0x457;
|
||||||
|
else if (cp == 0x404)
|
||||||
|
cp = 0x454;
|
||||||
|
else if (cp == 0x490)
|
||||||
|
cp = 0x491;
|
||||||
|
let t = cp >= CYR_A && cp < CYR_A + length(CYRILLIC) ? CYRILLIC[cp - CYR_A] : CYRILLIC_MORE[`${cp}`];
|
||||||
|
out += t != null ? t : substr(s, i, len);
|
||||||
|
i += len;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
/* ---------- validation ---------- */
|
/* ---------- validation ---------- */
|
||||||
|
|
||||||
export function valid_slug(s) {
|
export function valid_slug(s) {
|
||||||
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
|
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** A name people see: 1-48 characters (not bytes), none of < > " \ or control characters. */
|
||||||
export function valid_name(s) {
|
export function valid_name(s) {
|
||||||
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
|
return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** What valid_name wants, for the admin. */
|
||||||
|
export const NAME_RULE = 'Enter a name: up to 48 characters, without < > " or \\.';
|
||||||
|
|
||||||
export function valid_key(s) {
|
export function valid_key(s) {
|
||||||
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** An IPv6 address in its usual spelling (no zone, no brackets). */
|
||||||
|
export function is_ip6(s) {
|
||||||
|
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
|
||||||
|
};
|
||||||
|
|
||||||
export function valid_host(s) {
|
export function valid_host(s) {
|
||||||
return type(s) == 'string' && length(s) <= 253 &&
|
return type(s) == 'string' && length(s) <= 253 &&
|
||||||
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
|
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
|
||||||
ip2int(s) != null || match(s, /^[0-9a-fA-F:]+$/) != null);
|
ip2int(s) != null || is_ip6(s));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
|
||||||
export function valid_date(s) {
|
export function valid_date(s) {
|
||||||
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null;
|
let m = type(s) == 'string' ? match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) : null;
|
||||||
|
if (!m)
|
||||||
|
return false;
|
||||||
|
let l = localtime(timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 12, min: 0, sec: 0 }));
|
||||||
|
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Turn a display name into a portal slug candidate. */
|
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
|
||||||
export function slugify(s) {
|
export function slugify(s) {
|
||||||
let out = lc(trim(`${s ?? ''}`));
|
let out = lc(translit(trim(`${s ?? ''}`)));
|
||||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||||
out = replace(out, /^-+|-+$/g, '');
|
out = replace(out, /^-+|-+$/g, '');
|
||||||
return substr(out, 0, 32) || 'user';
|
return substr(out, 0, 32) || 'user';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A device's name as a DNS label ("Galaxy S24" → "galaxy-s24", "Телефон" →
|
||||||
|
* "telefon"): at most 40 characters, "device" when nothing is left.
|
||||||
|
*/
|
||||||
|
export function host_label(s) {
|
||||||
|
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
|
||||||
|
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
|
||||||
|
return l || 'device';
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A server's name as a tunnel name ("Outline Home" → "Outline-Home"): the
|
||||||
|
* AmneziaWG and WireGuard apps name the tunnel after the file, and Android and
|
||||||
|
* wg-quick refuse anything but [a-zA-Z0-9_=+.-] up to 15 characters; Windows
|
||||||
|
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
|
||||||
|
*/
|
||||||
|
export function tunnel_name(s) {
|
||||||
|
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
|
||||||
|
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
|
||||||
|
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
|
||||||
|
};
|
||||||
|
|
||||||
/* ---------- time ---------- */
|
/* ---------- time ---------- */
|
||||||
|
|
||||||
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ export function spark(rec, n) {
|
|||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Daily totals (rx+tx) from the 1st of this month to today, oldest first (the portal's month chart). */
|
||||||
|
export function month_days(rec) {
|
||||||
|
return spark(rec, +substr(day_key_ago(0), 8, 2));
|
||||||
|
};
|
||||||
|
|
||||||
/** The device holds an older configuration than the one it would get now. */
|
/** The device holds an older configuration than the one it would get now. */
|
||||||
function config_stale(m, d) {
|
function config_stale(m, d) {
|
||||||
m._issued ??= awg.issued();
|
m._issued ??= awg.issued();
|
||||||
@@ -23,12 +28,43 @@ function config_stale(m, d) {
|
|||||||
return was != null && was != awg.config_fingerprint(m, d);
|
return was != null && was != awg.config_fingerprint(m, d);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The device a page request came from (`devs`: one person's device views):
|
||||||
|
* through the tunnel, by its tunnel address; outside it, the one online device
|
||||||
|
* whose tunnel comes from the request's address. The apps route the VPN's own
|
||||||
|
* address around their tunnel, and the portal shares it, so a device on the VPN
|
||||||
|
* opens the page from where its tunnel comes from. Two such devices behind one
|
||||||
|
* address (one NAT): neither.
|
||||||
|
*/
|
||||||
|
export function device_here(devs, peer) {
|
||||||
|
peer = replace(peer ?? '', /^::ffff:/, '');
|
||||||
|
if (!peer)
|
||||||
|
return null;
|
||||||
|
let near = [];
|
||||||
|
for (let d in devs) {
|
||||||
|
if (d.address == peer)
|
||||||
|
return d.id;
|
||||||
|
if (d.online && d.endpoint == peer)
|
||||||
|
push(near, d.id);
|
||||||
|
}
|
||||||
|
return length(near) == 1 ? near[0] : null;
|
||||||
|
};
|
||||||
|
|
||||||
export function device_view(m, d, usage, dmp) {
|
export function device_view(m, d, usage, dmp) {
|
||||||
let u = usage.devices?.[d.id];
|
let u = usage.devices?.[d.id];
|
||||||
let peer = dmp.peers[d.public_key];
|
let peer = dmp.peers[d.public_key];
|
||||||
let ts = time();
|
let ts = time();
|
||||||
let hs = peer?.handshake || u?.handshake || 0;
|
// Set up again (Reconnect): a handshake from before it does not count.
|
||||||
|
m._reconnect ??= awg.reconnects();
|
||||||
|
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
|
||||||
let p = m.people[d.person];
|
let p = m.people[d.person];
|
||||||
|
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
|
||||||
|
let label = '';
|
||||||
|
if (m.settings.hostnames && p) {
|
||||||
|
m._labels ??= {};
|
||||||
|
m._labels[p.id] ??= core.device_labels(m, p);
|
||||||
|
label = m._labels[p.id][d.id] ?? 'device';
|
||||||
|
}
|
||||||
let v = {
|
let v = {
|
||||||
id: d.id,
|
id: d.id,
|
||||||
name: d.name,
|
name: d.name,
|
||||||
@@ -37,14 +73,14 @@ export function device_view(m, d, usage, dmp) {
|
|||||||
disabled: d.disabled,
|
disabled: d.disabled,
|
||||||
created: d.created,
|
created: d.created,
|
||||||
created_by: d.created_by,
|
created_by: d.created_by,
|
||||||
online: live.online(dmp, d.id, peer),
|
online: hs > 0 && live.online(dmp, d.id, peer),
|
||||||
handshake: hs,
|
handshake: hs,
|
||||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||||
active: !!peer,
|
active: !!peer,
|
||||||
month: live.month(u),
|
month: live.month(u),
|
||||||
total: u?.total ?? [ 0, 0 ],
|
total: u?.total ?? [ 0, 0 ],
|
||||||
spark: spark(u, 7),
|
spark: spark(u, 7),
|
||||||
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '',
|
hostname: label ? `${label}.${p.id}.${m.settings.domain}` : '',
|
||||||
browser_key: d.private_key == '',
|
browser_key: d.private_key == '',
|
||||||
// Its configuration changed since it was last shown or downloaded.
|
// Its configuration changed since it was last shown or downloaded.
|
||||||
config_stale: config_stale(m, d),
|
config_stale: config_stale(m, d),
|
||||||
@@ -96,6 +132,7 @@ export function person_view(m, p, usage, dmp, states, opts) {
|
|||||||
v.home_nets = p.home_nets;
|
v.home_nets = p.home_nets;
|
||||||
v.circle = p.circle;
|
v.circle = p.circle;
|
||||||
v.created = p.created;
|
v.created = p.created;
|
||||||
|
v.code_set = p.code_set;
|
||||||
}
|
}
|
||||||
return v;
|
return v;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,12 +12,16 @@ import * as health from 'dawnline.health';
|
|||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
import * as nft from 'dawnline.nft';
|
import * as nft from 'dawnline.nft';
|
||||||
import * as netifd from 'dawnline.netifd';
|
import * as netifd from 'dawnline.netifd';
|
||||||
|
import * as upd from 'dawnline.updates';
|
||||||
|
|
||||||
export const STATE = `${RUN_DIR}/watchdog.json`;
|
export const STATE = `${RUN_DIR}/watchdog.json`;
|
||||||
/** The agent writes the time here on every tick. */
|
/** The agent writes the time here on every tick. */
|
||||||
export const BEAT = `${RUN_DIR}/agent.beat`;
|
export const BEAT = `${RUN_DIR}/agent.beat`;
|
||||||
// Seconds before the next repair, by the number of repairs so far.
|
// Seconds before the next repair, by the number of repairs so far.
|
||||||
const WAIT = [ 0, 120, 600, 1800, 3600 ];
|
const WAIT = [ 0, 120, 600, 1800, 3600 ];
|
||||||
|
// Good minutes in a row before a repaired target's count of repairs is
|
||||||
|
// forgotten: one good minute between two failures is still flapping.
|
||||||
|
const SETTLED = 10;
|
||||||
|
|
||||||
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
|
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
|
||||||
export function iface_errors(ifname) {
|
export function iface_errors(ifname) {
|
||||||
@@ -65,7 +69,8 @@ function probes(m) {
|
|||||||
repair: { what: 'restarting it', run: restart_services },
|
repair: { what: 'restarting it', run: restart_services },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (stat(loop.RESOLVER.conf))
|
// Only while a server is on: with all of them off it idles on loopback.
|
||||||
|
if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key)))
|
||||||
push(out, {
|
push(out, {
|
||||||
id: 'resolver', src: 'dawnline', name: 'Resolver', who: 'DNS for Home-only devices', ok: loop.resolver_running(),
|
id: 'resolver', src: 'dawnline', name: 'Resolver', who: 'DNS for Home-only devices', ok: loop.resolver_running(),
|
||||||
problem: "isn't running", back: 'runs again',
|
problem: "isn't running", back: 'runs again',
|
||||||
@@ -76,8 +81,10 @@ function probes(m) {
|
|||||||
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
|
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
|
||||||
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
|
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
|
||||||
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
|
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
|
||||||
// A reload keeps LuCI logins; a restart (second try) signs everyone out.
|
// A reload keeps LuCI logins; a restart (second try) signs everyone out —
|
||||||
repair: { what: 'reloading rpcd', run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
|
// and after three it stops: restarting rpcd every hour for good would
|
||||||
|
// sign every admin out for good.
|
||||||
|
repair: { what: 'reloading rpcd', max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
|
||||||
});
|
});
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -86,6 +93,9 @@ function probes(m) {
|
|||||||
export function run(m) {
|
export function run(m) {
|
||||||
let now = time();
|
let now = time();
|
||||||
let fix = m.settings.watchdog;
|
let fix = m.settings.watchdog;
|
||||||
|
// An update is replacing packages or restarting tunnels: what looks broken
|
||||||
|
// meanwhile is being worked on; repairs would only get in its way.
|
||||||
|
let busy = upd.busy();
|
||||||
let st = read_json(STATE, {});
|
let st = read_json(STATE, {});
|
||||||
let t = type(st.targets) == 'object' ? st.targets : {};
|
let t = type(st.targets) == 'object' ? st.targets : {};
|
||||||
let repairs = filter(st.repairs ?? [], (r) => now - r.ts < 86400);
|
let repairs = filter(st.repairs ?? [], (r) => now - r.ts < 86400);
|
||||||
@@ -99,16 +109,30 @@ export function run(m) {
|
|||||||
if (x.reported)
|
if (x.reported)
|
||||||
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
|
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
|
||||||
x.bad = 0;
|
x.bad = 0;
|
||||||
x.tries = 0;
|
|
||||||
x.next = 0;
|
x.next = 0;
|
||||||
x.reported = false;
|
x.reported = false;
|
||||||
x.stuck = false;
|
x.stuck = false;
|
||||||
|
// The repairs so far are forgotten only once it has stayed up a while:
|
||||||
|
// a target that fails every other minute keeps its back-off.
|
||||||
|
x.good = (x.good ?? 0) + 1;
|
||||||
|
if (x.good >= SETTLED) {
|
||||||
|
x.tries = 0;
|
||||||
|
x.good = 0;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
x.good = 0;
|
||||||
// One bad minute can be a restart in progress.
|
// One bad minute can be a restart in progress.
|
||||||
if (++x.bad < 2)
|
if (++x.bad < 2)
|
||||||
continue;
|
continue;
|
||||||
if (!fix || !p.repair) {
|
if (busy)
|
||||||
|
continue;
|
||||||
|
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
|
||||||
|
slog(p.src, 'error', `${p.problem} — not repaired again (${p.repair.max} repairs didn't help)`, p.detail?.(), p.who);
|
||||||
|
x.reported = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!fix || !p.repair || (p.repair.max && x.tries >= p.repair.max)) {
|
||||||
if (!x.reported)
|
if (!x.reported)
|
||||||
slog(p.src, 'error', p.problem, p.detail?.(), p.who);
|
slog(p.src, 'error', p.problem, p.detail?.(), p.who);
|
||||||
x.reported = true;
|
x.reported = true;
|
||||||
|
|||||||
@@ -27,4 +27,5 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
|
|||||||
|
|
||||||
## Checks
|
## Checks
|
||||||
|
|
||||||
- `scripts/lint-ucode.py` and `scripts/check-ucode.sh` (compiles on the router) pass before any deploy; new directories and entry points are added to both, and executables to the mode check in `.github/workflows/ci.yml`.
|
- `scripts/lint-ucode.py` and `scripts/ucode-container.sh` (compiles and runs `tests/ucode` in the OpenWrt rootfs containers; `scripts/check-ucode.sh` compiles on the router instead) pass before any deploy; new directories and entry points are added to `lint-ucode.py` and `scripts/compile-ucode.sh`, and executables to the mode check in `.github/workflows/ci.yml`.
|
||||||
|
- Pure functions get a case in `tests/ucode/<module>.test.uc`; what reads the clock takes an optional `ts` so a test can pass one.
|
||||||
@@ -19,9 +19,9 @@ grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/pack
|
|||||||
mkdir -p "$STAGE/www" "$OUT"
|
mkdir -p "$STAGE/www" "$OUT"
|
||||||
cp -R "$APP/root/." "$STAGE/"
|
cp -R "$APP/root/." "$STAGE/"
|
||||||
cp -R "$APP/htdocs/." "$STAGE/www/"
|
cp -R "$APP/htdocs/." "$STAGE/www/"
|
||||||
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" \
|
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \
|
||||||
"$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \
|
"$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \
|
||||||
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal"
|
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc"
|
||||||
find "$STAGE" -name '.DS_Store' -delete
|
find "$STAGE" -name '.DS_Store' -delete
|
||||||
|
|
||||||
TAR="$OUT/luci-app-dawnline-$VERSION.tar.gz"
|
TAR="$OUT/luci-app-dawnline-$VERSION.tar.gz"
|
||||||
|
|||||||
@@ -0,0 +1,393 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Capture the raw README screenshots from a live router into
|
||||||
|
// docs/screenshots/raw/<name>.png (2x PNG); scripts/frame-screenshots.py then
|
||||||
|
// puts them into a browser window for the README.
|
||||||
|
//
|
||||||
|
// Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome
|
||||||
|
// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with
|
||||||
|
// the password from LUCI_PASSWORD or asked on the terminal; the session lives
|
||||||
|
// only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed.
|
||||||
|
//
|
||||||
|
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
|
||||||
|
// [--mask real=shown ...] [--name real=shown ...]
|
||||||
|
// [--only overview,people] [--demo]
|
||||||
|
//
|
||||||
|
// --mask replaces text on every page before the capture (a domain, a name);
|
||||||
|
// --name does the same for a person's name in any case, and for their initials.
|
||||||
|
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
|
||||||
|
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
|
||||||
|
// the router's answers are rewritten in the headless browser on their way to the page.
|
||||||
|
|
||||||
|
import { execFileSync, spawn } from 'node:child_process';
|
||||||
|
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { dirname, join, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createInterface } from 'node:readline';
|
||||||
|
import { demoRpc } from './screenshot-demo.mjs';
|
||||||
|
|
||||||
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
|
||||||
|
const SCALE = 2;
|
||||||
|
|
||||||
|
const args = {
|
||||||
|
router: 'https://outline.lan',
|
||||||
|
person: '',
|
||||||
|
mask: [],
|
||||||
|
names: [],
|
||||||
|
only: [],
|
||||||
|
demo: false,
|
||||||
|
};
|
||||||
|
for (let i = 2; i < process.argv.length; i++) {
|
||||||
|
const a = process.argv[i];
|
||||||
|
const v = () => process.argv[++i] ?? die(`${a} needs a value`);
|
||||||
|
if (a === '--router') args.router = v().replace(/\/+$/, '');
|
||||||
|
else if (a === '--person') args.person = v();
|
||||||
|
else if (a === '--mask') args.mask.push(v().split('=', 2));
|
||||||
|
else if (a === '--name') args.names.push(v().split('=', 2));
|
||||||
|
else if (a === '--only') args.only = v().split(',');
|
||||||
|
else if (a === '--demo') args.demo = true;
|
||||||
|
else die(`unknown argument ${a}`);
|
||||||
|
}
|
||||||
|
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
|
||||||
|
|
||||||
|
/** As shared/format initials(): first letters of the first and last word, or the first two of one word. */
|
||||||
|
const initials = (name) => {
|
||||||
|
const p = name.trim().split(/\s+/);
|
||||||
|
return (p[0][0] + (p.length > 1 ? p[p.length - 1][0] : (p[0][1] ?? ''))).toUpperCase();
|
||||||
|
};
|
||||||
|
for (const [real, shown] of args.names)
|
||||||
|
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
|
||||||
|
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
|
||||||
|
|
||||||
|
function die(msg) {
|
||||||
|
console.error(msg);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
|
||||||
|
const USER = process.env.LUCI_USER || 'root';
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Each shot: the page, what must be on it before the capture, what to do
|
||||||
|
* first (in the page), and the area to keep (in the page, CSS pixels).
|
||||||
|
* Admin pages keep the theme's header and the content column, 48px either side.
|
||||||
|
*/
|
||||||
|
const column = `(() => {
|
||||||
|
const r = document.querySelector('.dl-root').getBoundingClientRect();
|
||||||
|
return { x: r.left - 48, w: r.width + 96 };
|
||||||
|
})()`;
|
||||||
|
// From the top down to an element; whatever follows it is hidden, not cut through.
|
||||||
|
const below = (sel) => `(() => {
|
||||||
|
const c = ${column}, el = document.querySelector(${JSON.stringify(sel)});
|
||||||
|
for (let e = el; e && !e.classList.contains('dl-root'); e = e.parentElement)
|
||||||
|
for (let n = e.nextElementSibling; n; n = n.nextElementSibling) n.style.visibility = 'hidden';
|
||||||
|
return { x: c.x, y: 0, width: c.w, height: el.getBoundingClientRect().bottom + 40 };
|
||||||
|
})()`;
|
||||||
|
|
||||||
|
const SHOTS = [
|
||||||
|
{
|
||||||
|
name: 'overview',
|
||||||
|
url: () => `${LUCI}/server`,
|
||||||
|
width: 1400,
|
||||||
|
ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas',
|
||||||
|
// The map shows the last 30 days, not only who is online now.
|
||||||
|
prep: `(() => {
|
||||||
|
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days');
|
||||||
|
b?.click();
|
||||||
|
})()`,
|
||||||
|
settle: 6000,
|
||||||
|
clip: below('.dl-srvov .dl-panel.flush'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'people',
|
||||||
|
url: () => `${LUCI}/server?section=people`,
|
||||||
|
width: 1400,
|
||||||
|
ready: '.dl-srvbody a[href*="dawnline/person"]',
|
||||||
|
clip: below('.dl-srvbody'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'person',
|
||||||
|
url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`,
|
||||||
|
width: 1400,
|
||||||
|
ready: '.dl-grid-person .dl-row',
|
||||||
|
// Where they connected from, on the map.
|
||||||
|
prep: `(() => {
|
||||||
|
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
|
||||||
|
b?.click();
|
||||||
|
})()`,
|
||||||
|
settle: 6000,
|
||||||
|
// Down to the end of Access & limits or of the map, whichever is lower; activity rows that would be cut are hidden.
|
||||||
|
clip: `(() => {
|
||||||
|
const c = ${column}, cols = document.querySelectorAll('.dl-grid-person > .dl-col');
|
||||||
|
const places = cols[0].children[2];
|
||||||
|
const cut = Math.max(cols[1].getBoundingClientRect().bottom, places ? places.getBoundingClientRect().bottom : 0) + 40;
|
||||||
|
document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => {
|
||||||
|
if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden';
|
||||||
|
});
|
||||||
|
// Activity that would start right at the cut goes too, its heading with it.
|
||||||
|
const act = cols[0].children[3];
|
||||||
|
if (act && act.getBoundingClientRect().top > cut - 120) act.style.visibility = 'hidden';
|
||||||
|
return { x: c.x, y: 0, width: c.w, height: cut };
|
||||||
|
})()`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'portal',
|
||||||
|
url: (s) => s.portal,
|
||||||
|
width: 1320,
|
||||||
|
ready: 'body',
|
||||||
|
settle: 3000,
|
||||||
|
// The content: everything but full-width or full-height wrappers, 36px around it.
|
||||||
|
clip: `(() => {
|
||||||
|
let l = innerWidth, r = 0, b = 0;
|
||||||
|
for (const e of document.body.querySelectorAll('*')) {
|
||||||
|
const x = e.getBoundingClientRect();
|
||||||
|
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
|
||||||
|
l = Math.min(l, x.left);
|
||||||
|
r = Math.max(r, x.right);
|
||||||
|
b = Math.max(b, x.bottom);
|
||||||
|
}
|
||||||
|
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
|
||||||
|
})()`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const MASK = `((pairs, inits) => {
|
||||||
|
const doc = new Map();
|
||||||
|
const isPrivate = (a) => a[0] === 10 || a[0] === 127 || (a[0] === 172 && a[1] >= 16 && a[1] < 32) ||
|
||||||
|
(a[0] === 192 && a[1] === 168) || (a[0] === 100 && a[1] >= 64 && a[1] < 128) || a[0] === 0 || a[0] >= 224;
|
||||||
|
const ip = (m) => {
|
||||||
|
const a = m.split('.').map(Number);
|
||||||
|
if (a.some((x) => x > 255) || isPrivate(a)) return m;
|
||||||
|
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
|
||||||
|
return doc.get(m);
|
||||||
|
};
|
||||||
|
// IPv6 too, unless link-local or private (fe80::, fc00::/7).
|
||||||
|
const ip6 = (m) => {
|
||||||
|
if (/^(fe8|fe9|fea|feb|fc|fd)/i.test(m)) return m;
|
||||||
|
if (!doc.has(m)) doc.set(m, '2001:db8::' + (24 + doc.size));
|
||||||
|
return doc.get(m);
|
||||||
|
};
|
||||||
|
const swap = (s) =>
|
||||||
|
pairs
|
||||||
|
.reduce((t, [a, b]) => t.split(a).join(b), s)
|
||||||
|
.replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip)
|
||||||
|
.replace(/\\b(?:[0-9a-f]{1,4}:){3,7}[0-9a-f]{1,4}\\b/gi, ip6);
|
||||||
|
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||||
|
for (let n; (n = w.nextNode()); ) {
|
||||||
|
const ini = inits.find(([a]) => n.nodeValue.trim() === a);
|
||||||
|
const v = ini ? n.nodeValue.replace(ini[0], ini[1]) : swap(n.nodeValue);
|
||||||
|
if (v !== n.nodeValue) n.nodeValue = v;
|
||||||
|
}
|
||||||
|
document.querySelectorAll('input').forEach((i) => { const v = swap(i.value); if (v !== i.value) i.value = v; });
|
||||||
|
})(${JSON.stringify(args.mask)}, ${JSON.stringify(INITIALS)})`;
|
||||||
|
|
||||||
|
async function password() {
|
||||||
|
if (process.env.LUCI_PASSWORD) return process.env.LUCI_PASSWORD;
|
||||||
|
if (!process.stdin.isTTY) die('Set LUCI_PASSWORD or run on a terminal');
|
||||||
|
process.stdout.write(`LuCI password for ${USER}: `);
|
||||||
|
execFileSync('stty', ['-echo'], { stdio: 'inherit' });
|
||||||
|
try {
|
||||||
|
const rl = createInterface({ input: process.stdin });
|
||||||
|
const line = await new Promise((ok) => rl.once('line', ok));
|
||||||
|
rl.close();
|
||||||
|
return line.replace(/\r$/, '');
|
||||||
|
} finally {
|
||||||
|
execFileSync('stty', ['echo'], { stdio: 'inherit' });
|
||||||
|
process.stdout.write('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findBrowser() {
|
||||||
|
const c = [
|
||||||
|
process.env.BROWSER,
|
||||||
|
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
||||||
|
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||||
|
'/usr/bin/chromium',
|
||||||
|
'/usr/bin/google-chrome',
|
||||||
|
];
|
||||||
|
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A page over the DevTools protocol: send(method, params) and waitFor(event). */
|
||||||
|
async function connect(wsUrl) {
|
||||||
|
const ws = new WebSocket(wsUrl);
|
||||||
|
await new Promise((ok, fail) => {
|
||||||
|
ws.onopen = ok;
|
||||||
|
ws.onerror = fail;
|
||||||
|
});
|
||||||
|
let id = 0;
|
||||||
|
const pending = new Map();
|
||||||
|
const waiters = [];
|
||||||
|
const listeners = [];
|
||||||
|
ws.onmessage = (m) => {
|
||||||
|
const msg = JSON.parse(m.data);
|
||||||
|
if (msg.id && pending.has(msg.id)) {
|
||||||
|
const { ok, fail } = pending.get(msg.id);
|
||||||
|
pending.delete(msg.id);
|
||||||
|
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
||||||
|
} else if (msg.method) {
|
||||||
|
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
|
||||||
|
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
||||||
|
waiters.splice(waiters.indexOf(w), 1);
|
||||||
|
w.ok(msg.params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const send = (method, params = {}) =>
|
||||||
|
new Promise((ok, fail) => {
|
||||||
|
pending.set(++id, { ok, fail });
|
||||||
|
ws.send(JSON.stringify({ id, method, params }));
|
||||||
|
});
|
||||||
|
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
||||||
|
const on = (method, fn) => listeners.push({ method, fn });
|
||||||
|
return { send, waitFor, on, close: () => ws.close() };
|
||||||
|
}
|
||||||
|
|
||||||
|
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const pass = await password();
|
||||||
|
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
|
||||||
|
const chrome = spawn(
|
||||||
|
findBrowser(),
|
||||||
|
[
|
||||||
|
'--headless=new',
|
||||||
|
'--remote-debugging-port=0',
|
||||||
|
`--user-data-dir=${profile}`,
|
||||||
|
// The router's certificate is usually for its public name, not router.lan.
|
||||||
|
'--ignore-certificate-errors',
|
||||||
|
'--hide-scrollbars',
|
||||||
|
'--no-first-run',
|
||||||
|
'--no-default-browser-check',
|
||||||
|
// MapLibre needs WebGL; headless gets it from SwiftShader.
|
||||||
|
'--use-angle=swiftshader',
|
||||||
|
'--enable-unsafe-swiftshader',
|
||||||
|
'about:blank',
|
||||||
|
],
|
||||||
|
{ stdio: 'ignore' },
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const portFile = join(profile, 'DevToolsActivePort');
|
||||||
|
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
|
||||||
|
const port = readFileSync(portFile, 'utf8').split('\n')[0];
|
||||||
|
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||||
|
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
||||||
|
await page.send('Page.enable');
|
||||||
|
await page.send('Emulation.setEmulatedMedia', {
|
||||||
|
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
|
||||||
|
});
|
||||||
|
// The person shown on the Person page; known once People has loaded (or from --person).
|
||||||
|
const s = { person: args.person, portal: '' };
|
||||||
|
if (args.demo) {
|
||||||
|
page.on('Fetch.requestPaused', async (e) => {
|
||||||
|
try {
|
||||||
|
const r = await page.send('Fetch.getResponseBody', {
|
||||||
|
requestId: e.requestId,
|
||||||
|
});
|
||||||
|
const body = r.base64Encoded ? Buffer.from(r.body, 'base64').toString('utf8') : r.body;
|
||||||
|
const out = demoRpc(e.request.postData ?? '', body, s.person);
|
||||||
|
await page.send('Fetch.fulfillRequest', {
|
||||||
|
requestId: e.requestId,
|
||||||
|
responseCode: e.responseStatusCode ?? 200,
|
||||||
|
responseHeaders: e.responseHeaders ?? [],
|
||||||
|
body: Buffer.from(out, 'utf8').toString('base64'),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
await page.send('Fetch.continueRequest', { requestId: e.requestId }).catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await page.send('Fetch.enable', {
|
||||||
|
patterns: [{ urlPattern: '*ubus*', requestStage: 'Response' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const evaluate = async (expression) => {
|
||||||
|
const r = await page.send('Runtime.evaluate', {
|
||||||
|
expression,
|
||||||
|
awaitPromise: true,
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
|
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||||
|
return r.result.value;
|
||||||
|
};
|
||||||
|
const go = async (url) => {
|
||||||
|
const loaded = page.waitFor('Page.loadEventFired');
|
||||||
|
await page.send('Page.navigate', { url });
|
||||||
|
await loaded;
|
||||||
|
};
|
||||||
|
const waitSel = async (sel, ms = 20000) => {
|
||||||
|
for (let t = 0; t < ms; t += 250) {
|
||||||
|
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
|
||||||
|
await sleep(250);
|
||||||
|
}
|
||||||
|
throw new Error(`timed out waiting for ${sel}`);
|
||||||
|
};
|
||||||
|
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
|
||||||
|
const viewport = (width, height = 2600) =>
|
||||||
|
page.send('Emulation.setDeviceMetricsOverride', {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
deviceScaleFactor: SCALE,
|
||||||
|
mobile: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
await viewport(1400);
|
||||||
|
await go(`${args.router}/cgi-bin/luci/`);
|
||||||
|
if (await evaluate(`!!document.querySelector('input[name=luci_password]')`)) {
|
||||||
|
await evaluate(`(() => {
|
||||||
|
document.querySelector('input[name=luci_username]').value = ${JSON.stringify(USER)};
|
||||||
|
document.querySelector('input[name=luci_password]').value = ${JSON.stringify(pass)};
|
||||||
|
})()`);
|
||||||
|
const loaded = page.waitFor('Page.loadEventFired');
|
||||||
|
await evaluate(`document.querySelector('form.login-form, form').submit()`);
|
||||||
|
await loaded;
|
||||||
|
if (await evaluate(`!!document.querySelector('input[name=luci_password]')`))
|
||||||
|
die(
|
||||||
|
(await evaluate(`!!document.querySelector('.login-error')`))
|
||||||
|
? `LuCI login failed: wrong password for ${USER} (LUCI_USER sets the user)`
|
||||||
|
: `LuCI login failed: still on the login page (${await evaluate('location.href')})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The person to show (the first one on People unless --person) and their personal link.
|
||||||
|
await go(`${LUCI}/server?section=people`);
|
||||||
|
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
|
||||||
|
if (!s.person)
|
||||||
|
s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
|
||||||
|
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
|
||||||
|
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
|
||||||
|
.then((r) => r.link ?? r.links?.[0] ?? '')`);
|
||||||
|
|
||||||
|
for (const shot of SHOTS) {
|
||||||
|
if (args.only.length && !args.only.includes(shot.name)) continue;
|
||||||
|
const url = shot.url(s);
|
||||||
|
if (!url) {
|
||||||
|
console.log(`skip ${shot.name}: no URL (the portal is off?)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await viewport(shot.width);
|
||||||
|
await go(url);
|
||||||
|
await waitSel(shot.ready);
|
||||||
|
await sleep(2000);
|
||||||
|
if (shot.prep) await evaluate(shot.prep);
|
||||||
|
await sleep(shot.settle ?? 1500);
|
||||||
|
await evaluate(MASK);
|
||||||
|
const clip = await evaluate(shot.clip);
|
||||||
|
const { data } = await page.send('Page.captureScreenshot', {
|
||||||
|
format: 'png',
|
||||||
|
clip: { ...clip, scale: 1 },
|
||||||
|
captureBeyondViewport: true,
|
||||||
|
});
|
||||||
|
writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64'));
|
||||||
|
console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||||
|
}
|
||||||
|
page.close();
|
||||||
|
} finally {
|
||||||
|
chrome.kill();
|
||||||
|
await sleep(300);
|
||||||
|
rmSync(profile, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => die(e.message));
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Compile-check every ucode file on a router without installing anything:
|
# Compile-check every ucode file on a router without installing anything:
|
||||||
# the tree is unpacked under /tmp/dlc and modules are resolved from there.
|
# the tree is unpacked under /tmp/dlc and scripts/compile-ucode.sh runs there
|
||||||
|
# (the same check CI runs in an OpenWrt rootfs container, scripts/ucode-container.sh).
|
||||||
# scripts/check-ucode.sh [root@host]
|
# scripts/check-ucode.sh [root@host]
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
HOST="${1:-root@outline.lan}"
|
HOST="${1:-root@outline.lan}"
|
||||||
@@ -12,21 +13,6 @@ TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
|
|||||||
python3 "$(dirname "$0")/lint-ucode.py" "$ROOT"
|
python3 "$(dirname "$0")/lint-ucode.py" "$ROOT"
|
||||||
( cd "$ROOT" && COPYFILE_DISABLE=1 tar -czf "$TMP/t.tgz" usr etc )
|
( cd "$ROOT" && COPYFILE_DISABLE=1 tar -czf "$TMP/t.tgz" usr etc )
|
||||||
scp -q "$TMP/t.tgz" "$HOST:/tmp/dl-check.tgz"
|
scp -q "$TMP/t.tgz" "$HOST:/tmp/dl-check.tgz"
|
||||||
ssh "$HOST" sh <<'REMOTE'
|
ssh "$HOST" 'rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz'
|
||||||
rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz
|
# The script goes over stdin (`sh -s`), nothing of it stays on the router.
|
||||||
cd /tmp/dlc
|
ssh "$HOST" 'sh -s /tmp/dlc; rc=$?; rm -rf /tmp/dlc; exit $rc' < "$(dirname "$0")/compile-ucode.sh"
|
||||||
rc=0
|
|
||||||
# Modules by their import name: dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc dawnline.rpc.x.
|
|
||||||
for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do
|
|
||||||
[ -f "$f" ] || continue
|
|
||||||
n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g')
|
|
||||||
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
|
|
||||||
done
|
|
||||||
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
|
|
||||||
[ -f "$f" ] || continue
|
|
||||||
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -c -o /dev/null "$f" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
|
|
||||||
done
|
|
||||||
rm -rf /tmp/dlc
|
|
||||||
[ $rc = 0 ] && echo "all ucode files compile"
|
|
||||||
exit $rc
|
|
||||||
REMOTE
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Compile-check every ucode file of a Dawnline tree without installing it:
|
||||||
|
# modules are imported by name (dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc
|
||||||
|
# dawnline.rpc.x) and entry points compiled with `ucode -c`. Needs ucode with
|
||||||
|
# its fs, uci, ubus and uloop modules, which is any OpenWrt box or an
|
||||||
|
# openwrt/rootfs container (scripts/ucode-container.sh); check-ucode.sh pipes
|
||||||
|
# this script to a router.
|
||||||
|
# scripts/compile-ucode.sh [ROOT] ROOT holds usr/ and etc/ (default: .)
|
||||||
|
#
|
||||||
|
# ucode resolves names at compile time and imports are static, so this catches
|
||||||
|
# a syntax error, a missing module and a named import that nothing exports.
|
||||||
|
set -eu
|
||||||
|
ROOT="$(cd "${1:-.}" && pwd)"
|
||||||
|
cd "$ROOT"
|
||||||
|
LIB="$ROOT/usr/share/ucode/*.uc"
|
||||||
|
rc=0
|
||||||
|
for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do
|
||||||
|
[ -f "$f" ] || continue
|
||||||
|
n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g')
|
||||||
|
out=$(ucode -L "$LIB" -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
|
||||||
|
done
|
||||||
|
# Entry points (ucode scripts outside the module tree); the shell ones live in
|
||||||
|
# the ShellCheck list of .github/workflows/ci.yml instead.
|
||||||
|
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline \
|
||||||
|
usr/share/dawnline/portal/cgi.uc; do
|
||||||
|
[ -f "$f" ] || { echo "FAIL $f: missing"; rc=1; continue; }
|
||||||
|
out=$(ucode -L "$LIB" -c -o /dev/null "$f" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
|
||||||
|
done
|
||||||
|
[ $rc = 0 ] && echo "all ucode files compile"
|
||||||
|
exit $rc
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Put the README screenshots into a browser window on a dawn gradient.
|
"""Frame the README screenshots the way the portal draws its own surfaces.
|
||||||
|
|
||||||
Raw captures live in docs/screenshots/raw/<name>.png; the framed images are
|
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
|
||||||
written to docs/screenshots/<name>.png. Needs a Chromium-based browser for the
|
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
|
||||||
headless render (BROWSER=/path/to/chrome, default: Brave or Chrome on macOS).
|
are written to docs/screenshots/<name>.png at the same scale. Each page sits on
|
||||||
Run: scripts/frame-screenshots.py
|
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
|
||||||
|
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
|
||||||
|
in a row in front of the page's lower edge, numbered: sheets captured alone on
|
||||||
|
a transparent page (raw/<step>.png, FLOW_MARGIN around each). Needs a
|
||||||
|
Chromium-based browser for the headless render (BROWSER=/path/to/chrome,
|
||||||
|
default: Brave or Chrome on macOS).
|
||||||
|
Run: scripts/frame-screenshots.py [name ...] (all of them when no name is given)
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
@@ -16,17 +22,19 @@ import tempfile
|
|||||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||||
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
|
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
|
||||||
OUT = os.path.join(ROOT, 'docs', 'screenshots')
|
OUT = os.path.join(ROOT, 'docs', 'screenshots')
|
||||||
|
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
|
||||||
|
'geist-latin-wght-normal.woff2')
|
||||||
|
|
||||||
# name -> what the address bar shows
|
SHOTS = ['overview', 'people', 'person', 'portal']
|
||||||
SHOTS = {
|
# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
|
||||||
'overview': 'router.lan · Dawnline',
|
# adding a device there would add one.
|
||||||
'people': 'router.lan · Dawnline · People',
|
FLOWS = {
|
||||||
'person': 'router.lan · Dawnline · Myata',
|
'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
|
||||||
'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
|
PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
|
||||||
|
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
|
||||||
|
STEP_GAP, STEP_OVER, STEP_PAD = 28, 150, 120 # between steps; how far they reach over the page; canvas beside them
|
||||||
|
SCALE = 2
|
||||||
|
|
||||||
CANDIDATES = [
|
CANDIDATES = [
|
||||||
os.environ.get('BROWSER', ''),
|
os.environ.get('BROWSER', ''),
|
||||||
@@ -37,26 +45,18 @@ CANDIDATES = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
|
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
|
||||||
|
@font-face{{font-family:Geist;src:url('file://{font}') format('woff2');font-weight:100 900}}
|
||||||
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
|
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
|
||||||
body{{display:flex;align-items:center;justify-content:center;
|
body{{position:relative;background:#080808}}
|
||||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
|
.panel{{position:absolute;left:{px}px;top:{py}px;width:{pw}px;height:{ph}px;
|
||||||
background:
|
border-radius:36px;background:#121212;box-shadow:inset 0 0 0 1px rgba(255,255,255,.05),0 30px 80px rgba(0,0,0,.5)}}
|
||||||
radial-gradient({gw}px {gh}px at 50% 118%, rgba(255,140,70,.55), rgba(255,140,70,0) 70%),
|
.page{{position:absolute;left:{x}px;top:{y}px;width:{iw}px;height:{ih}px;display:block;border-radius:20px;
|
||||||
radial-gradient({gw2}px {gh2}px at 50% 100%, rgba(250,90,120,.30), rgba(250,90,120,0) 70%),
|
box-shadow:0 0 0 1px rgba(255,255,255,.04)}}
|
||||||
linear-gradient(180deg,#070a14 0%,#0c1226 55%,#1a1430 100%)}}
|
.sheet{{position:absolute;display:block;filter:drop-shadow(0 24px 48px rgba(0,0,0,.6))}}
|
||||||
.win{{width:{iw}px;border-radius:14px;overflow:hidden;background:#000;
|
.n{{position:absolute;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;
|
||||||
box-shadow:0 0 0 1px rgba(255,255,255,.08),0 40px 120px rgba(0,0,0,.65),0 10px 30px rgba(0,0,0,.4)}}
|
font:600 16px Geist,sans-serif;color:#ededed;background:#232323;
|
||||||
.bar{{height:{bar}px;background:#15171c;display:flex;align-items:center;gap:8px;padding:0 16px;
|
box-shadow:0 0 0 1px rgba(255,255,255,.12),0 6px 16px rgba(0,0,0,.5)}}
|
||||||
border-bottom:1px solid rgba(255,255,255,.06);position:relative}}
|
</style></head><body><div class="panel"></div><img class="page" src="file://{src}">{steps}</body></html>"""
|
||||||
.dot{{width:12px;height:12px;border-radius:50%}}
|
|
||||||
.url{{position:absolute;left:50%;transform:translateX(-50%);height:24px;padding:0 14px;border-radius:7px;
|
|
||||||
background:#0d0f13;color:#8b8f98;font-size:13px;display:flex;align-items:center;gap:6px;white-space:nowrap}}
|
|
||||||
.url svg{{width:11px;height:11px;fill:none;stroke:#8b8f98;stroke-width:2}}
|
|
||||||
img{{display:block;width:{iw}px;height:{ih}px}}
|
|
||||||
</style></head><body><div class="win"><div class="bar">
|
|
||||||
<span class="dot" style="background:#ff5f57"></span><span class="dot" style="background:#febc2e"></span><span class="dot" style="background:#28c840"></span>
|
|
||||||
<span class="url"><svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>{url}</span>
|
|
||||||
</div><img src="file://{src}"></div></body></html>"""
|
|
||||||
|
|
||||||
|
|
||||||
def png_size(path):
|
def png_size(path):
|
||||||
@@ -65,25 +65,56 @@ def png_size(path):
|
|||||||
return struct.unpack('>II', head[16:24])
|
return struct.unpack('>II', head[16:24])
|
||||||
|
|
||||||
|
|
||||||
|
def layout(iw, ih, flow):
|
||||||
|
"""Where the page goes and its steps in a row in front of its lower edge: (width, height, page x, page y, steps)."""
|
||||||
|
w, h = iw + 2 * (INSET + PAD_X), ih + 2 * (INSET + PAD_Y)
|
||||||
|
x, y = PAD_X + INSET, PAD_Y + INSET
|
||||||
|
if not flow:
|
||||||
|
return w, h, x, y, ''
|
||||||
|
ml, mt, mr, mb = FLOW_MARGIN
|
||||||
|
sizes = [tuple(v // SCALE for v in png_size(src)) for src in flow]
|
||||||
|
row = sum(pw - ml - mr for pw, _ in sizes) + STEP_GAP * (len(sizes) - 1)
|
||||||
|
w = max(w, row + 2 * STEP_PAD)
|
||||||
|
x = (w - iw) // 2
|
||||||
|
top = y + ih - STEP_OVER
|
||||||
|
h = top + max(ph - mt - mb for _, ph in sizes) + PAD_Y
|
||||||
|
out, sx = [], (w - row) // 2
|
||||||
|
for i, (src, (pw, ph)) in enumerate(zip(flow, sizes)):
|
||||||
|
out.append(f'<img class="sheet" src="file://{src}" style="left:{sx - ml}px;top:{top - mt}px;width:{pw}px;height:{ph}px">')
|
||||||
|
out.append(f'<span class="n" style="left:{sx - 14}px;top:{top - 14}px">{i + 1}</span>')
|
||||||
|
sx += pw - ml - mr + STEP_GAP
|
||||||
|
return w, h, x, y, ''.join(out)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None)
|
browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None)
|
||||||
if not browser:
|
if not browser:
|
||||||
sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome')
|
sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome')
|
||||||
|
only = sys.argv[1:]
|
||||||
|
unknown = [n for n in only if n not in SHOTS]
|
||||||
|
if unknown:
|
||||||
|
sys.exit(f'unknown screenshot {", ".join(unknown)} (one of {", ".join(SHOTS)})')
|
||||||
tmp = tempfile.mkdtemp()
|
tmp = tempfile.mkdtemp()
|
||||||
for name, url in SHOTS.items():
|
for name in SHOTS:
|
||||||
|
if only and name not in only:
|
||||||
|
continue
|
||||||
src = os.path.join(RAW, f'{name}.png')
|
src = os.path.join(RAW, f'{name}.png')
|
||||||
if not os.path.exists(src):
|
if not os.path.exists(src):
|
||||||
print(f'skip {name}: no raw capture')
|
print(f'skip {name}: no raw capture')
|
||||||
continue
|
continue
|
||||||
iw, ih = png_size(src)
|
iw, ih = (v // SCALE for v in png_size(src))
|
||||||
w, h = iw + 2 * PAD_X, ih + BAR + 2 * PAD_Y
|
flow = [os.path.join(RAW, f'{step}.png') for step in FLOWS.get(name, [])]
|
||||||
|
if not all(os.path.exists(p) for p in flow):
|
||||||
|
print(f'{name}: a step is missing, the page alone')
|
||||||
|
flow = []
|
||||||
|
w, h, x, y, steps = layout(iw, ih, flow)
|
||||||
html = os.path.join(tmp, f'{name}.html')
|
html = os.path.join(tmp, f'{name}.html')
|
||||||
with open(html, 'w', encoding='utf-8') as f:
|
with open(html, 'w', encoding='utf-8') as f:
|
||||||
f.write(TEMPLATE.format(w=w, h=h, iw=iw, ih=ih, bar=BAR, url=url, src=src,
|
f.write(TEMPLATE.format(w=w, h=h, x=x, y=y, iw=iw, ih=ih, px=x - INSET, py=y - INSET, pw=iw + 2 * INSET,
|
||||||
gw=int(w * .8), gh=int(h * .5), gw2=int(w * .6), gh2=int(h * .45)))
|
ph=ih + 2 * INSET, src=src, font=FONT, steps=steps))
|
||||||
out = os.path.join(OUT, f'{name}.png')
|
out = os.path.join(OUT, f'{name}.png')
|
||||||
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
|
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
|
||||||
'--force-device-scale-factor=1', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
|
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
|
||||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
print(f'{name}: {w}x{h}')
|
print(f'{name}: {w}x{h}')
|
||||||
shutil.rmtree(tmp)
|
shutil.rmtree(tmp)
|
||||||
|
|||||||
@@ -3,8 +3,10 @@
|
|||||||
|
|
||||||
ucode resolves names where they are used: calling a function that is declared
|
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").
|
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
|
Also: calls and named imports must match what a Dawnline module exports, the
|
||||||
the rpcd methods (dawnline.rpc.*) must match the plugin and its ACL.
|
rpcd methods (dawnline.rpc.*) must match the plugin and its ACL, and regexes
|
||||||
|
stay POSIX (rules/backend.md). Imports against the module layering are
|
||||||
|
reported as notes, not failures.
|
||||||
Run: scripts/lint-ucode.py [package root]
|
Run: scripts/lint-ucode.py [package root]
|
||||||
"""
|
"""
|
||||||
import glob
|
import glob
|
||||||
@@ -22,9 +24,8 @@ files = modules + [
|
|||||||
PLUGIN,
|
PLUGIN,
|
||||||
f"{root}/usr/libexec/dawnline/agent",
|
f"{root}/usr/libexec/dawnline/agent",
|
||||||
f"{root}/usr/libexec/dawnline/updater",
|
f"{root}/usr/libexec/dawnline/updater",
|
||||||
f"{root}/usr/libexec/dawnline/resolver",
|
|
||||||
f"{root}/usr/bin/dawnline",
|
f"{root}/usr/bin/dawnline",
|
||||||
f"{root}/usr/share/dawnline/portal/www/cgi-bin/portal",
|
f"{root}/usr/share/dawnline/portal/cgi.uc",
|
||||||
]
|
]
|
||||||
files = [f for f in files if os.path.exists(f)]
|
files = [f for f in files if os.path.exists(f)]
|
||||||
bad = 0
|
bad = 0
|
||||||
@@ -40,6 +41,16 @@ def strip_comments(text):
|
|||||||
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
|
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
|
||||||
|
|
||||||
|
|
||||||
|
def blank_comments(text):
|
||||||
|
"""Comments replaced by their newlines: line numbers stay, their text goes."""
|
||||||
|
return re.sub(r'//[^\n]*|/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S)
|
||||||
|
|
||||||
|
|
||||||
|
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
|
||||||
|
# a delimiter (so a division keeps out). Good enough for how Dawnline writes them.
|
||||||
|
REGEX_LITERAL = re.compile(r'(?<![\w)\]])/((?:\\.|[^/\\\n])+)/[gis]*(?=[,);\s])')
|
||||||
|
|
||||||
|
|
||||||
def modname(path):
|
def modname(path):
|
||||||
"""dawnline/rpc/people.uc → 'rpc.people' (as in import … from 'dawnline.rpc.people')."""
|
"""dawnline/rpc/people.uc → 'rpc.people' (as in import … from 'dawnline.rpc.people')."""
|
||||||
rel = os.path.relpath(path, MODDIR)[:-3]
|
rel = os.path.relpath(path, MODDIR)[:-3]
|
||||||
@@ -55,7 +66,7 @@ for f in files:
|
|||||||
problem(f"{f}:{line}: {name}() is used before its definition")
|
problem(f"{f}:{line}: {name}() is used before its definition")
|
||||||
# In a module an exported function is an expression statement: its closing
|
# In a module an exported function is an expression statement: its closing
|
||||||
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
|
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
|
||||||
lines = open(f, encoding='utf-8').read().split('\n')
|
lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
|
||||||
inside = None
|
inside = None
|
||||||
for n, text in enumerate(lines, 1):
|
for n, text in enumerate(lines, 1):
|
||||||
if inside is None and re.match(r'^export function \w+\(', text):
|
if inside is None and re.match(r'^export function \w+\(', text):
|
||||||
@@ -68,6 +79,14 @@ for f in files:
|
|||||||
# not preceded by valid expression"), and let [a, b] = … does not compile.
|
# not preceded by valid expression"), and let [a, b] = … does not compile.
|
||||||
if re.search(r'/[^/\n]*\(\?[:=!][^/\n]*/', text):
|
if re.search(r'/[^/\n]*\(\?[:=!][^/\n]*/', text):
|
||||||
problem(f"{f}:{n}: ucode regexes are POSIX: no (?: (?= (?! groups")
|
problem(f"{f}:{n}: ucode regexes are POSIX: no (?: (?= (?! groups")
|
||||||
|
# Lazy quantifiers (*? +? }?) and the [\s\S] class are PCRE: the C
|
||||||
|
# library's regcomp does something else with them or rejects them.
|
||||||
|
for m in REGEX_LITERAL.finditer(text):
|
||||||
|
body = m.group(1)
|
||||||
|
if re.search(r'(?<!\\)[*+}]\?', body):
|
||||||
|
problem(f"{f}:{n}: ucode regexes are POSIX: no lazy quantifiers (*? +? }}?) in /{body}/")
|
||||||
|
if re.search(r'\[\\[sS]\\[sS]\]', body):
|
||||||
|
problem(f"{f}:{n}: ucode regexes are POSIX: no [\\s\\S] class in /{body}/ (use (.|\\n) or a negated class)")
|
||||||
if re.match(r'\s*(let|const)\s*[\[{]', text):
|
if re.match(r'\s*(let|const)\s*[\[{]', text):
|
||||||
problem(f"{f}:{n}: ucode has no destructuring")
|
problem(f"{f}:{n}: ucode has no destructuring")
|
||||||
|
|
||||||
@@ -124,5 +143,24 @@ if methods and os.path.exists(ACL):
|
|||||||
if 'uci' in acl.get(kind, {}) and 'dawnline' in acl[kind]['uci']:
|
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")
|
problem(f"{ACL}: {kind} grants uci 'dawnline' (private keys, no validation): use the rpc methods")
|
||||||
|
|
||||||
|
# Layering (rules/backend.md): util, schema → core → store → domain modules →
|
||||||
|
# apply → entry points. A module importing one from a layer above it is
|
||||||
|
# reported, not failed, until the existing edges are untangled.
|
||||||
|
LAYER = {'util': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
|
||||||
|
LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'}
|
||||||
|
notes = 0
|
||||||
|
for f in modules:
|
||||||
|
mod = modname(f)
|
||||||
|
if mod.startswith('rpc.'):
|
||||||
|
continue # an entry point: may import anything
|
||||||
|
mine = LAYER.get(mod, 4)
|
||||||
|
for dep in re.findall(r"from 'dawnline\.([\w.]+)'", strip_comments(open(f, encoding='utf-8').read())):
|
||||||
|
theirs = LAYER.get(dep, 4)
|
||||||
|
if theirs > mine or (theirs == mine and mine < 4 and dep != mod):
|
||||||
|
print(f"note: {f}: {mod} ({LAYER_NAME[mine]}) imports dawnline.{dep} ({LAYER_NAME[theirs]}), a layer above it")
|
||||||
|
notes += 1
|
||||||
|
if notes:
|
||||||
|
print(f"lint-ucode: {notes} layering notes (not failures)")
|
||||||
|
|
||||||
print(f"lint-ucode: {len(files)} files checked" + (", problems found" if bad else ", ok"))
|
print(f"lint-ucode: {len(files)} files checked" + (", problems found" if bad else ", ok"))
|
||||||
sys.exit(bad)
|
sys.exit(bad)
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
// Demo data for the README screenshots (scripts/capture-screenshots.mjs --demo):
|
||||||
|
// the router's own answers (luci.dawnline status, events) with a made-up cast in
|
||||||
|
// place of its people, devices, places and activity, in the states the
|
||||||
|
// screenshots should show (online, ending soon, over the limit, paused, ended,
|
||||||
|
// outside their hours). The router's ids stay, so every page keeps working; it
|
||||||
|
// is only ever read.
|
||||||
|
|
||||||
|
// The admin counts in binary units: "100 GB" is 100 GiB.
|
||||||
|
const GB = 2 ** 30;
|
||||||
|
const MIN = 60;
|
||||||
|
const HOUR = 3600;
|
||||||
|
const DAY = 86400;
|
||||||
|
|
||||||
|
/** Where the cast connects from: [lat, lon, country, cc, network]. */
|
||||||
|
const CITIES = {
|
||||||
|
Lisbon: [38.7223, -9.1393, 'Portugal', 'PT', 'MEO'],
|
||||||
|
Porto: [41.1579, -8.6291, 'Portugal', 'PT', 'NOS'],
|
||||||
|
Sintra: [38.8029, -9.3817, 'Portugal', 'PT', 'Vodafone Portugal'],
|
||||||
|
Madrid: [40.4168, -3.7038, 'Spain', 'ES', 'Telefonica de Espana'],
|
||||||
|
Barcelona: [41.3874, 2.1686, 'Spain', 'ES', 'Orange Espagne'],
|
||||||
|
Berlin: [52.52, 13.405, 'Germany', 'DE', 'Deutsche Telekom'],
|
||||||
|
Milan: [45.4642, 9.19, 'Italy', 'IT', 'TIM'],
|
||||||
|
Amsterdam: [52.3676, 4.9041, 'Netherlands', 'NL', 'KPN'],
|
||||||
|
Paris: [48.8566, 2.3522, 'France', 'FR', 'Orange'],
|
||||||
|
London: [51.5072, -0.1276, 'United Kingdom', 'GB', 'BT'],
|
||||||
|
Stockholm: [59.3293, 18.0686, 'Sweden', 'SE', 'Telia'],
|
||||||
|
};
|
||||||
|
/** The router's own place. */
|
||||||
|
const HOME = 'Lisbon';
|
||||||
|
/** Shared at home (Access): what a Home-only person can be limited to. */
|
||||||
|
const SERVICES = [
|
||||||
|
{ id: 'demo-nas', name: 'NAS', address: '10.0.1.20', ports: ['445', '5000'] },
|
||||||
|
{
|
||||||
|
id: 'demo-ha',
|
||||||
|
name: 'Home Assistant',
|
||||||
|
address: '10.0.1.30',
|
||||||
|
ports: ['8123'],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
/** How busy each day of the week is, Monday first. */
|
||||||
|
const WEEK = [0.9, 1.15, 0.8, 1.05, 1.3, 0.75, 1.1];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who the screenshots show, the --person first (the Person page), each with
|
||||||
|
* their city. A device: [name, kind, when it was last seen, GB this month,
|
||||||
|
* earlier places as 'City:days ago']; when: 'online', 'mins:N', 'hours:N',
|
||||||
|
* 'days:N', 'never', 'stale' (settings changed since), 'disabled'. Its last
|
||||||
|
* place is the person's city unless `at` names another.
|
||||||
|
*/
|
||||||
|
export const CAST = [
|
||||||
|
{
|
||||||
|
name: 'Lena Ortiz',
|
||||||
|
city: 'Lisbon',
|
||||||
|
limit: 4,
|
||||||
|
quota: 100,
|
||||||
|
used: 38.6,
|
||||||
|
note: 'Family',
|
||||||
|
devices: [
|
||||||
|
['iPhone 16', 'phone', 'online', 14.2, ['Sintra:3', 'Porto:9', 'Madrid:16']],
|
||||||
|
['MacBook Pro', 'computer', 'hours:3', 21.9, ['Berlin:12']],
|
||||||
|
['iPad Air', 'tablet', 'never', 0],
|
||||||
|
],
|
||||||
|
added: [['iPad Air', 2, 'portal']],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Marco Rossi',
|
||||||
|
city: 'Milan',
|
||||||
|
ends: 4,
|
||||||
|
devices: [
|
||||||
|
['Pixel 9', 'phone', 'online', 6.4, ['Barcelona:8']],
|
||||||
|
['ThinkPad X1', 'computer', 'days:1', 12.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Yuki Tanaka',
|
||||||
|
city: 'Amsterdam',
|
||||||
|
state: 'quota',
|
||||||
|
quota: 20,
|
||||||
|
used: 20.4,
|
||||||
|
devices: [
|
||||||
|
['Galaxy S24', 'phone', 'hours:6', 14.1, ['Paris:5']],
|
||||||
|
['Living room TV', 'other', 'stale', 6.3],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Sam Okafor',
|
||||||
|
city: 'London',
|
||||||
|
state: 'paused',
|
||||||
|
paused: 3,
|
||||||
|
devices: [
|
||||||
|
['Gaming PC', 'computer', 'days:9', 3.1],
|
||||||
|
['Steam Deck', 'other', 'disabled', 0],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Nora Lindqvist',
|
||||||
|
city: 'Stockholm',
|
||||||
|
state: 'expired',
|
||||||
|
ends: -3,
|
||||||
|
devices: [['iPhone 13 mini', 'phone', 'days:4', 1.2]],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Mia Ortiz',
|
||||||
|
city: 'Lisbon',
|
||||||
|
state: 'hours',
|
||||||
|
hours: '07:00-21:00',
|
||||||
|
limit: 1,
|
||||||
|
devices: [['Fire HD 10', 'tablet', 'hours:11', 2.6]],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const slug = (s) =>
|
||||||
|
s
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-|-$/g, '');
|
||||||
|
const date = (t) => new Date(t * 1000).toISOString().slice(0, 10);
|
||||||
|
const seen = (when, now) => {
|
||||||
|
const [k, n] = when.split(':');
|
||||||
|
const v = +n || 0;
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
online: now - 40,
|
||||||
|
mins: now - v * MIN,
|
||||||
|
hours: now - v * HOUR,
|
||||||
|
days: now - v * DAY,
|
||||||
|
stale: now - 2 * DAY,
|
||||||
|
disabled: now - 41 * DAY,
|
||||||
|
}[k] ?? 0
|
||||||
|
);
|
||||||
|
};
|
||||||
|
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
|
||||||
|
const week = (gb, last, now) =>
|
||||||
|
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
|
||||||
|
let ipN = 10;
|
||||||
|
/** A documentation address (the capture swaps public addresses for these anyway). */
|
||||||
|
const ip = () => `203.0.113.${ipN++}`;
|
||||||
|
const where = (city) => `${city} · ${CITIES[city][4]}`;
|
||||||
|
|
||||||
|
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
|
||||||
|
const demo = { events: [], people: new Map(), days: [], now: 0 };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
|
||||||
|
* only partly gone. Each day's [rx, tx] in bytes, rx (from the devices) about an eighth.
|
||||||
|
*/
|
||||||
|
function daily(days, gb, now) {
|
||||||
|
const month = days[days.length - 1].slice(0, 7);
|
||||||
|
const w = days.map((d, i) => {
|
||||||
|
const wd = (new Date(`${d}T12:00:00Z`).getUTCDay() + 6) % 7;
|
||||||
|
const today = i === days.length - 1 ? ((now % DAY) / DAY) * 0.9 + 0.1 : 1;
|
||||||
|
return WEEK[wd] * (0.85 + ((i * 37) % 11) / 30) * today;
|
||||||
|
});
|
||||||
|
const inMonth = w.reduce((s, x, i) => s + (days[i].startsWith(month) ? x : 0), 0) || 1;
|
||||||
|
return w.map((x) => {
|
||||||
|
const b = (x / inMonth) * gb * GB;
|
||||||
|
return [Math.round(b * 0.12), Math.round(b * 0.88)];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const usage = (days, pairs) => days.map((day, i) => ({ day, rx: pairs[i][0], tx: pairs[i][1] }));
|
||||||
|
|
||||||
|
/** The places a device was at, oldest first: [city, ts, ip]. */
|
||||||
|
function trail(c, d, hs, now) {
|
||||||
|
if (!hs) return [];
|
||||||
|
const earlier = (d[4] ?? []).map((s) => {
|
||||||
|
const [city, ago] = s.split(':');
|
||||||
|
return [city, now - +ago * DAY - 5 * HOUR, ip()];
|
||||||
|
});
|
||||||
|
return [...earlier.reverse(), [c.city, hs, ip()]];
|
||||||
|
}
|
||||||
|
|
||||||
|
function demoStatus(st, first) {
|
||||||
|
const now = st.now;
|
||||||
|
ipN = 10;
|
||||||
|
const real = [...st.people].sort((a, b) => (a.id === first ? -1 : b.id === first ? 1 : a.id < b.id ? -1 : 1));
|
||||||
|
const spare = real.flatMap((p) => p.devices);
|
||||||
|
const points = [];
|
||||||
|
const events = [];
|
||||||
|
const people = CAST.map((c, i) => {
|
||||||
|
const base = real[i] ?? {
|
||||||
|
...real[real.length - 1],
|
||||||
|
id: `demo-${i}`,
|
||||||
|
devices: [],
|
||||||
|
};
|
||||||
|
const state = c.state ?? 'active';
|
||||||
|
const devices = c.devices.map((cd, j) => {
|
||||||
|
const [name, kind, when, gb] = cd;
|
||||||
|
const tpl = base.devices[j] ?? {
|
||||||
|
...spare[j % spare.length],
|
||||||
|
id: `${base.id}-demo-${j}`,
|
||||||
|
address: `10.8.0.${200 + i * 8 + j}`,
|
||||||
|
};
|
||||||
|
const hs = when === 'never' ? 0 : seen(when, now);
|
||||||
|
const online = when === 'online' && !['paused', 'expired', 'hours'].includes(state);
|
||||||
|
const places = trail(c, cd, hs, now);
|
||||||
|
places.forEach(([city, ts, addr], k) => {
|
||||||
|
const [lat, lon, country, cc, org] = CITIES[city];
|
||||||
|
const current = online && k === places.length - 1;
|
||||||
|
points.push({
|
||||||
|
person: base.id,
|
||||||
|
device: tpl.id,
|
||||||
|
ip: addr,
|
||||||
|
ts,
|
||||||
|
online: current,
|
||||||
|
lat,
|
||||||
|
lon,
|
||||||
|
city,
|
||||||
|
country,
|
||||||
|
cc,
|
||||||
|
asn: 0,
|
||||||
|
org,
|
||||||
|
});
|
||||||
|
const ev = {
|
||||||
|
person: base.id,
|
||||||
|
device: tpl.id,
|
||||||
|
pname: c.name,
|
||||||
|
dname: name,
|
||||||
|
dkind: kind,
|
||||||
|
};
|
||||||
|
// Online now: connected a while ago (the handshake renews every few minutes); otherwise on for a couple of hours.
|
||||||
|
events.push({
|
||||||
|
...ev,
|
||||||
|
type: 'connect',
|
||||||
|
detail: addr,
|
||||||
|
where: where(city),
|
||||||
|
ts: current ? now - 95 * MIN - j * 13 * MIN : ts - 2 * HOUR,
|
||||||
|
});
|
||||||
|
if (!current) events.push({ ...ev, type: 'disconnect', ts });
|
||||||
|
});
|
||||||
|
// A phone in hand switches between Wi-Fi and mobile data.
|
||||||
|
if (online && kind === 'phone') {
|
||||||
|
const [, , addr] = places[places.length - 1];
|
||||||
|
events.push({
|
||||||
|
person: base.id,
|
||||||
|
device: tpl.id,
|
||||||
|
pname: c.name,
|
||||||
|
dname: name,
|
||||||
|
dkind: kind,
|
||||||
|
type: 'roam',
|
||||||
|
detail: `${ip()} → ${addr}`,
|
||||||
|
ts: now - 25 * MIN,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...tpl,
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
online,
|
||||||
|
active: online,
|
||||||
|
handshake: hs,
|
||||||
|
endpoint: places.length ? places[places.length - 1][2] : '',
|
||||||
|
config_stale: when === 'stale',
|
||||||
|
disabled: when === 'disabled',
|
||||||
|
month: [Math.round(gb * 0.12 * GB), Math.round(gb * 0.88 * GB)],
|
||||||
|
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
|
||||||
|
spark: week(gb, hs, now),
|
||||||
|
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
for (const [name, ago, by] of c.added ?? []) {
|
||||||
|
const d = devices.find((x) => x.name === name);
|
||||||
|
if (d)
|
||||||
|
events.push({
|
||||||
|
person: base.id,
|
||||||
|
device: d.id,
|
||||||
|
pname: c.name,
|
||||||
|
dname: name,
|
||||||
|
dkind: d.kind,
|
||||||
|
type: 'device_added',
|
||||||
|
detail: name,
|
||||||
|
by,
|
||||||
|
ts: now - ago * DAY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (c.paused)
|
||||||
|
events.push({
|
||||||
|
person: base.id,
|
||||||
|
pname: c.name,
|
||||||
|
type: 'paused',
|
||||||
|
by: 'admin',
|
||||||
|
ts: now - c.paused * DAY,
|
||||||
|
});
|
||||||
|
const month = devices.reduce((s, d) => [s[0] + d.month[0], s[1] + d.month[1]], [0, 0]);
|
||||||
|
const live = devices.some((d) => d.online);
|
||||||
|
demo.people.set(base.id, {
|
||||||
|
devices: devices.map((d, j) => [d.id, c.devices[j][3]]),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
name: c.name,
|
||||||
|
state,
|
||||||
|
paused: state === 'paused',
|
||||||
|
hours: c.hours ?? '',
|
||||||
|
note: c.note ?? '',
|
||||||
|
expires: c.ends !== undefined ? date(now + c.ends * DAY) : '',
|
||||||
|
device_limit: c.limit ?? Math.max(3, devices.length),
|
||||||
|
quota_gb: c.quota ?? 0,
|
||||||
|
quota_period: 'month',
|
||||||
|
quota_limit: (c.quota ?? 0) * GB,
|
||||||
|
quota_used: Math.round((c.used ?? (month[0] + month[1]) / GB) * GB),
|
||||||
|
bonus_gb: 0,
|
||||||
|
month,
|
||||||
|
total: [month[0] * 3, month[1] * 3],
|
||||||
|
online: devices.filter((d) => d.online).length,
|
||||||
|
last_seen: Math.max(0, ...devices.map((d) => d.handshake)),
|
||||||
|
rate: (base.rate ?? []).map(([t], k) => [t, live ? 12000 + ((k * 7919) % 9000) : 0, live ? 120000 + ((k * 104729) % 90000) : 0]),
|
||||||
|
devices,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const devices = people.flatMap((p) => p.devices);
|
||||||
|
const month = people.reduce((s, p) => [s[0] + p.month[0], s[1] + p.month[1]], [0, 0]);
|
||||||
|
events.sort((a, b) => a.ts - b.ts);
|
||||||
|
demo.events = events;
|
||||||
|
points.sort((a, b) => b.ts - a.ts);
|
||||||
|
demo.now = now;
|
||||||
|
demo.days = (st.series ?? []).map((x) => x.day);
|
||||||
|
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
|
||||||
|
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
|
||||||
|
const series = usage(demo.days, daily(demo.days, all, now));
|
||||||
|
const today = series[series.length - 1];
|
||||||
|
const [lat, lon, country, cc, org] = CITIES[HOME];
|
||||||
|
return {
|
||||||
|
...st,
|
||||||
|
people,
|
||||||
|
totals: {
|
||||||
|
...st.totals,
|
||||||
|
people: people.length,
|
||||||
|
devices: devices.length,
|
||||||
|
online: devices.filter((d) => d.online).length,
|
||||||
|
active: people.filter((p) => p.state === 'active').length,
|
||||||
|
today: [today.rx, today.tx],
|
||||||
|
month,
|
||||||
|
},
|
||||||
|
series,
|
||||||
|
servers: st.servers.map((x) => ({ ...x, series })),
|
||||||
|
services: st.services?.length ? st.services : SERVICES,
|
||||||
|
geo: st.geo && {
|
||||||
|
...st.geo,
|
||||||
|
home: { lat, lon, city: HOME, country, cc, asn: 0, org },
|
||||||
|
points,
|
||||||
|
},
|
||||||
|
events: events.slice(-60),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A ubus JSON-RPC exchange (LuCI batches calls into one request) with the
|
||||||
|
* luci.dawnline answers made into the demo; anything else as it came.
|
||||||
|
*/
|
||||||
|
export function demoRpc(request, response, first) {
|
||||||
|
let req;
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
req = JSON.parse(request);
|
||||||
|
res = JSON.parse(response);
|
||||||
|
} catch {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const calls = new Map((Array.isArray(req) ? req : [req]).map((c) => [c.id, c.params ?? []]));
|
||||||
|
const fix = (r) => {
|
||||||
|
const [, object, method, args] = calls.get(r?.id) ?? [];
|
||||||
|
const data = r?.result?.[1];
|
||||||
|
if (object !== 'luci.dawnline' || !data || typeof data !== 'object') return r;
|
||||||
|
if (method === 'status' && Array.isArray(data.people)) return { ...r, result: [r.result[0], demoStatus(data, first)] };
|
||||||
|
if (method === 'person_usage' && demo.people.has(args?.id) && demo.days.length) {
|
||||||
|
const devs = demo.people.get(args.id).devices ?? [];
|
||||||
|
const per = Object.fromEntries(devs.map(([id, gb]) => [id, daily(demo.days, gb, demo.now)]));
|
||||||
|
const sum = demo.days.map((_, i) => devs.reduce((s, [id]) => [s[0] + per[id][i][0], s[1] + per[id][i][1]], [0, 0]));
|
||||||
|
const devices = Object.fromEntries(devs.map(([id]) => [id, usage(demo.days, per[id])]));
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
result: [r.result[0], { ...data, person: usage(demo.days, sum), devices }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Every check passes: the screenshots show Dawnline, not this router's own setup.
|
||||||
|
if (method === 'health' && Array.isArray(data.checks))
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
result: [
|
||||||
|
r.result[0],
|
||||||
|
{
|
||||||
|
...data,
|
||||||
|
checks: data.checks.map((c) => (c.status === 'warn' || c.status === 'error' ? { ...c, status: 'ok', problem: null } : c)),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
if (method === 'events' && Array.isArray(data.events)) {
|
||||||
|
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
result: [r.result[0], { ...data, events: mine, total: mine.length }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
return JSON.stringify(Array.isArray(res) ? res.map(fix) : fix(res));
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Run the ucode checks the way CI does: in an OpenWrt rootfs container with the
|
||||||
|
# release's own ucode and libuci — compile every file (compile-ucode.sh), then
|
||||||
|
# the unit tests (tests/ucode/run.sh). Needs docker; the repository is mounted
|
||||||
|
# read-only at /src, the container is thrown away.
|
||||||
|
# scripts/ucode-container.sh [24.10|25.12|all] [test name filter]
|
||||||
|
#
|
||||||
|
# Images are the x86-64 rootfs of the OpenWrt releases the packages are built
|
||||||
|
# for (build/Dockerfile, scripts/build-packages.sh), pinned by digest so a
|
||||||
|
# retagged image cannot change what CI runs. To move to a new release change
|
||||||
|
# the tag and the digest together (docker buildx imagetools inspect <image>).
|
||||||
|
set -euo pipefail
|
||||||
|
REPO="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
image_for() {
|
||||||
|
case "$1" in
|
||||||
|
24.10) echo 'openwrt/rootfs:x86-64-24.10.6@sha256:fd76f3afb9c390ef2915618b6e3d7187698c03ecc6c23d3a13f12b62d9c6209e' ;;
|
||||||
|
25.12) echo 'openwrt/rootfs:x86-64-25.12.3@sha256:af882e0583954fc2ceac6b081a9d214fc739cfea36a29b48795a5f15563aa3b5' ;;
|
||||||
|
*) echo "unknown release $1 (24.10 or 25.12)" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
releases="${1:-all}"
|
||||||
|
[ "$releases" = all ] && releases='24.10 25.12'
|
||||||
|
rc=0
|
||||||
|
for rel in $releases; do
|
||||||
|
image="$(image_for "$rel")"
|
||||||
|
echo "== OpenWrt $rel ($image)"
|
||||||
|
# The checks run from this stdin script (`sh -s`): ucode-mod-uloop is not in
|
||||||
|
# the 24.10 rootfs, so what is missing is installed from the release's feeds.
|
||||||
|
docker run --rm -i --platform linux/amd64 -v "$REPO:/src:ro" -e "FILTER=${2:-}" "$image" sh -s <<-'INNER' || rc=1
|
||||||
|
set -eu
|
||||||
|
missing=''
|
||||||
|
command -v ucode >/dev/null || missing='ucode'
|
||||||
|
for m in fs uci ubus uloop; do
|
||||||
|
[ -e "/usr/lib/ucode/$m.so" ] || missing="$missing ucode-mod-$m"
|
||||||
|
done
|
||||||
|
if [ -n "$missing" ]; then
|
||||||
|
echo "installing:$missing"
|
||||||
|
if command -v apk >/dev/null; then
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
apk add --quiet $missing
|
||||||
|
else
|
||||||
|
mkdir -p /var/lock
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
opkg update >/dev/null && opkg install $missing >/dev/null
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
sh /src/scripts/compile-ucode.sh /src/package/luci-app-dawnline/root
|
||||||
|
sh /src/tests/ucode/run.sh /src "$FILTER"
|
||||||
|
INNER
|
||||||
|
done
|
||||||
|
exit $rc
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// dawnline.awg: disguise presets against their own validation, the parser
|
||||||
|
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
|
||||||
|
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
|
||||||
|
import { readfile, writefile, unlink } from 'fs';
|
||||||
|
import * as awg from 'dawnline.awg';
|
||||||
|
|
||||||
|
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
|
||||||
|
let fixtures = sourcepath(0, true) + '/fixtures';
|
||||||
|
|
||||||
|
test('obf_preset off', () => {
|
||||||
|
let o = awg.obf_preset('off');
|
||||||
|
eq(o, { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }, 'plain WireGuard headers');
|
||||||
|
eq(awg.obf_errors(o), [], 'valid');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('obf_preset balanced', () => {
|
||||||
|
for (let i = 0; i < 25; i++) {
|
||||||
|
let o = awg.obf_preset('balanced');
|
||||||
|
eq(awg.obf_errors(o), [], 'balanced is valid');
|
||||||
|
ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`);
|
||||||
|
let jmin = +o.jmin, jmax = +o.jmax;
|
||||||
|
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `junk sizes ${o.jmin}-${o.jmax}`);
|
||||||
|
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
|
||||||
|
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
|
||||||
|
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
||||||
|
ok(+o[k] >= 5, `${k} above the reserved values`);
|
||||||
|
ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`);
|
||||||
|
ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets');
|
||||||
|
eq(o.header_protection_key, null, 'no 3.1 values');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('obf_preset max', () => {
|
||||||
|
let o = awg.obf_preset('max');
|
||||||
|
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey');
|
||||||
|
ok(+o.jc >= 4 && +o.jc <= 6, 'jc');
|
||||||
|
ok(substr(o.i1, 0, 3) == '<r ', 'DNS-like first packet');
|
||||||
|
eq([ o.random_trailers, o.disable_cookies, o.content_padding_addition ], [ 'on', 'on', '10-100' ], '3.1 options');
|
||||||
|
ok(substr(o.i2, 0, 3) == '<r ', 'DNS-answer second packet');
|
||||||
|
// The template varies by name length and top-level domain (the letters
|
||||||
|
// themselves are random at run time): over many servers, more than one shape.
|
||||||
|
let shapes = {};
|
||||||
|
for (let i = 0; i < 20; i++)
|
||||||
|
shapes[awg.obf_preset('max').i1] = true;
|
||||||
|
ok(length(keys(shapes)) > 1, 'signature packets differ between servers');
|
||||||
|
// The preset passes the server's own validation (jmin/jmax may be small: 0.5.2).
|
||||||
|
eq(awg.obf_errors(o), [], 'max is valid');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('obf_errors', () => {
|
||||||
|
eq(awg.obf_errors({}), [], 'nothing set');
|
||||||
|
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range');
|
||||||
|
eq(awg.obf_errors({ jmin: '0', jmax: '0' }), [], 'zero junk sizes are allowed');
|
||||||
|
eq(awg.obf_errors({ jmin: '2000' }), [ 'jmin=2000 (0-1024)' ], 'jmin range');
|
||||||
|
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'jmin > jmax' ], 'order');
|
||||||
|
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 's1 + 56 = s2' ], 'the handshake size clash');
|
||||||
|
eq(awg.obf_errors({ s4: '33' }), [ 's4=33 (0-32)' ], 's4 range');
|
||||||
|
eq(awg.obf_errors({ jc: 'x' }), [ 'jc=x (0-10)' ], 'not a number');
|
||||||
|
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'h1-h4 must be distinct' ], 'duplicate headers');
|
||||||
|
eq(awg.obf_errors({ h1: '7-9', h2: 'abc' }), [ 'h2 must be a number or range' ], 'header ranges');
|
||||||
|
eq(awg.obf_neutral({ jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }), true, 'off is neutral');
|
||||||
|
eq(awg.obf_neutral({ jc: '4', jmin: '64', jmax: '128' }), false, 'junk is not neutral');
|
||||||
|
});
|
||||||
|
|
||||||
|
function dump_of(name) {
|
||||||
|
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
|
||||||
|
return awg.dump();
|
||||||
|
}
|
||||||
|
|
||||||
|
test('dump: AmneziaWG 1.0 (14 interface fields)', () => {
|
||||||
|
let d = dump_of('1.0');
|
||||||
|
eq(d.ok, true, 'ok');
|
||||||
|
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
|
||||||
|
eq(d.peers['HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw='],
|
||||||
|
{ ifname: 'awgmain', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, 'peer with a session');
|
||||||
|
eq(d.peers['TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='],
|
||||||
|
{ ifname: 'awgmain', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dump: AmneziaWG 2.0 (33 interface fields)', () => {
|
||||||
|
let d = dump_of('2.0');
|
||||||
|
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
|
||||||
|
eq(keys(d.peers), [ 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=' ], 'one peer');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dump: AmneziaWG 3.1 (33 interface fields, protection on)', () => {
|
||||||
|
let d = dump_of('3.1');
|
||||||
|
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
|
||||||
|
eq(length(d.peers), 2, 'two peers');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dump: the tool fails', () => {
|
||||||
|
unlink(AWG_DUMP);
|
||||||
|
let d = awg.dump();
|
||||||
|
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('handshake_since: Reconnect hides older handshakes', () => {
|
||||||
|
eq(awg.handshake_since(1000, null), 1000, 'never set up again');
|
||||||
|
eq(awg.handshake_since(1000, 0), 1000, 'no time');
|
||||||
|
eq(awg.handshake_since(1000, 1500), 0, 'connected before: not set up yet');
|
||||||
|
eq(awg.handshake_since(1500, 1500), 0, 'the same second does not count');
|
||||||
|
eq(awg.handshake_since(1600, 1500), 1600, 'connected after');
|
||||||
|
eq(awg.handshake_since(0, 1500), 0, 'never connected');
|
||||||
|
});
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
// dawnline.core: the model read from the fixture config (real libuci), access
|
||||||
|
// hours, quotas and the derived person state at an explicit time, address
|
||||||
|
// allocation and the automatic MTU.
|
||||||
|
import * as core from 'dawnline.core';
|
||||||
|
|
||||||
|
// A local time that no time zone turns into another day.
|
||||||
|
function at(y, mo, d, h, mi) {
|
||||||
|
return timelocal({ year: y, mon: mo, mday: d, hour: h, min: mi, sec: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let m = core.load();
|
||||||
|
|
||||||
|
test('load reads the fixture', () => {
|
||||||
|
eq(keys(m.servers), [ 'main' ], 'servers');
|
||||||
|
eq(sort(keys(m.people)), [ 'alice', 'bob' ], 'people');
|
||||||
|
eq(m.servers.main.subnet, '10.9.0.0/29', 'subnet');
|
||||||
|
eq(m.servers.main.mtu, 1380, 'stored MTU');
|
||||||
|
eq(m.servers.main.obf, { jc: '4', jmin: '64', jmax: '128', s4: '12' }, 'disguise values as strings');
|
||||||
|
eq(m.servers.main.mesh, 'all', 'mesh default');
|
||||||
|
eq(m.people.alice.devices, [ 'alice_phone' ], 'devices attached to their person');
|
||||||
|
eq(m.people.alice.access, 'both', 'access');
|
||||||
|
eq(m.people.bob.access, 'internet', 'access default');
|
||||||
|
eq(m.people.bob.quota_gb, 2, 'quota as a number');
|
||||||
|
eq(m.people.bob.device_limit, 3, 'device limit from the settings default');
|
||||||
|
eq(m.devices.alice_phone.kind, 'phone', 'kind');
|
||||||
|
eq(m.settings.portal_enabled, true, 'bool setting');
|
||||||
|
eq(m.settings.updates.interval, '7d', 'update policy from the same section');
|
||||||
|
eq(m.settings.updates.targets, [ 'app' ], 'update targets list');
|
||||||
|
eq(m.settings.retention.log_connections, '0', 'raw retention values');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parse_hours', () => {
|
||||||
|
eq(core.parse_hours('07:00-23:00'), [ 420, 1380 ], 'day window');
|
||||||
|
eq(core.parse_hours('23:00-07:00'), [ 1380, 420 ], 'overnight window');
|
||||||
|
eq(core.parse_hours('7:00-23:00'), [ 420, 1380 ], 'one-digit hour');
|
||||||
|
eq(core.parse_hours('00:00-24:00'), [ 0, 1440 ], 'whole day');
|
||||||
|
eq(core.parse_hours('24:00-01:00'), null, 'start at 24:00');
|
||||||
|
eq(core.parse_hours('10:00-10:00'), null, 'empty window');
|
||||||
|
eq(core.parse_hours('always'), null, 'words');
|
||||||
|
eq(core.parse_hours(''), null, 'empty');
|
||||||
|
eq(core.parse_hours(null), null, 'null');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('person_quota', () => {
|
||||||
|
let march = at(2026, 3, 10, 12, 0);
|
||||||
|
eq(core.person_quota({ quota_gb: 0 }, march), 0, 'unlimited');
|
||||||
|
eq(core.person_quota({ quota_gb: 2 }, march), 2147483648, '2 GiB');
|
||||||
|
eq(core.person_quota({ quota_gb: 2, bonus_gb: 1, bonus_month: '2026-03' }, march), 3221225472, 'bonus this month');
|
||||||
|
eq(core.person_quota({ quota_gb: 2, bonus_gb: 1, bonus_month: '2026-02' }, march), 2147483648, 'bonus of another month');
|
||||||
|
eq(core.person_quota({ quota_gb: -1 }, march), 0, 'negative is unlimited');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('person_usage', () => {
|
||||||
|
let march = at(2026, 3, 10, 12, 0);
|
||||||
|
let usage = { people: { bob: { total: [ 100, 50 ], months: { '2026-03': [ 10, 5 ], '2026-02': [ 1000, 1000 ] } } } };
|
||||||
|
eq(core.person_usage({ id: 'bob', quota_period: 'month' }, usage, march), 15, 'this month');
|
||||||
|
eq(core.person_usage({ id: 'bob', quota_period: 'month' }, usage, at(2026, 4, 1, 0, 0)), 0, 'a month without traffic');
|
||||||
|
eq(core.person_usage({ id: 'bob', quota_period: 'total' }, usage, march), 150, 'total');
|
||||||
|
eq(core.person_usage({ id: 'nobody', quota_period: 'month' }, usage, march), 0, 'unknown person');
|
||||||
|
eq(core.person_usage({ id: 'bob' }, null, march), 0, 'no usage data');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('own_state', () => {
|
||||||
|
let base = { id: 'p', paused: false, expires: '', expire_action: 'pause', quota_gb: 0, hours: '' };
|
||||||
|
let noon = at(2026, 3, 10, 12, 0);
|
||||||
|
eq(core.own_state(m, base, null, noon), 'active', 'nothing set');
|
||||||
|
eq(core.own_state(m, { ...base, paused: true }, null, noon), 'paused', 'paused');
|
||||||
|
eq(core.own_state(m, { ...base, expires: '2026-03-09' }, null, noon), 'expired', 'expired yesterday');
|
||||||
|
eq(core.own_state(m, { ...base, expires: '2026-03-10' }, null, noon), 'active', 'expires at the end of today');
|
||||||
|
eq(core.own_state(m, { ...base, expires: '2026-03-09', expire_action: 'notify' }, null, noon), 'active', 'notify keeps access');
|
||||||
|
let usage = { people: { p: { months: { '2026-03': [ 600000000, 600000000 ] } } } };
|
||||||
|
eq(core.own_state(m, { ...base, quota_gb: 1 }, usage, noon), 'quota', 'over quota');
|
||||||
|
eq(core.own_state(m, { ...base, quota_gb: 1, bonus_gb: 1, bonus_month: '2026-03' }, usage, noon), 'active', 'bonus lifts the quota');
|
||||||
|
eq(core.own_state(m, { ...base, quota_gb: 1 }, usage, at(2026, 4, 1, 0, 0)), 'active', 'a new month resets the usage');
|
||||||
|
eq(core.own_state(m, { ...base, hours: '09:00-17:00' }, null, noon), 'active', 'inside the hours');
|
||||||
|
eq(core.own_state(m, { ...base, hours: '09:00-17:00' }, null, at(2026, 3, 10, 20, 0)), 'hours', 'outside the hours');
|
||||||
|
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, at(2026, 3, 10, 23, 0)), 'active', 'overnight, before midnight');
|
||||||
|
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, at(2026, 3, 10, 5, 59)), 'active', 'overnight, after midnight');
|
||||||
|
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, noon), 'hours', 'overnight, daytime');
|
||||||
|
eq(core.own_state(m, { ...base, paused: true, expires: '2000-01-01' }, null, noon), 'paused', 'paused wins over expired');
|
||||||
|
eq(core.own_state(m, { ...base, expires: '2000-01-01', quota_gb: 1 }, usage, noon), 'expired', 'expired wins over quota');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('person_state', () => {
|
||||||
|
let noon = at(2026, 3, 10, 12, 0);
|
||||||
|
let p = { id: 'p', server: 'main', paused: false, expires: '', expire_action: 'pause', quota_gb: 0, hours: '' };
|
||||||
|
eq(core.person_state(m, p, null, noon), 'active', 'server on');
|
||||||
|
eq(core.person_state(m, { ...p, server: 'gone' }, null, noon), 'no_server', 'no server');
|
||||||
|
let off = { servers: { main: { ...m.servers.main, enabled: false } } };
|
||||||
|
eq(core.person_state(off, p, null, noon), 'server_off', 'server off');
|
||||||
|
eq(core.person_state(off, { ...p, paused: true }, null, noon), 'server_off', 'server off is about the server');
|
||||||
|
ok(core.person_expired({ expires: '2000-01-01' }, noon), 'person_expired');
|
||||||
|
ok(!core.person_expired({ expires: '' }, noon), 'no end date');
|
||||||
|
ok(!core.person_expired({ expires: 'garbage' }, noon), 'bad date is not expired');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('alloc_address', () => {
|
||||||
|
let srv = { id: 'main', subnet: '10.9.0.0/29' };
|
||||||
|
let other = { id: 'other', subnet: '10.9.1.0/29' };
|
||||||
|
let model = (addrs) => {
|
||||||
|
let mm = { servers: { main: srv, other }, people: { a: { server: 'main' }, o: { server: 'other' } }, devices: {} };
|
||||||
|
for (let i, a in addrs)
|
||||||
|
mm.devices[`d${i}`] = { person: 'a', address: a };
|
||||||
|
return mm;
|
||||||
|
};
|
||||||
|
eq(core.alloc_address(model([]), srv), '10.9.0.2', 'router has the first host');
|
||||||
|
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.3' ]), srv), '10.9.0.4', 'next free');
|
||||||
|
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.4' ]), srv), '10.9.0.3', 'lowest gap');
|
||||||
|
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.3', '10.9.0.4', '10.9.0.5', '10.9.0.6' ]), srv), null, 'exhausted (.7 is broadcast)');
|
||||||
|
eq(core.alloc_address(model([ '10.9.0.2', 'garbage' ]), srv), '10.9.0.3', 'a broken address is ignored');
|
||||||
|
let mm = model([]);
|
||||||
|
mm.devices.x = { person: 'o', address: '10.9.0.2' };
|
||||||
|
eq(core.alloc_address(mm, srv), '10.9.0.2', 'another server\'s devices do not count');
|
||||||
|
eq(core.alloc_address(model([]), { id: 'main', subnet: 'nonsense' }), null, 'no subnet');
|
||||||
|
eq(core.server_address(srv), '10.9.0.1', 'server_address');
|
||||||
|
eq(core.tunnels({ ...srv, ifname: 'awgmain', private_key: 'k' }), [ { ifname: 'awgmain', subnet: '10.9.0.0/29', address: '10.9.0.1' } ], 'tunnels');
|
||||||
|
eq(core.tunnels({ ...srv, ifname: 'awgmain' }), [], 'no key, no tunnel');
|
||||||
|
eq(core.tunnels({ ...srv, ifname: 'awgmain', private_key: 'k', blocked: 'taken' }), [], 'blocked interface');
|
||||||
|
eq(core.tunnels({ ...srv, ifname: 'awg-main', private_key: 'k' }), [], 'bad interface name');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tunnel_mtu / device_mtu', () => {
|
||||||
|
eq(core.tunnel_mtu({ mtu: 1420 }), 1420, 'set by hand');
|
||||||
|
eq(core.tunnel_mtu({ mtu: 0, obf: {} }), 1380, 'automatic');
|
||||||
|
eq(core.tunnel_mtu({ mtu: 0 }), 1380, 'automatic without disguise');
|
||||||
|
eq(core.tunnel_mtu({ mtu: 0, obf: { s4: '12' } }), 1368, 'S4 taken off');
|
||||||
|
eq(core.tunnel_mtu({ mtu: 0, obf: { s4: '100' } }), 1280, 'never below 1280');
|
||||||
|
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone' }), 1280, 'phone');
|
||||||
|
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer' }), 1380, 'computer');
|
||||||
|
eq(core.device_mtu({ mtu: 1200 }, { kind: 'tablet' }), 1200, 'a smaller tunnel MTU stays');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('names and codes', () => {
|
||||||
|
ok(core.valid_ifname('awgmain') && core.valid_ifname('a') && core.valid_ifname('awg_1'), 'interface names');
|
||||||
|
ok(!core.valid_ifname('Awg') && !core.valid_ifname('1awg') && !core.valid_ifname('awg-main') && !core.valid_ifname('awgmain123456'), 'bad interface names');
|
||||||
|
for (let i = 0; i < 20; i++)
|
||||||
|
ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renumber_server', () => {
|
||||||
|
let srv = { id: 'main', name: 'Main', subnet: '10.9.0.0/29' };
|
||||||
|
let mm = {
|
||||||
|
servers: { main: srv, other: { id: 'other', subnet: '10.9.1.0/29' } },
|
||||||
|
people: { a: { server: 'main', devices: [ 'a1', 'a2' ] }, o: { server: 'other', devices: [ 'o1' ] } },
|
||||||
|
devices: { a1: { person: 'a', address: '10.9.0.5' }, a2: { person: 'a', address: '10.9.0.3' }, o1: { person: 'o', address: '10.9.1.2' } },
|
||||||
|
};
|
||||||
|
let set = {};
|
||||||
|
let c = { set: (cfg, s, k, v) => { set[`${s}.${k}`] = v; }, delete: () => {} };
|
||||||
|
core.renumber_server(c, mm, srv, '10.77.0.0/24');
|
||||||
|
eq(srv.subnet, '10.77.0.0/24', 'the server moves');
|
||||||
|
eq([ mm.devices.a1.address, mm.devices.a2.address ], [ '10.77.0.2', '10.77.0.3' ], 'devices renumbered lowest first');
|
||||||
|
eq(mm.devices.o1.address, '10.9.1.2', 'another server untouched');
|
||||||
|
eq(set, { 'a1.address': '10.77.0.2', 'a2.address': '10.77.0.3', 'main.subnet': '10.77.0.0/24' }, 'written to uci');
|
||||||
|
let err = null;
|
||||||
|
try { core.renumber_server(c, mm, srv, '10.9.2.0/30'); } catch (e) { err = e; }
|
||||||
|
ok(err != null, 'refuses a subnet too small for the devices');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('device_labels', () => {
|
||||||
|
let mm = { devices: {
|
||||||
|
a: { id: 'a', name: 'iPhone', created: 1 }, b: { id: 'b', name: 'iPhone!', created: 2 },
|
||||||
|
c: { id: 'c', name: 'Телефон', created: 3 }, d: { id: 'd', name: 'телефон', created: 4 },
|
||||||
|
} };
|
||||||
|
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
|
||||||
|
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 1234567 2345678 3456789 4567890
|
||||||
|
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
|
||||||
|
awgmain TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= (none) (none) 10.9.0.3/32 0 0 0 off
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 12 12 1234567 2345678 3456789 4567890 <b 0xdead>
|
||||||
|
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 12 12 1234567 2345678 3456789 4567890 <r 2><b 0x858000010001> yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= 10-100 on on
|
||||||
|
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
|
||||||
|
awgmain TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= (none) (none) 10.9.0.3/32 0 0 0 off
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Stand-in for amneziawg-tools in the ucode tests (no kernel module in a
|
||||||
|
# container): `genkey` prints one fixed key, `show all dump` prints the fixture
|
||||||
|
# a test has put at /tmp/dawnline-tests/awg-dump (or fails, as the tool does
|
||||||
|
# when no interface is up). Anything else fails.
|
||||||
|
case "$1 ${2:-} ${3:-}" in
|
||||||
|
'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;;
|
||||||
|
'show all dump') cat /tmp/dawnline-tests/awg-dump ;;
|
||||||
|
*) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Test fixture: a small installation (one server, two people, one device).
|
||||||
|
# migrate.test.uc expects bob's random code, the server's stored MTU 1380,
|
||||||
|
# the old portal title and uhttpd's error_page: the one-time steps remove them.
|
||||||
|
|
||||||
|
config settings 'settings'
|
||||||
|
option portal_enabled '1'
|
||||||
|
option portal_port '8443'
|
||||||
|
option portal_host 'vpn.example.com'
|
||||||
|
option portal_title 'My VPN'
|
||||||
|
option log_connections '0'
|
||||||
|
option update_interval '7d'
|
||||||
|
list update_targets 'app'
|
||||||
|
|
||||||
|
config server 'main'
|
||||||
|
option name 'Main'
|
||||||
|
option ifname 'awgmain'
|
||||||
|
option port '51820'
|
||||||
|
option subnet '10.9.0.0/29'
|
||||||
|
option private_key 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='
|
||||||
|
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
|
||||||
|
option mtu '1380'
|
||||||
|
option jc '4'
|
||||||
|
option jmin '64'
|
||||||
|
option jmax '128'
|
||||||
|
option s4 '12'
|
||||||
|
|
||||||
|
config person 'alice'
|
||||||
|
option server 'main'
|
||||||
|
option name 'Alice'
|
||||||
|
option code 'abcdef-ghijkl-mnopqr'
|
||||||
|
option access 'both'
|
||||||
|
|
||||||
|
config person 'bob'
|
||||||
|
option server 'main'
|
||||||
|
option name 'Bob'
|
||||||
|
option code 'XyZ12345'
|
||||||
|
option quota_gb '2'
|
||||||
|
|
||||||
|
config device 'alice_phone'
|
||||||
|
option person 'alice'
|
||||||
|
option name 'Phone'
|
||||||
|
option kind 'phone'
|
||||||
|
option address '10.9.0.2'
|
||||||
|
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Test fixture: LuCI's web server as versions before 0.4 left it, with the
|
||||||
|
# portal as its error page (migrate.uhttpd removes that).
|
||||||
|
|
||||||
|
config uhttpd 'main'
|
||||||
|
list listen_http '0.0.0.0:80'
|
||||||
|
list listen_https '0.0.0.0:443'
|
||||||
|
option home '/www'
|
||||||
|
option error_page '/cgi-bin/dawnline-portal'
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// dawnline.geo: which addresses need a lookup, how results go into the cache
|
||||||
|
// (bounded, never pushing out what is still shown) and the activity-log label.
|
||||||
|
import * as geo from 'dawnline.geo';
|
||||||
|
|
||||||
|
const NOW = 1790000000;
|
||||||
|
const PLACE = { lat: 45.04, lon: 38.98, city: 'Krasnodar', country: 'Russia', cc: 'RU', asn: 12389, org: 'Rostelecom' };
|
||||||
|
|
||||||
|
test('stale', () => {
|
||||||
|
let cache = { ips: {
|
||||||
|
'37.78.36.76': { ...PLACE, ts: NOW - 86400 },
|
||||||
|
'212.233.85.1': { ...PLACE, ts: NOW - 31 * 86400 },
|
||||||
|
'185.135.150.35': { fail: NOW - 3600 },
|
||||||
|
'185.135.150.28': { fail: NOW - 2 * 86400 },
|
||||||
|
'83.239.111.148': { lat: 1, lon: 2, city: 'Old', ts: NOW },
|
||||||
|
}, home: null };
|
||||||
|
eq(geo.stale(cache, [ '37.78.36.76' ], NOW), [], 'fresh: known');
|
||||||
|
eq(geo.stale(cache, [ '212.233.85.1' ], NOW), [ '212.233.85.1' ], 'older than the TTL');
|
||||||
|
eq(geo.stale(cache, [ '185.135.150.35' ], NOW), [], 'failed today: not again yet');
|
||||||
|
eq(geo.stale(cache, [ '185.135.150.28' ], NOW), [ '185.135.150.28' ], 'failed two days ago: retried');
|
||||||
|
eq(geo.stale(cache, [ '83.239.111.148' ], NOW), [ '83.239.111.148' ], 'an entry from before ASNs were kept');
|
||||||
|
eq(geo.stale(cache, [ '10.0.1.164', '100.64.1.1', '', null, 'fe80::1' ], NOW), [], 'local addresses never');
|
||||||
|
eq(geo.stale(cache, [ '1.1.1.1', '8.8.8.8', '1.1.1.1' ], NOW), [ '1.1.1.1', '8.8.8.8' ], 'once each, in order');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('merge', () => {
|
||||||
|
let cache = { ips: {}, home: null };
|
||||||
|
ok(geo.merge(cache, { '1.1.1.1': { ...PLACE }, '8.8.8.8': false }, [], NOW), 'changed');
|
||||||
|
eq(cache.ips['1.1.1.1'], { ...PLACE, ts: NOW }, 'a place, stamped');
|
||||||
|
eq(cache.ips['8.8.8.8'], { fail: NOW }, 'nothing found: a failure, retried later');
|
||||||
|
ok(!geo.merge(cache, {}, [], NOW), 'no results: unchanged');
|
||||||
|
ok(!geo.merge(cache, { '10.0.0.1': PLACE }, [], NOW) && !cache.ips['10.0.0.1'], 'a local address is not kept');
|
||||||
|
eq(geo.place(cache, '1.1.1.1')?.city, 'Krasnodar', 'place');
|
||||||
|
eq(geo.place(cache, '8.8.8.8'), null, 'no place for a failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('merge keeps the cache bounded, what is shown stays', () => {
|
||||||
|
let cache = { ips: {}, home: null };
|
||||||
|
for (let i = 0; i < 500; i++)
|
||||||
|
cache.ips[`1.0.${int(i / 250)}.${i % 250 + 1}`] = { ...PLACE, ts: NOW - 1000 + i };
|
||||||
|
let oldest = '1.0.0.1', second = '1.0.0.2';
|
||||||
|
ok(geo.merge(cache, { '9.9.9.9': PLACE }, [ oldest ], NOW), 'changed');
|
||||||
|
eq(length(keys(cache.ips)), 500, 'back to the cap');
|
||||||
|
ok(cache.ips[oldest] != null, 'the oldest is still shown: kept');
|
||||||
|
ok(cache.ips[second] == null, 'the oldest not shown went');
|
||||||
|
ok(cache.ips['9.9.9.9'] != null, 'the new one is in');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('label', () => {
|
||||||
|
eq(geo.label(PLACE), 'Krasnodar · Rostelecom', 'city and ISP');
|
||||||
|
eq(geo.label({ city: '', org: 'Rostelecom' }), 'Rostelecom', 'no city');
|
||||||
|
eq(geo.label(null), null, 'no place');
|
||||||
|
});
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// dawnline.live: event categories and the retention policy, from a settings
|
||||||
|
// object and from the fixture config (real libuci).
|
||||||
|
import * as live from 'dawnline.live';
|
||||||
|
|
||||||
|
test('category_of', () => {
|
||||||
|
eq(live.category_of('connect'), 'connections', 'connect');
|
||||||
|
eq(live.category_of('roam'), 'connections', 'roam');
|
||||||
|
eq(live.category_of('device_added'), 'people', 'device events are people events');
|
||||||
|
eq(live.category_of('person_changed'), 'people', 'person');
|
||||||
|
eq(live.category_of('server_down'), 'problems', 'server');
|
||||||
|
eq(live.category_of('something_new'), 'problems', 'unknown types are problems');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('policy defaults', () => {
|
||||||
|
eq(live.policy({}), { keep_days: 30, max: 2000, categories: [ 'connections', 'people', 'problems' ],
|
||||||
|
persist: 'hourly', usage_days: 62, usage_months: 24 }, 'empty settings');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('policy categories', () => {
|
||||||
|
eq(live.policy({ log_connections: '0' }).categories, [ 'people', 'problems' ], 'old switch');
|
||||||
|
eq(live.policy({ log_category: 'devices, problems' }).categories, [ 'people', 'problems' ], 'string list, devices renamed');
|
||||||
|
eq(live.policy({ log_category: [ 'connections', 'bogus', 'connections' ] }).categories, [ 'connections' ], 'list, unknown and repeats dropped');
|
||||||
|
eq(live.policy({ log_category: [], log_connections: '0' }).categories, [], 'explicit empty list wins');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ranges come from dawnline.schema: a stored value outside them (an older
|
||||||
|
// version, a hand edit) reads as the default, as settings_update would have refused it.
|
||||||
|
test('policy ranges', () => {
|
||||||
|
eq(live.policy({ log_max: '50' }).max, 2000, 'max below the floor: default');
|
||||||
|
eq(live.policy({ log_max: '99999' }).max, 2000, 'max above the ceiling: default');
|
||||||
|
eq(live.policy({ log_max: '150' }).max, 150, 'max in range');
|
||||||
|
eq(live.policy({ log_max: 'abc' }).max, 2000, 'bad max');
|
||||||
|
eq(live.policy({ log_keep_days: '0' }).keep_days, 0, 'keep forever');
|
||||||
|
eq(live.policy({ log_keep_days: '-3' }).keep_days, 30, 'negative days');
|
||||||
|
eq(live.policy({ log_persist: '10min' }).persist, '10min', 'persist');
|
||||||
|
eq(live.policy({ log_persist: 'daily' }).persist, 'hourly', 'bad persist');
|
||||||
|
eq(live.policy({ usage_keep_days: '1' }).usage_days, 62, 'usage days below the floor: default');
|
||||||
|
eq(live.policy({ usage_keep_months: '500' }).usage_months, 24, 'usage months above the ceiling: default');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('policy from the config', () => {
|
||||||
|
eq(live.policy(null).categories, [ 'people', 'problems' ], 'fixture turns connections off');
|
||||||
|
eq(live.policy(null).max, 2000, 'default where the fixture says nothing');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('endpoint_ip', () => {
|
||||||
|
eq(live.endpoint_ip('203.0.113.7:41821'), '203.0.113.7', 'v4');
|
||||||
|
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
|
||||||
|
eq(live.endpoint_ip(''), '', 'none');
|
||||||
|
});
|
||||||
|
|
||||||
|
// A connect is logged before its new address is located; the place comes later.
|
||||||
|
test('fill_places', () => {
|
||||||
|
let ev = [
|
||||||
|
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 100 },
|
||||||
|
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 200 },
|
||||||
|
{ type: 'disconnect', detail: null, ts: 210 },
|
||||||
|
{ type: 'connect', detail: '8.8.8.8', where: 'Mountain View · Google', ts: 220 },
|
||||||
|
{ type: 'connect', detail: '9.9.9.9', where: null, ts: 230 },
|
||||||
|
];
|
||||||
|
ok(live.fill_places(ev, { '1.1.1.1': 'Sydney · Cloudflare', '8.8.8.8': 'Elsewhere' }, 150), 'changed');
|
||||||
|
eq(ev[1].where, 'Sydney · Cloudflare', 'the waiting connect gets its place');
|
||||||
|
eq(ev[0].where, null, 'older than `since`: left alone');
|
||||||
|
eq(ev[3].where, 'Mountain View · Google', 'a place already there stays');
|
||||||
|
eq(ev[4].where, null, 'another address');
|
||||||
|
ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged');
|
||||||
|
ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log');
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
// dawnline.migrate: the one-time steps on the fixture config (real libuci):
|
||||||
|
// each changes what it must the first time and nothing the second time.
|
||||||
|
// This test rewrites /etc/config/dawnline and /etc/config/uhttpd.
|
||||||
|
import { cursor } from 'uci';
|
||||||
|
import { stat } from 'fs';
|
||||||
|
import * as core from 'dawnline.core';
|
||||||
|
import * as migrate from 'dawnline.migrate';
|
||||||
|
|
||||||
|
function conf(name) {
|
||||||
|
let c = cursor();
|
||||||
|
c.load(name);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('before: the fixture holds the old state', () => {
|
||||||
|
let c = conf('dawnline');
|
||||||
|
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
|
||||||
|
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
|
||||||
|
eq(c.get('dawnline', 'settings', 'portal_title'), 'My VPN', 'a portal title');
|
||||||
|
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('run: the steps change what they must', () => {
|
||||||
|
migrate.run();
|
||||||
|
let c = conf('dawnline');
|
||||||
|
ok(match(c.get('dawnline', 'bob', 'code'), core.WORD_CODE), 'bob has a word code');
|
||||||
|
eq(c.get('dawnline', 'alice', 'code'), 'abcdef-ghijkl-mnopqr', 'alice keeps hers');
|
||||||
|
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
|
||||||
|
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
|
||||||
|
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
|
||||||
|
eq(c.get('dawnline', 'settings', 'portal_title'), null, 'no portal title');
|
||||||
|
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
|
||||||
|
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
|
||||||
|
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
|
||||||
|
user_read: true, user_write: true, user_exec: false,
|
||||||
|
group_read: false, group_write: false, group_exec: false,
|
||||||
|
other_read: false, other_write: false, other_exec: false }, 'config stays private');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('run again: a step runs once', () => {
|
||||||
|
let before = conf('dawnline').get('dawnline', 'bob', 'code');
|
||||||
|
let mtime = stat('/etc/config/dawnline').mtime;
|
||||||
|
migrate.run();
|
||||||
|
eq(conf('dawnline').get('dawnline', 'bob', 'code'), before, 'the code is not drawn again');
|
||||||
|
eq(stat('/etc/config/dawnline').mtime, mtime, 'nothing written');
|
||||||
|
});
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Run the ucode unit tests against the real libuci: the fixture configs are
|
||||||
|
# copied into /etc/config (replacing what is there), the stand-in `awg` goes on
|
||||||
|
# PATH and tests/ucode/run.uc runs every *.test.uc. For a throw-away OpenWrt
|
||||||
|
# rootfs container (scripts/ucode-container.sh); on anything else it refuses
|
||||||
|
# unless DAWNLINE_TEST_FORCE=1, because it overwrites /etc/config/dawnline.
|
||||||
|
# tests/ucode/run.sh [REPO] [test name filter]
|
||||||
|
set -eu
|
||||||
|
REPO="$(cd "${1:-$(dirname "$0")/../..}" && pwd)"
|
||||||
|
T="$REPO/tests/ucode"
|
||||||
|
if [ ! -e /.dockerenv ] && [ "${DAWNLINE_TEST_FORCE:-}" != 1 ]; then
|
||||||
|
echo "run.sh replaces /etc/config/dawnline and /etc/config/uhttpd: run it in a container (scripts/ucode-container.sh)" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
cp "$T"/fixtures/config/* /etc/config/
|
||||||
|
mkdir -p /tmp/dawnline-tests /var/run/dawnline
|
||||||
|
PATH="$T/fixtures/bin:$PATH" ucode -L "$REPO/package/luci-app-dawnline/root/usr/share/ucode/*.uc" "$T/run.uc" "${2:-}"
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/ucode
|
||||||
|
'use strict';
|
||||||
|
// Dawnline ucode unit tests. Runs every *.test.uc beside this file (in name
|
||||||
|
// order; migrate.test.uc changes /etc/config/dawnline, so it sorts after the
|
||||||
|
// tests that read the fixture as it is) with four helpers in scope:
|
||||||
|
// test(name, fn) one case; a thrown error or die() fails it
|
||||||
|
// eq(got, want, note) deep equality (JSON form), note names the case
|
||||||
|
// ok(cond, note) a true value
|
||||||
|
// throws(fn, re, note) fn must throw; the message must match re when given
|
||||||
|
// tests/ucode/run.sh prepares the fixtures and starts this with the modules
|
||||||
|
// on -L; an optional argument runs only the files whose name contains it.
|
||||||
|
import { lsdir } from 'fs';
|
||||||
|
|
||||||
|
let dir = sourcepath(0, true);
|
||||||
|
let passed = 0, failed = 0, file = null;
|
||||||
|
|
||||||
|
function eq(got, want, note) {
|
||||||
|
let g = sprintf('%J', got), w = sprintf('%J', want);
|
||||||
|
if (g != w)
|
||||||
|
die(`${note ? note + ': ' : ''}got ${g}, want ${w}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ok(cond, note) {
|
||||||
|
if (!cond)
|
||||||
|
die(note ?? 'expected a true value');
|
||||||
|
}
|
||||||
|
|
||||||
|
function throws(fn, re, note) {
|
||||||
|
let msg = null;
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
msg = e.message ?? `${e}`;
|
||||||
|
}
|
||||||
|
if (msg == null)
|
||||||
|
die(`${note ?? 'call'} did not throw`);
|
||||||
|
if (re && !match(msg, re))
|
||||||
|
die(`${note ?? 'call'} threw "${msg}", not ${re}`);
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
function test(name, fn) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
passed++;
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
failed++;
|
||||||
|
// The first frame in the test file itself (not eq()/ok() in here).
|
||||||
|
let at = filter(e.stacktrace ?? [], (f) => f.filename && index(f.filename, '/run.uc') < 0)[0];
|
||||||
|
printf('FAIL %s: %s\n %s%s\n', file, name, e.message ?? `${e}`, at ? ` (${at.filename}:${at.line})` : '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (file in sort(lsdir(dir) ?? [])) {
|
||||||
|
if (!match(file, /\.test\.uc$/) || (ARGV[0] && index(file, ARGV[0]) < 0))
|
||||||
|
continue;
|
||||||
|
try {
|
||||||
|
include(`${dir}/${file}`, { test, eq, ok, throws });
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
failed++;
|
||||||
|
printf('FAIL %s: could not run\n %s\n', file, e.message ?? `${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf('%d passed, %d failed\n', passed, failed);
|
||||||
|
exit(failed ? 1 : 0);
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// dawnline.schema: what the admin may save (validate) and how stored values
|
||||||
|
// are read (get), one case per settings type.
|
||||||
|
import * as schema from 'dawnline.schema';
|
||||||
|
|
||||||
|
test('validate: bool', () => {
|
||||||
|
eq(schema.validate('portal_enabled', true), '1', 'true');
|
||||||
|
eq(schema.validate('portal_enabled', false), '0', 'false');
|
||||||
|
eq(schema.validate('portal_enabled', '1'), '1', 'string 1');
|
||||||
|
eq(schema.validate('portal_enabled', ''), null, 'empty removes the option');
|
||||||
|
throws(() => schema.validate('portal_enabled', 'yes'), /0 or 1/, 'yes');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: int', () => {
|
||||||
|
eq(schema.validate('portal_port', '8443'), '8443', 'in range');
|
||||||
|
eq(schema.validate('portal_port', ' 443 '), '443', 'trimmed');
|
||||||
|
eq(schema.validate('portal_port', '08443'), '8443', 'leading zero dropped');
|
||||||
|
eq(schema.validate('portal_port', 9000), '9000', 'number');
|
||||||
|
throws(() => schema.validate('portal_port', '0'), /free port/, 'below min');
|
||||||
|
throws(() => schema.validate('portal_port', '70000'), /free port/, 'above max');
|
||||||
|
throws(() => schema.validate('portal_port', 'abc'), /free port/, 'letters');
|
||||||
|
throws(() => schema.validate('portal_port', '-1'), /free port/, 'negative');
|
||||||
|
throws(() => schema.validate('default_device_limit', '33'), /1-32/, 'device limit');
|
||||||
|
eq(schema.validate('log_keep_days', '0'), '0', 'zero allowed where min is 0');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: enum', () => {
|
||||||
|
eq(schema.validate('geo_provider', 'ipapi.co'), 'ipapi.co', 'known');
|
||||||
|
throws(() => schema.validate('geo_provider', 'maxmind'), /Unknown location service/, 'unknown');
|
||||||
|
eq(schema.validate('update_interval', '7d'), '7d', 'interval from dawnline.updates');
|
||||||
|
throws(() => schema.validate('update_interval', '2d'), /6h, 12h, 1d or 7d/, 'unknown interval');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: host and hosts', () => {
|
||||||
|
eq(schema.validate('portal_host', 'vpn.example.com'), 'vpn.example.com', 'name');
|
||||||
|
eq(schema.validate('portal_host', '203.0.113.7'), '203.0.113.7', 'address');
|
||||||
|
throws(() => schema.validate('portal_host', 'bad host!'), /hostname or IP/, 'bad');
|
||||||
|
eq(schema.validate('portal_alt', [ 'a.example.com', ' a.example.com ', '', 'b.example.com' ]),
|
||||||
|
[ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, empty ones dropped');
|
||||||
|
throws(() => schema.validate('portal_alt', [ 'a.example.com', 'bad host' ]), /hostnames or IP/, 'a typo is refused, not dropped');
|
||||||
|
eq(schema.validate('portal_alt', []), null, 'empty list removes the option');
|
||||||
|
eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: url', () => {
|
||||||
|
eq(schema.validate('portal_redirect', 'https://example.com/x?y=1'), 'https://example.com/x?y=1', 'https with path');
|
||||||
|
eq(schema.validate('portal_redirect', 'http://example.com:8080'), 'http://example.com:8080', 'http with port');
|
||||||
|
throws(() => schema.validate('portal_redirect', 'ftp://example.com'), /full http/, 'scheme');
|
||||||
|
throws(() => schema.validate('portal_redirect', 'https://example.com/<x>'), /full http/, 'angle brackets');
|
||||||
|
throws(() => schema.validate('portal_redirect', 'https://example.com/' + replace(sprintf('%300s', ''), ' ', 'a')), /full http/, 'over 300 characters');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: file', () => {
|
||||||
|
eq(schema.validate('portal_cert', '/etc/passwd'), '/etc/passwd', 'existing file');
|
||||||
|
throws(() => schema.validate('portal_cert', '/nonexistent/cert.pem'), /does not exist/, 'missing');
|
||||||
|
throws(() => schema.validate('portal_cert', 'cert.pem'), /does not exist/, 'relative');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: domain', () => {
|
||||||
|
eq(schema.validate('domain', 'lan'), 'lan', 'single');
|
||||||
|
eq(schema.validate('domain', 'home.arpa'), 'home.arpa', 'dotted');
|
||||||
|
throws(() => schema.validate('domain', 'Lan'), /lowercase/, 'upper case');
|
||||||
|
throws(() => schema.validate('domain', replace(sprintf('%33s', ''), ' ', 'a')), /lowercase/, '33-char label');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: ipv4', () => {
|
||||||
|
eq(schema.validate('home_dns_fallback', '9.9.9.9'), '9.9.9.9', 'address');
|
||||||
|
eq(schema.validate('home_dns_fallback', ''), 'none', 'empty means no fallback');
|
||||||
|
throws(() => schema.validate('home_dns_fallback', '999.1.1.1'), /IPv4/, 'bad octet');
|
||||||
|
throws(() => schema.validate('home_dns_fallback', 'dns.example'), /IPv4/, 'name');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: time', () => {
|
||||||
|
eq(schema.validate('update_time', '04:00'), '04:00', 'padded');
|
||||||
|
eq(schema.validate('update_time', '4:00'), '4:00', 'unpadded');
|
||||||
|
eq(schema.validate('update_time', '23:59'), '23:59', 'last minute');
|
||||||
|
throws(() => schema.validate('update_time', '24:00'), /HH:MM/, 'hour 24');
|
||||||
|
throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: targets', () => {
|
||||||
|
eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once');
|
||||||
|
eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice');
|
||||||
|
eq(schema.validate('update_targets', 'app'), [ 'none' ], 'not a list');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: unknown key', () => {
|
||||||
|
throws(() => schema.validate('nonsense', '1'), /Unknown setting/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('get', () => {
|
||||||
|
eq(schema.get({ portal_enabled: 'on' }, 'portal_enabled'), true, 'bool synonyms');
|
||||||
|
eq(schema.get({ portal_enabled: 'maybe' }, 'portal_enabled'), false, 'bad bool is the default');
|
||||||
|
eq(schema.get({}, 'portal_enabled'), false, 'missing bool');
|
||||||
|
eq(schema.get({ portal_port: '443' }, 'portal_port'), 443, 'int');
|
||||||
|
eq(schema.get({ portal_port: '99999' }, 'portal_port'), 8443, 'int out of range is the default');
|
||||||
|
eq(schema.get({ portal_port: 'x' }, 'portal_port'), 8443, 'bad int');
|
||||||
|
eq(schema.get({}, 'portal_alt'), [], 'missing list');
|
||||||
|
eq(schema.get({ portal_alt: 'a.example.com' }, 'portal_alt'), [ 'a.example.com' ], 'single value as list');
|
||||||
|
eq(schema.get({ portal_alt: [ 'a', '' ] }, 'portal_alt'), [ 'a' ], 'empty entries dropped');
|
||||||
|
eq(schema.get({}, 'update_targets'), [ 'app', 'packages' ], 'default targets');
|
||||||
|
eq(schema.get({ geo_provider: 'ipapi.co' }, 'geo_provider'), 'ipapi.co', 'enum');
|
||||||
|
eq(schema.get({ geo_provider: 'x' }, 'geo_provider'), 'ipwho.is', 'bad enum is the default');
|
||||||
|
eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty');
|
||||||
|
eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4');
|
||||||
|
eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4');
|
||||||
|
eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through');
|
||||||
|
eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value');
|
||||||
|
eq(schema.get(null, 'portal_port'), 8443, 'no section');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parsing helpers', () => {
|
||||||
|
eq(schema.bool('TRUE', false), true, 'case-insensitive');
|
||||||
|
eq(schema.bool(' 0 ', true), false, 'trimmed');
|
||||||
|
eq(schema.bool(null, true), true, 'default');
|
||||||
|
eq(schema.to_int('-5', 0, 0, 10), 0, 'below min');
|
||||||
|
eq(schema.to_int('7', 0, 0, 10), 7, 'in range');
|
||||||
|
eq(schema.to_int('7.5', 0), 0, 'not whole');
|
||||||
|
ok(schema.valid_port('65535'), 'max port');
|
||||||
|
ok(!schema.valid_port('0'), 'port 0');
|
||||||
|
ok(!schema.valid_port('65536'), 'port 65536');
|
||||||
|
ok(!schema.valid_port('12a'), 'letters');
|
||||||
|
ok(!schema.valid_port(null), 'null');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('addresses', () => {
|
||||||
|
ok(schema.ipv4('10.0.0.1') && !schema.ipv4('10.0.0.256') && !schema.ipv4(null), 'ipv4');
|
||||||
|
eq(schema.ipv6_groups('::1'), [ 0, 0, 0, 0, 0, 0, 0, 1 ], 'loopback');
|
||||||
|
eq(schema.ipv6_groups('2001:db8::1'), [ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1 ], 'compressed');
|
||||||
|
eq(schema.ipv6_groups('::ffff:192.0.2.1'), [ 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x0201 ], 'embedded IPv4');
|
||||||
|
eq(schema.ipv6_groups('1:2:3:4:5:6:7:8'), [ 1, 2, 3, 4, 5, 6, 7, 8 ], 'full');
|
||||||
|
eq(schema.ipv6_groups('1:2:3:4:5:6:7:8:9'), null, 'nine groups');
|
||||||
|
eq(schema.ipv6_groups('1:2:3:4:5:6:7'), null, 'seven groups, no gap');
|
||||||
|
eq(schema.ipv6_groups('1::2::3'), null, 'two gaps');
|
||||||
|
eq(schema.ipv6_groups('fe80::1%eth0'), null, 'zone id');
|
||||||
|
eq(schema.ipv6_groups('12345::'), null, 'group too long');
|
||||||
|
ok(schema.ip('10.0.0.1') && schema.ip('fe80::1') && !schema.ip('nope'), 'ip');
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// dawnline.updates: the update policy from raw settings, what is due at a
|
||||||
|
// given time, and release version ordering.
|
||||||
|
import * as updates from 'dawnline.updates';
|
||||||
|
|
||||||
|
function at(y, mo, d, h, mi) {
|
||||||
|
return timelocal({ year: y, mon: mo, mday: d, hour: h, min: mi, sec: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
test('policy defaults', () => {
|
||||||
|
eq(updates.policy(null), { check: true, interval: '1d', auto: true, mode: 'scheduled', time: '04:00',
|
||||||
|
targets: [ 'app', 'packages' ], keep: false, mirrors: true }, 'no settings');
|
||||||
|
eq(updates.policy({}), updates.policy(null), 'empty settings');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('policy values', () => {
|
||||||
|
let p = updates.policy({ update_check: '0', update_interval: '7d', update_auto: 'no', update_mode: 'immediate',
|
||||||
|
update_time: '23:59', update_targets: 'amneziawg', update_keep: '1', update_mirrors: 'off' });
|
||||||
|
eq(p, { check: false, interval: '7d', auto: false, mode: 'immediate', time: '23:59', targets: [ 'amneziawg' ], keep: true, mirrors: false }, 'all set');
|
||||||
|
eq(updates.policy({ update_interval: '2d' }).interval, '1d', 'unknown interval');
|
||||||
|
eq(updates.policy({ update_time: '24:00' }).time, '04:00', 'bad time');
|
||||||
|
eq(updates.policy({ update_time: '4:30' }).time, '4:30', 'unpadded time');
|
||||||
|
eq(updates.policy({ update_mode: 'later' }).mode, 'scheduled', 'unknown mode');
|
||||||
|
eq(updates.policy({ update_targets: [ 'packages', 'bogus', 'app' ] }).targets, [ 'packages', 'app' ], 'unknown targets dropped');
|
||||||
|
eq(updates.policy({ update_targets: [ 'none' ] }).targets, [], '"none" is no target');
|
||||||
|
eq(updates.policy({ update_targets: [] }).targets, [], 'empty list');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('due', () => {
|
||||||
|
let pol = updates.policy({ update_time: '04:00' });
|
||||||
|
let t = at(2026, 3, 10, 4, 30);
|
||||||
|
eq(updates.due(pol, {}, t), 'install', 'in the window, never run');
|
||||||
|
eq(updates.due(pol, { install_day: '2026-03-10' }, t), 'check', 'window spent, check is due');
|
||||||
|
eq(updates.due(pol, { install_day: '2026-03-10', check: t - 3600 }, t), null, 'checked an hour ago');
|
||||||
|
eq(updates.due(pol, { check: t - 90000 }, at(2026, 3, 10, 12, 0)), 'check', 'outside the window, a day has passed');
|
||||||
|
eq(updates.due(pol, {}, at(2026, 3, 10, 5, 30)), 'check', 'window over (an hour)');
|
||||||
|
eq(updates.due(updates.policy({ update_auto: '0', update_check: '0' }), {}, t), null, 'everything off');
|
||||||
|
eq(updates.due(updates.policy({ update_mode: 'immediate' }), {}, t), 'check', 'immediate mode has no window');
|
||||||
|
eq(updates.due(updates.policy({ update_targets: [] }), {}, t), 'check', 'nothing to install');
|
||||||
|
let late = updates.policy({ update_time: '23:30' });
|
||||||
|
eq(updates.due(late, {}, at(2026, 3, 11, 0, 15)), 'install', 'window across midnight');
|
||||||
|
eq(updates.mark_day(late, {}, at(2026, 3, 11, 0, 15)).install_day, '2026-03-10', 'mark_day records the slot\'s day');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('version_cmp', () => {
|
||||||
|
eq(updates.version_cmp('0.5.1', '0.5.1'), 0, 'equal');
|
||||||
|
eq(updates.version_cmp('v0.5.1', '0.5.1'), 0, 'v prefix');
|
||||||
|
eq(updates.version_cmp('0.5.1', '0.5.2'), -1, 'patch');
|
||||||
|
eq(updates.version_cmp('0.10.0', '0.9.9'), 1, 'numbers, not strings');
|
||||||
|
eq(updates.version_cmp('0.6', '0.6.0'), 0, 'missing part is zero');
|
||||||
|
eq(updates.version_cmp('0.6.0-rc1', '0.6.0'), -1, 'pre-release before the release');
|
||||||
|
eq(updates.version_cmp('0.6.0-rc2', '0.6.0-rc10'), -1, 'rc numbers as numbers');
|
||||||
|
eq(updates.version_cmp('0.6.0-beta', '0.6.0-rc1'), -1, 'beta before rc');
|
||||||
|
eq(updates.version_cmp('garbage', '0.1'), -1, 'unparsable is lowest');
|
||||||
|
});
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
// dawnline.util: validation, addresses, slugs and dates (pure functions).
|
||||||
|
import * as util from 'dawnline.util';
|
||||||
|
|
||||||
|
test('valid_name', () => {
|
||||||
|
ok(util.valid_name('Alice'), 'plain');
|
||||||
|
ok(util.valid_name('Мама'), 'non-ASCII letters');
|
||||||
|
ok(!util.valid_name(''), 'empty');
|
||||||
|
ok(!util.valid_name(' '), 'blank');
|
||||||
|
ok(!util.valid_name(null), 'null');
|
||||||
|
ok(!util.valid_name(42), 'number');
|
||||||
|
ok(util.valid_name('a' + replace(sprintf('%47s', ''), ' ', 'b')), '48 characters');
|
||||||
|
ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 characters');
|
||||||
|
ok(util.valid_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧ'), '25 Cyrillic letters (50 bytes) are 25 characters');
|
||||||
|
ok(!util.valid_name('Bob "B"'), 'quotes');
|
||||||
|
ok(!util.valid_name('a<b'), 'angle bracket');
|
||||||
|
ok(!util.valid_name('a"b'), 'quote');
|
||||||
|
ok(!util.valid_name('a\\b'), 'backslash');
|
||||||
|
ok(!util.valid_name('a\tb'), 'control character');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid_host', () => {
|
||||||
|
ok(util.valid_host('vpn.example.com'), 'name');
|
||||||
|
ok(util.valid_host('router'), 'single label');
|
||||||
|
ok(util.valid_host('203.0.113.7'), 'IPv4');
|
||||||
|
ok(util.valid_host('2001:db8::1'), 'IPv6');
|
||||||
|
ok(!util.valid_host('-a.example.com'), 'leading dash');
|
||||||
|
ok(!util.valid_host('a..example.com'), 'empty label');
|
||||||
|
ok(!util.valid_host('bad host'), 'space');
|
||||||
|
ok(!util.valid_host(''), 'empty');
|
||||||
|
ok(!util.valid_host(null), 'null');
|
||||||
|
let label = replace(sprintf('%63s', ''), ' ', 'a');
|
||||||
|
ok(util.valid_host(`${label}.example`), '63-char label');
|
||||||
|
ok(!util.valid_host(`${label}a.example`), '64-char label');
|
||||||
|
ok(!util.valid_host(join('.', [ label, label, label, label, 'x' ])), 'over 253 characters');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid_date', () => {
|
||||||
|
ok(util.valid_date('2026-01-31'), 'ISO day');
|
||||||
|
ok(!util.valid_date('2026-1-31'), 'no padding');
|
||||||
|
ok(!util.valid_date('20260131'), 'no dashes');
|
||||||
|
ok(!util.valid_date('2026-01-31T00:00'), 'trailing time');
|
||||||
|
ok(!util.valid_date(20260131), 'not a string');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid_slug and valid_key', () => {
|
||||||
|
ok(util.valid_slug('alice'), 'word');
|
||||||
|
ok(util.valid_slug('a'), 'one character');
|
||||||
|
ok(util.valid_slug('alice-2'), 'dash inside');
|
||||||
|
ok(!util.valid_slug('-alice'), 'leading dash');
|
||||||
|
ok(!util.valid_slug('Alice'), 'upper case');
|
||||||
|
ok(!util.valid_slug(replace(sprintf('%33s', ''), ' ', 'a')), '33 characters');
|
||||||
|
ok(util.valid_key('yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='), 'WireGuard key');
|
||||||
|
ok(!util.valid_key('yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk'), 'no padding');
|
||||||
|
ok(!util.valid_key('yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmb='), 'impossible last sextet');
|
||||||
|
ok(!util.valid_key(''), 'empty');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ip2int / int2ip / cidr_any', () => {
|
||||||
|
eq(util.ip2int('10.9.0.1'), 168361985, 'ip2int');
|
||||||
|
eq(util.int2ip(168361985), '10.9.0.1', 'int2ip');
|
||||||
|
eq(util.ip2int('256.0.0.1'), null, 'octet over 255');
|
||||||
|
eq(util.ip2int('1.2.3'), null, 'three octets');
|
||||||
|
eq(util.cidr_any('10.0.0.5'), { net: util.ip2int('10.0.0.5'), prefix: 32, size: 1, ip: util.ip2int('10.0.0.5') }, 'bare address is a /32');
|
||||||
|
eq(util.cidr_any('10.0.0.5/8'), { net: util.ip2int('10.0.0.0'), prefix: 8, size: 16777216, ip: util.ip2int('10.0.0.5') }, 'masked base');
|
||||||
|
eq(util.cidr_any('10.0.0.0/33'), null, 'prefix over 32');
|
||||||
|
eq(util.cidr_any(null), null, 'null');
|
||||||
|
eq(util.in_nets('10.9.0.7', [ '192.168.0.0/16', '10.9.0.0/29' ]), '10.9.0.0/29', 'first match');
|
||||||
|
eq(util.in_nets('10.9.0.8', [ '10.9.0.0/29' ]), null, 'just outside');
|
||||||
|
eq(util.in_nets('nonsense', [ '10.9.0.0/29' ]), null, 'not an address');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parse_cidr', () => {
|
||||||
|
let c = util.parse_cidr('10.9.0.0/24');
|
||||||
|
eq([ util.int2ip(c.net), c.prefix, c.size, util.int2ip(c.first), util.int2ip(c.last) ], [ '10.9.0.0', 24, 256, '10.9.0.1', '10.9.0.254' ], '/24');
|
||||||
|
eq(util.int2ip(util.parse_cidr('10.9.0.77/24').net), '10.9.0.0', 'host bits masked off');
|
||||||
|
eq(util.cidr_str(util.parse_cidr('10.9.0.77/24')), '10.9.0.0/24', 'cidr_str');
|
||||||
|
eq(util.parse_cidr('10.9.0.0/7'), null, 'too wide');
|
||||||
|
eq(util.parse_cidr('10.9.0.0/31'), null, 'too narrow');
|
||||||
|
eq(util.parse_cidr('10.9.0.0'), null, 'no prefix');
|
||||||
|
eq(util.parse_cidr('300.0.0.0/24'), null, 'bad octet');
|
||||||
|
eq(util.parse_cidr(null), null, 'null');
|
||||||
|
ok(util.cidr_overlaps(util.parse_cidr('10.9.0.0/24'), util.parse_cidr('10.9.0.128/25')), 'overlap');
|
||||||
|
ok(!util.cidr_overlaps(util.parse_cidr('10.9.0.0/24'), util.parse_cidr('10.9.1.0/24')), 'adjacent');
|
||||||
|
ok(util.in_cidr('10.9.0.200', util.parse_cidr('10.9.0.0/24')), 'in_cidr');
|
||||||
|
ok(!util.in_cidr('10.9.1.1', util.parse_cidr('10.9.0.0/24')), 'not in_cidr');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cloudflare_ip', () => {
|
||||||
|
ok(util.cloudflare_ip('104.16.1.1'), 'v4 range');
|
||||||
|
ok(util.cloudflare_ip('2606:4700::1'), 'v6 range');
|
||||||
|
ok(!util.cloudflare_ip('8.8.8.8'), 'other v4');
|
||||||
|
ok(!util.cloudflare_ip('2001:db8::1'), 'other v6');
|
||||||
|
ok(!util.cloudflare_ip(null), 'null');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('slugify', () => {
|
||||||
|
eq(util.slugify('Alice Smith'), 'alice-smith', 'spaces to dashes');
|
||||||
|
eq(util.slugify(' --Bob!! '), 'bob', 'trimmed dashes');
|
||||||
|
eq(util.slugify(''), 'user', 'empty');
|
||||||
|
eq(util.slugify(null), 'user', 'null');
|
||||||
|
eq(util.slugify('Мама'), 'mama', 'Cyrillic written in Latin');
|
||||||
|
eq(util.slugify('Юля Щукина'), 'yulya-shchukina', 'Cyrillic words');
|
||||||
|
eq(util.slugify('日本'), 'user', 'nothing left');
|
||||||
|
eq(length(util.slugify(replace(sprintf('%40s', ''), ' ', 'x'))), 32, 'cut at 32');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dates', () => {
|
||||||
|
let end = util.date_end('2026-02-28');
|
||||||
|
let t = localtime(end);
|
||||||
|
eq([ t.year, t.mon, t.mday, t.hour, t.min, t.sec ], [ 2026, 2, 28, 23, 59, 59 ], 'end of the local day');
|
||||||
|
eq(util.date_end('2026-2-28'), null, 'bad date');
|
||||||
|
let noon = timelocal({ year: 2026, mon: 3, mday: 1, hour: 12, min: 0, sec: 0 });
|
||||||
|
eq(util.day_key(noon), '2026-03-01', 'day_key');
|
||||||
|
eq(util.month_key(noon), '2026-03', 'month_key');
|
||||||
|
eq(util.day_key_ago(1, noon), '2026-02-28', 'day_key_ago crosses the month');
|
||||||
|
eq(util.day_key_ago(0, noon), '2026-03-01', 'zero days');
|
||||||
|
eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('text: ulength, ucut, translit, host_label, tunnel_name', () => {
|
||||||
|
eq(util.ulength('Мама'), 4, 'characters, not bytes');
|
||||||
|
eq(util.ulength('abc'), 3, 'ascii');
|
||||||
|
eq(util.ucut('Привет', 3), 'При', 'cut by characters');
|
||||||
|
eq(util.ucut('ab', 5), 'ab', 'shorter than the cut');
|
||||||
|
eq(util.translit('Мама Таня'), 'mama tanya', 'Russian');
|
||||||
|
eq(util.translit('Їжак Ґава ёж'), 'yizhak gava yozh', 'Ukrainian letters and ё');
|
||||||
|
eq(util.translit('Mixed Текст 1'), 'Mixed tekst 1', 'Latin and digits pass');
|
||||||
|
eq(util.host_label('Galaxy S24'), 'galaxy-s24', 'label');
|
||||||
|
eq(util.host_label('Телефон Ёжика'), 'telefon-yozhika', 'Cyrillic label');
|
||||||
|
eq(util.tunnel_name('Outline Home'), 'Outline-Home', 'tunnel name keeps the case');
|
||||||
|
eq(util.tunnel_name('Дом у моря'), 'dom-u-morya', 'Cyrillic tunnel name');
|
||||||
|
eq(util.tunnel_name(' My VPN (home)! '), 'My-VPN-home', 'tunnel name: runs of other characters are one dash');
|
||||||
|
eq(util.tunnel_name('A very long server name'), 'A-very-long-ser', 'tunnel name: 15 characters at most');
|
||||||
|
eq(util.tunnel_name('Home server 12345'), 'Home-server-123', 'tunnel name: cut');
|
||||||
|
eq(util.tunnel_name('Lakeside house x'), 'Lakeside-house', 'tunnel name: no dash left at the cut');
|
||||||
|
eq(util.tunnel_name('nul'), 'dawnline', 'tunnel name: a Windows device name');
|
||||||
|
eq(util.tunnel_name('COM1'), 'dawnline', 'tunnel name: a Windows device name, any case');
|
||||||
|
eq(util.tunnel_name('???'), 'dawnline', 'tunnel name: nothing left');
|
||||||
|
eq(util.tunnel_name(null), 'dawnline', 'tunnel name: null');
|
||||||
|
eq(util.host_label('!!!'), 'device', 'nothing left');
|
||||||
|
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// dawnline.view: which device a portal page was opened from, and the usage series it draws.
|
||||||
|
import * as view from 'dawnline.view';
|
||||||
|
import { day_key_ago } from 'dawnline.util';
|
||||||
|
|
||||||
|
const devs = [
|
||||||
|
{ id: 'd_1', address: '10.0.0.2', online: true, endpoint: '203.0.113.7' },
|
||||||
|
{ id: 'd_2', address: '10.0.0.3', online: false, endpoint: '198.51.100.4' },
|
||||||
|
{ id: 'd_3', address: '10.0.0.4', online: true, endpoint: '192.0.2.9' },
|
||||||
|
];
|
||||||
|
|
||||||
|
test('device_here', () => {
|
||||||
|
eq(view.device_here(devs, '10.0.0.3'), 'd_2', 'through the tunnel: its address, online or not');
|
||||||
|
eq(view.device_here(devs, '203.0.113.7'), 'd_1', 'beside the tunnel: where its tunnel comes from');
|
||||||
|
eq(view.device_here(devs, '::ffff:203.0.113.7'), 'd_1', 'an IPv4 request on a dual-stack socket');
|
||||||
|
eq(view.device_here(devs, '198.51.100.4'), null, 'a device that is not online does not count');
|
||||||
|
eq(view.device_here(devs, '233.252.0.1'), null, 'from elsewhere');
|
||||||
|
eq(view.device_here([ ...devs, { id: 'd_4', address: '10.0.0.5', online: true, endpoint: '203.0.113.7' } ], '203.0.113.7'), null,
|
||||||
|
'two devices behind one address: neither');
|
||||||
|
eq(view.device_here(devs, ''), null, 'no address');
|
||||||
|
eq(view.device_here([ { id: 'd_5', address: '10.0.0.6', online: true, endpoint: '' } ], ''), null, 'no address, no endpoint');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('month_days', () => {
|
||||||
|
let n = +substr(day_key_ago(0), 8, 2);
|
||||||
|
let days = {};
|
||||||
|
// On the 1st, today is the 1st: then only today's own value.
|
||||||
|
if (n > 1)
|
||||||
|
days[day_key_ago(n - 1)] = [ 1, 2 ];
|
||||||
|
days[day_key_ago(0)] = [ 5, 7 ];
|
||||||
|
// Last month's last day stays out of this month's chart.
|
||||||
|
days[day_key_ago(n)] = [ 100, 100 ];
|
||||||
|
let s = view.month_days({ days });
|
||||||
|
eq(length(s), n, 'one bar a day, from the 1st to today');
|
||||||
|
eq(s[n - 1], 12, 'today last, received and sent together');
|
||||||
|
eq(s[0], n > 1 ? 3 : 12, 'the 1st first');
|
||||||
|
eq(length(view.month_days(null)), n, 'no usage yet: zeros');
|
||||||
|
eq(view.month_days(null)[0], 0, 'a day without traffic is zero');
|
||||||
|
});
|
||||||
@@ -452,6 +452,10 @@ do_backup() {
|
|||||||
do_teardown() {
|
do_teardown() {
|
||||||
step "Running Dawnline's own removal"
|
step "Running Dawnline's own removal"
|
||||||
if ubus list luci.dawnline >/dev/null 2>&1; then
|
if ubus list luci.dawnline >/dev/null 2>&1; then
|
||||||
|
# The removal takes the update lock itself: hand it over (the service is
|
||||||
|
# stopped first, so no automatic update can slip in between).
|
||||||
|
[ "$DRY_RUN" -eq 1 ] || /etc/init.d/dawnline stop >/dev/null 2>&1
|
||||||
|
exec 8>&- 2>/dev/null
|
||||||
# The same call as Settings → Remove Dawnline from this router.
|
# The same call as Settings → Remove Dawnline from this router.
|
||||||
if act "call luci.dawnline uninstall (Settings → Remove Dawnline)" rpc \
|
if act "call luci.dawnline uninstall (Settings → Remove Dawnline)" rpc \
|
||||||
ubus -t 120 call luci.dawnline uninstall '{"confirm":"remove"}'; then
|
ubus -t 120 call luci.dawnline uninstall '{"confirm":"remove"}'; then
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.4.2",
|
"version": "0.10.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.4.2",
|
"version": "0.10.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"qrcode-generator": "1.4.4"
|
"qrcode-generator": "1.4.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "22.20.5",
|
||||||
"prettier": "3.6.2",
|
"prettier": "3.6.2",
|
||||||
"tsup": "8.5.0",
|
"tsup": "8.5.0",
|
||||||
"typescript": "5.9.3",
|
"typescript": "5.9.3",
|
||||||
@@ -933,6 +934,16 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/node": {
|
||||||
|
"version": "22.20.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||||
|
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~6.21.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@vitest/expect": {
|
"node_modules/@vitest/expect": {
|
||||||
"version": "3.2.4",
|
"version": "3.2.4",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz",
|
||||||
@@ -1973,6 +1984,13 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/undici-types": {
|
||||||
|
"version": "6.21.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||||
|
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "7.3.7",
|
"version": "7.3.7",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz",
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.4.2",
|
"version": "0.10.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc --noEmit && tsup",
|
"build": "tsc --noEmit && tsup",
|
||||||
"dev": "tsup --watch",
|
"dev": "tsup --watch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"format:check": "prettier --check .",
|
"format:check": "prettier --check .",
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
"qrcode-generator": "1.4.4"
|
"qrcode-generator": "1.4.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/node": "22.20.5",
|
||||||
"prettier": "3.6.2",
|
"prettier": "3.6.2",
|
||||||
"tsup": "8.5.0",
|
"tsup": "8.5.0",
|
||||||
"typescript": "5.9.3",
|
"typescript": "5.9.3",
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import { E } from './e';
|
|||||||
import { api, type HomeHost } from './api';
|
import { api, type HomeHost } from './api';
|
||||||
import { button } from './ui/button';
|
import { button } from './ui/button';
|
||||||
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
|
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
|
||||||
import { attempt } from './ui/toast';
|
import { attempt, notify } from './ui/toast';
|
||||||
import { chipToggle, input } from './ui/controls';
|
import { chipToggle, input } from './ui/controls';
|
||||||
|
import { firstBad, liveField } from './ui/layout';
|
||||||
|
import { circleNameHelp, ipv4Help, nameHelp, portsHelp } from './netcheck';
|
||||||
import { icon } from '../shared/icons';
|
import { icon } from '../shared/icons';
|
||||||
|
|
||||||
type Service = Status['services'][number];
|
type Service = Status['services'][number];
|
||||||
@@ -30,17 +32,23 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
|
|||||||
placeholder: 'All ports, or e.g. 445, 5000',
|
placeholder: 'All ports, or e.g. 445, 5000',
|
||||||
class: 'cbi-input-text dl-mono',
|
class: 'cbi-input-text dl-mono',
|
||||||
});
|
});
|
||||||
const field = (label: string, el: Node) =>
|
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown to people who may reach it.'));
|
||||||
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
const addrRow = liveField('Address', addr, () => ipv4Help(addr.value));
|
||||||
|
const portsRow = liveField('Ports', ports, () => portsHelp(ports.value));
|
||||||
modal(
|
modal(
|
||||||
sv ? `Edit ${sv.name}` : 'Add service',
|
sv ? `Edit ${sv.name}` : 'Add service',
|
||||||
[field('Name', name), field('Address', addr), field('Ports', ports)],
|
[nameRow, addrRow, portsRow],
|
||||||
[
|
[
|
||||||
cancelButton(),
|
cancelButton(),
|
||||||
' ',
|
' ',
|
||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
async () => {
|
async () => {
|
||||||
|
const bad = firstBad([nameRow, addrRow, portsRow]);
|
||||||
|
if (bad) {
|
||||||
|
notify(bad, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
||||||
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
|
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
|
||||||
closeModal();
|
closeModal();
|
||||||
@@ -316,11 +324,13 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
|||||||
);
|
);
|
||||||
const field = (label: string, el: Node) =>
|
const field = (label: string, el: Node) =>
|
||||||
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
||||||
|
const others = st.circles.filter((c) => c.server === serverId && c.id !== ci?.id).map((c) => c.name);
|
||||||
|
const nameRow = liveField('Name', name, () => circleNameHelp(name.value, others));
|
||||||
|
|
||||||
modal(
|
modal(
|
||||||
ci ? `Edit ${ci.name}` : 'New circle',
|
ci ? `Edit ${ci.name}` : 'New circle',
|
||||||
[
|
[
|
||||||
field('Name', name),
|
nameRow,
|
||||||
field('Colour', swatches),
|
field('Colour', swatches),
|
||||||
field('People', chips),
|
field('People', chips),
|
||||||
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
|
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
|
||||||
@@ -344,6 +354,11 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
|||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
async () => {
|
async () => {
|
||||||
|
const h = nameRow.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
|
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
|
||||||
closeModal();
|
closeModal();
|
||||||
onDone();
|
onDone();
|
||||||
|
|||||||
@@ -1,14 +1,23 @@
|
|||||||
// luci.dawnline RPC bindings. The backend reports failures as { error }.
|
// luci.dawnline RPC bindings. The backend reports failures as { error }, and
|
||||||
|
// a change the router saved but could not fully put into effect (access rules
|
||||||
|
// that did not load, a server that refused its devices) as { warning }.
|
||||||
|
|
||||||
|
import type { Network, PortHold } from './netcheck';
|
||||||
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
|
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
|
||||||
|
import { notify } from './ui/toast';
|
||||||
|
|
||||||
|
/** Throw a backend failure; show a warning the answer carries. */
|
||||||
|
function settle<T>(r: any): T {
|
||||||
|
if (r && typeof r === 'object') {
|
||||||
|
if (typeof r.error === 'string') throw new Error(r.error);
|
||||||
|
if (typeof r.warning === 'string' && r.warning) notify(r.warning, 'warning', 12000);
|
||||||
|
}
|
||||||
|
return r as T;
|
||||||
|
}
|
||||||
|
|
||||||
function call<T>(method: string, params: string[] = []) {
|
function call<T>(method: string, params: string[] = []) {
|
||||||
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
|
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
|
||||||
return async (...args: unknown[]): Promise<T> => {
|
return async (...args: unknown[]): Promise<T> => settle<T>(await fn(...args));
|
||||||
const r = await fn(...args);
|
|
||||||
if (r && typeof r === 'object' && typeof r.error === 'string') throw new Error(r.error);
|
|
||||||
return r as T;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SetupDefaults {
|
export interface SetupDefaults {
|
||||||
@@ -23,9 +32,31 @@ export interface SetupDefaults {
|
|||||||
lan_zone: string;
|
lan_zone: string;
|
||||||
wan_zone: string;
|
wan_zone: string;
|
||||||
portal_port: number;
|
portal_port: number;
|
||||||
taken: string[];
|
/** Networks the tunnel must not overlap: the router's and the other servers'. */
|
||||||
|
networks: Network[];
|
||||||
|
/** UDP ports the server can't take, TCP ports the portal can't. */
|
||||||
|
udp_taken: PortHold[];
|
||||||
|
tcp_taken: PortHold[];
|
||||||
awg: AwgCaps;
|
awg: AwgCaps;
|
||||||
awg_state?: AwgState;
|
awg_state?: AwgState;
|
||||||
|
/** Where the suggested address came from: ddns, cert, wan, portal ('' = nothing found). */
|
||||||
|
endpoint_from?: string;
|
||||||
|
/** What the WAN's IPv4 is: public, private (behind another router), cgnat, none. */
|
||||||
|
wan_kind?: 'public' | 'private' | 'cgnat' | 'none';
|
||||||
|
wan_ip?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a public address points (rpc endpoint_probe): the facts and their verdict in words. */
|
||||||
|
export interface EndpointProbe {
|
||||||
|
host: string;
|
||||||
|
ips: string[];
|
||||||
|
wan: string | null;
|
||||||
|
kind: 'public' | 'private' | 'cgnat' | 'none';
|
||||||
|
cloudflare: boolean;
|
||||||
|
here: boolean;
|
||||||
|
v6_only: boolean;
|
||||||
|
status: 'ok' | 'warn' | 'error';
|
||||||
|
text: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Backup {
|
export interface Backup {
|
||||||
@@ -176,7 +207,8 @@ export interface SettingsData {
|
|||||||
effective: Record<string, unknown>;
|
effective: Record<string, unknown>;
|
||||||
services: { id: string; name: string; address: string; ports: string[] }[];
|
services: { id: string; name: string; address: string; ports: string[] }[];
|
||||||
cert: { path: string; self_signed: boolean; expires: string | null } | null;
|
cert: { path: string; self_signed: boolean; expires: string | null } | null;
|
||||||
port_owners: string[];
|
/** TCP ports the portal can't take. */
|
||||||
|
tcp_taken: PortHold[];
|
||||||
wan443_taken?: boolean;
|
wan443_taken?: boolean;
|
||||||
portal_public_port?: number;
|
portal_public_port?: number;
|
||||||
geo_cached: number;
|
geo_cached: number;
|
||||||
@@ -309,7 +341,8 @@ export type PersonPatch = Partial<
|
|||||||
| 'bonus_gb'
|
| 'bonus_gb'
|
||||||
| 'hours'
|
| 'hours'
|
||||||
| 'note'
|
| 'note'
|
||||||
| 'dns_mode',
|
| 'dns_mode'
|
||||||
|
| 'server',
|
||||||
string
|
string
|
||||||
>
|
>
|
||||||
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
|
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
|
||||||
@@ -335,6 +368,7 @@ const personUpdateRaw = rpc.declare<any>({
|
|||||||
'services',
|
'services',
|
||||||
'circle',
|
'circle',
|
||||||
'home_nets',
|
'home_nets',
|
||||||
|
'server',
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -353,10 +387,8 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
|
|||||||
'note',
|
'note',
|
||||||
'dns_mode',
|
'dns_mode',
|
||||||
] as const;
|
] as const;
|
||||||
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets];
|
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets, patch.server];
|
||||||
const r = await personUpdateRaw(...args);
|
return settle(await personUpdateRaw(...args));
|
||||||
if (r && typeof r.error === 'string') throw new Error(r.error);
|
|
||||||
return r;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const status = call<Status>('status', ['days']);
|
const status = call<Status>('status', ['days']);
|
||||||
@@ -393,7 +425,7 @@ export interface ServiceLog {
|
|||||||
export type Health = { checks: HealthCheck[] } & ServiceLog;
|
export type Health = { checks: HealthCheck[] } & ServiceLog;
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
rev: call<{ rev: number }>('rev'),
|
rev: call<{ rev: number; version?: string }>('rev'),
|
||||||
personUpdate,
|
personUpdate,
|
||||||
settingsGet: call<SettingsData>('settings_get'),
|
settingsGet: call<SettingsData>('settings_get'),
|
||||||
portalInfo: call<PortalInfo>('portal_info'),
|
portalInfo: call<PortalInfo>('portal_info'),
|
||||||
@@ -401,7 +433,8 @@ export const api = {
|
|||||||
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
|
serviceSet: call<{ id: string }>('service_set', ['id', 'name', 'address', 'ports']),
|
||||||
serviceDelete: call<unknown>('service_delete', ['id']),
|
serviceDelete: call<unknown>('service_delete', ['id']),
|
||||||
geoClear: call<unknown>('geo_clear'),
|
geoClear: call<unknown>('geo_clear'),
|
||||||
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit']),
|
/** The newest `limit` events; a person's only, or only those after `since` (a ts), when given. */
|
||||||
|
events: call<{ events: LogEvent[]; total: number; policy: LogsInfo['policy'] }>('events', ['limit', 'person', 'since']),
|
||||||
logsClear,
|
logsClear,
|
||||||
interfaces: call<InterfacesData>('interfaces', ['id']),
|
interfaces: call<InterfacesData>('interfaces', ['id']),
|
||||||
serverInterfaces: call<InterfacesData>('server_interfaces', [
|
serverInterfaces: call<InterfacesData>('server_interfaces', [
|
||||||
@@ -422,7 +455,7 @@ export const api = {
|
|||||||
uninstall: call<unknown>('uninstall', ['confirm']),
|
uninstall: call<unknown>('uninstall', ['confirm']),
|
||||||
status,
|
status,
|
||||||
setupDefaults: call<SetupDefaults>('setup_defaults'),
|
setupDefaults: call<SetupDefaults>('setup_defaults'),
|
||||||
serverCreate: call<{ id: string }>('server_create', [
|
serverCreate: call<{ id: string; network_restart?: boolean }>('server_create', [
|
||||||
'id',
|
'id',
|
||||||
'name',
|
'name',
|
||||||
'ifname',
|
'ifname',
|
||||||
@@ -439,6 +472,10 @@ export const api = {
|
|||||||
]),
|
]),
|
||||||
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
|
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
|
||||||
serverUpdate: call<unknown>('server_update', ['id', 'values']),
|
serverUpdate: call<unknown>('server_update', ['id', 'values']),
|
||||||
|
/** What an existing server's ports and a new tunnel network must avoid (checked as you type). */
|
||||||
|
serverPorts: call<{ udp_taken: PortHold[]; tcp_taken: PortHold[]; networks?: Network[] }>('server_ports', ['id']),
|
||||||
|
/** Where a public address points, for the live help under the field (debounced by the caller). */
|
||||||
|
endpointProbe: call<EndpointProbe>('endpoint_probe', ['host', 'id', 'port']),
|
||||||
serverDelete: call<unknown>('server_delete', ['id']),
|
serverDelete: call<unknown>('server_delete', ['id']),
|
||||||
/** The personal link, its code and every address it works on (main first); not part of the status. */
|
/** 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']),
|
personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']),
|
||||||
@@ -453,10 +490,10 @@ export const api = {
|
|||||||
'quota_period',
|
'quota_period',
|
||||||
]),
|
]),
|
||||||
personPause: call<unknown>('person_pause', ['id', 'paused']),
|
personPause: call<unknown>('person_pause', ['id', 'paused']),
|
||||||
personRegen: call<{ link: string | null }>('person_regen', ['id']),
|
/** A new link; `remove` lists devices (ids) to take away with the old one. */
|
||||||
|
personRegen: call<{ link: string | null; removed: number }>('person_regen', ['id', 'remove']),
|
||||||
personDelete: call<unknown>('person_delete', ['id']),
|
personDelete: call<unknown>('person_delete', ['id']),
|
||||||
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
personUsage: call<{ person: DayUsage[]; devices: Record<string, DayUsage[]> }>('person_usage', ['id', 'days']),
|
||||||
pauseAll: call<unknown>('pause_all', ['paused']),
|
|
||||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
||||||
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
deviceConfig: call<ClientConfig>('device_config', ['id']),
|
||||||
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
|
deviceUpdate: call<unknown>('device_update', ['id', 'name', 'disabled']),
|
||||||
|
|||||||