Dawnline 0.6.0
- Access rules fail closed: when the table cannot load, no device is loaded into the tunnels (the firewall alone would let every loaded device reach everything); an older table that survived a failed rebuild keeps its rules and a revoked device still leaves. The agent re-syncs within a minute when the table is gone - A change the router saved but could not put into effect (access rules that did not load, a server that refused its devices) is said in the admin UI instead of a plain "Saved" - The guard judges every packet, not only a connection's first: a change of access, a pause or a limit now cuts open connections too - Each server's home networks are its own: with several servers, "all home" on one no longer reaches the other's networks where firewall zones overlap - People limited to some home networks reach the router only on the addresses in those networks (LuCI and SSH on the main LAN stay closed) - Internet-only people can open their personal portal with the VPN on - Tunnel DNS reaches the resolver and the LAN's DNS from servers that do not forward to those zones on their own (Home-only names on servers without "like a home device", LAN DNS on servers with no home network) - A new personal link offers to remove the devices added through the old one, so a leaked link is really contained - Import and restore refuse an inconsistent file (devices with addresses outside their server, shared addresses, malformed keys, broken references); Health reports one, and the sync leaves such a device out instead of failing its server. A config write that did not reach flash is an error, not a silent success - Backups are kept per kind (nightly ones no longer push out manual or pre-delete ones), nightly and pre-change backups hold the config only, archives are written whole or not at all, and a failed nightly backup is logged. A restore no longer has its history overwritten by the agent's in-memory counters - Settings defaults and ranges come from one place (dawnline.schema) - Portal: anything not shaped like a personal link is answered by a shell before ucode starts (a scan on the root costs nothing); 4 portal processes at once instead of 16; a link may make 40 changes a quarter hour; over plain HTTP the page shows but configurations, new devices and new keys are refused with the HTTPS twin of the link; the connect sheet polls only while the first connection is awaited, with backoff, and stops once the link stopped working - Updates: after Dawnline's own package changes, a shell checks that LuCI reaches it and the agent runs, and puts the kept previous version back when they do not (automatic runs always keep it); the AmneziaWG module reload verifies rmmod and modprobe; installs check free space; on apk a reinstall that changed nothing is an error; uninstall.sh hands the update lock to the removal it calls; an upgrade restarts the service only where it was enabled; the release workflow pins the SDK images by digest and the actions by commit - AmneziaWG: features count only when both the tools and the kernel module have them; a server whose disguise this build cannot run (a 3.1 preset after a rollback to 2.0) is kept down and reported; Components tells 1.0 builds from 2.0 ones; `awg show dump` is parsed by shape; Maximum's DNS-shaped signature packets are made for each server and its keep-alive is a 25-35 s range - CI compiles every ucode file and runs the new tests/ucode unit tests (54 tests on the real libuci) in OpenWrt 24.10 and 25.12 rootfs containers; scripts/compile-ucode.sh does the same wherever ucode runs and scripts/ucode-container.sh locally with docker; lint-ucode checks POSIX regexes and module layering; a tag builds only after CI passes
This commit is contained in:
1 parent
2b98abdba4
commit
31a2065f05
70 files changed
+2008
-307
No files matched your search
+19
-10
@@ -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 }}
|
||||||
|
|||||||
+65
-16
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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.5.2
|
PKG_VERSION:=0.6.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 ur=Object.create;var oo=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var hr=Object.getOwnPropertyNames;var fr=Object.getPrototypeOf,gr=Object.prototype.hasOwnProperty;var vr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var br=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hr(e))!gr.call(n,r)&&r!==o&&oo(n,r,{get:()=>e[r],enumerable:!(a=mr(e,r))||a.enumerable});return n};var xr=(n,e,o)=>(o=n!=null?ur(fr(n)):{},br(e||!n||!n.__esModule?oo(o,"default",{value:n,enumerable:!0}):o,n));var go=vr((ho,fo)=>{"use strict";var mo=(function(){var n=function(E,y){var S=236,b=17,x=E,M=o[y],h=null,f=0,R=null,C=[],I={},Q=function(_,A){f=x*4+17,h=(function($){for(var N=new Array($),T=0;T<$;T+=1){N[T]=new Array($);for(var j=0;j<$;j+=1)N[T][j]=null}return N})(f),G(0,0),G(f-7,0),G(0,f-7),q(),z(),de(_,A),x>=7&&X(_),R==null&&(R=U(x,M,C)),fe(R,A)},G=function(_,A){for(var $=-1;$<=7;$+=1)if(!(_+$<=-1||f<=_+$))for(var N=-1;N<=7;N+=1)A+N<=-1||f<=A+N||(0<=$&&$<=6&&(N==0||N==6)||0<=N&&N<=6&&($==0||$==6)||2<=$&&$<=4&&2<=N&&N<=4?h[_+$][A+N]=!0:h[_+$][A+N]=!1)},V=function(){for(var _=0,A=0,$=0;$<8;$+=1){Q(!0,$);var N=r.getLostPoint(I);($==0||_>N)&&(_=N,A=$)}return A},z=function(){for(var _=8;_<f-8;_+=1)h[_][6]==null&&(h[_][6]=_%2==0);for(var A=8;A<f-8;A+=1)h[6][A]==null&&(h[6][A]=A%2==0)},q=function(){for(var _=r.getPatternPosition(x),A=0;A<_.length;A+=1)for(var $=0;$<_.length;$+=1){var N=_[A],T=_[$];if(h[N][T]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?h[N+j][T+Y]=!0:h[N+j][T+Y]=!1}},X=function(_){for(var A=r.getBCHTypeNumber(x),$=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[Math.floor($/3)][$%3+f-8-3]=N}for(var $=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[$%3+f-8-3][Math.floor($/3)]=N}},de=function(_,A){for(var $=M<<3|A,N=r.getBCHTypeInfo($),T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<6?h[T][8]=j:T<8?h[T+1][8]=j:h[f-15+T][8]=j}for(var T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<8?h[8][f-T-1]=j:T<9?h[8][15-T-1+1]=j:h[8][15-T-1]=j}h[f-8][8]=!_},fe=function(_,A){for(var $=-1,N=f-1,T=7,j=0,Y=r.getMaskFunction(A),J=f-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var pe=0;pe<2;pe+=1)if(h[N][J-pe]==null){var be=!1;j<_.length&&(be=(_[j]>>>T&1)==1);var ee=Y(N,J-pe);ee&&(be=!be),h[N][J-pe]=be,T-=1,T==-1&&(j+=1,T=7)}if(N+=$,N<0||f<=N){N-=$,$=-$;break}}},O=function(_,A){for(var $=0,N=0,T=0,j=new Array(A.length),Y=new Array(A.length),J=0;J<A.length;J+=1){var pe=A[J].dataCount,be=A[J].totalCount-pe;N=Math.max(N,pe),T=Math.max(T,be),j[J]=new Array(pe);for(var ee=0;ee<j[J].length;ee+=1)j[J][ee]=255&_.getBuffer()[ee+$];$+=pe;var Se=r.getErrorCorrectPolynomial(be),_e=s(j[J],Se.getLength()-1),eo=_e.mod(Se);Y[J]=new Array(Se.getLength()-1);for(var ee=0;ee<Y[J].length;ee+=1){var to=ee+eo.getLength()-Y[J].length;Y[J][ee]=to>=0?eo.getAt(to):0}}for(var no=0,ee=0;ee<A.length;ee+=1)no+=A[ee].totalCount;for(var Ln=new Array(no),Ut=0,ee=0;ee<N;ee+=1)for(var J=0;J<A.length;J+=1)ee<j[J].length&&(Ln[Ut]=j[J][ee],Ut+=1);for(var ee=0;ee<T;ee+=1)for(var J=0;J<A.length;J+=1)ee<Y[J].length&&(Ln[Ut]=Y[J][ee],Ut+=1);return Ln},U=function(_,A,$){for(var N=l.getRSBlocks(_,A),T=c(),j=0;j<$.length;j+=1){var Y=$[j];T.put(Y.getMode(),4),T.put(Y.getLength(),r.getLengthInBits(Y.getMode(),_)),Y.write(T)}for(var J=0,j=0;j<N.length;j+=1)J+=N[j].dataCount;if(T.getLengthInBits()>J*8)throw"code length overflow. ("+T.getLengthInBits()+">"+J*8+")";for(T.getLengthInBits()+4<=J*8&&T.put(0,4);T.getLengthInBits()%8!=0;)T.putBit(!1);for(;!(T.getLengthInBits()>=J*8||(T.put(S,8),T.getLengthInBits()>=J*8));)T.put(b,8);return O(T,N)};I.addData=function(_,A){A=A||"Byte";var $=null;switch(A){case"Numeric":$=d(_);break;case"Alphanumeric":$=p(_);break;case"Byte":$=u(_);break;case"Kanji":$=w(_);break;default:throw"mode:"+A}C.push($),R=null},I.isDark=function(_,A){if(_<0||f<=_||A<0||f<=A)throw _+","+A;return h[_][A]},I.getModuleCount=function(){return f},I.make=function(){if(x<1){for(var _=1;_<40;_++){for(var A=l.getRSBlocks(_,M),$=c(),N=0;N<C.length;N++){var T=C[N];$.put(T.getMode(),4),$.put(T.getLength(),r.getLengthInBits(T.getMode(),_)),T.write($)}for(var j=0,N=0;N<A.length;N++)j+=A[N].dataCount;if($.getLengthInBits()<=j*8)break}x=_}Q(!1,V())},I.createTableTag=function(_,A){_=_||2,A=typeof A>"u"?_*4:A;var $="";$+='<table style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: "+A+"px;",$+='">',$+="<tbody>";for(var N=0;N<I.getModuleCount();N+=1){$+="<tr>";for(var T=0;T<I.getModuleCount();T+=1)$+='<td style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: 0px;",$+=" width: "+_+"px;",$+=" height: "+_+"px;",$+=" background-color: ",$+=I.isDark(N,T)?"#000000":"#ffffff",$+=";",$+='"/>';$+="</tr>"}return $+="</tbody>",$+="</table>",$},I.createSvgTag=function(_,A,$,N){var T={};typeof arguments[0]=="object"&&(T=arguments[0],_=T.cellSize,A=T.margin,$=T.alt,N=T.title),_=_||2,A=typeof A>"u"?_*4:A,$=typeof $=="string"?{text:$}:$||{},$.Line truncated
|
var mr=Object.create;var oo=Object.defineProperty;var hr=Object.getOwnPropertyDescriptor;var fr=Object.getOwnPropertyNames;var gr=Object.getPrototypeOf,vr=Object.prototype.hasOwnProperty;var br=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var xr=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fr(e))!vr.call(n,r)&&r!==o&&oo(n,r,{get:()=>e[r],enumerable:!(a=hr(e,r))||a.enumerable});return n};var wr=(n,e,o)=>(o=n!=null?mr(gr(n)):{},xr(e||!n||!n.__esModule?oo(o,"default",{value:n,enumerable:!0}):o,n));var vo=br((fo,go)=>{"use strict";var ho=(function(){var n=function(E,y){var S=236,b=17,x=E,M=o[y],h=null,f=0,R=null,C=[],I={},Q=function(_,A){f=x*4+17,h=(function($){for(var N=new Array($),T=0;T<$;T+=1){N[T]=new Array($);for(var j=0;j<$;j+=1)N[T][j]=null}return N})(f),G(0,0),G(f-7,0),G(0,f-7),q(),z(),ce(_,A),x>=7&&X(_),R==null&&(R=U(x,M,C)),fe(R,A)},G=function(_,A){for(var $=-1;$<=7;$+=1)if(!(_+$<=-1||f<=_+$))for(var N=-1;N<=7;N+=1)A+N<=-1||f<=A+N||(0<=$&&$<=6&&(N==0||N==6)||0<=N&&N<=6&&($==0||$==6)||2<=$&&$<=4&&2<=N&&N<=4?h[_+$][A+N]=!0:h[_+$][A+N]=!1)},Y=function(){for(var _=0,A=0,$=0;$<8;$+=1){Q(!0,$);var N=r.getLostPoint(I);($==0||_>N)&&(_=N,A=$)}return A},z=function(){for(var _=8;_<f-8;_+=1)h[_][6]==null&&(h[_][6]=_%2==0);for(var A=8;A<f-8;A+=1)h[6][A]==null&&(h[6][A]=A%2==0)},q=function(){for(var _=r.getPatternPosition(x),A=0;A<_.length;A+=1)for(var $=0;$<_.length;$+=1){var N=_[A],T=_[$];if(h[N][T]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[N+j][T+Z]=!0:h[N+j][T+Z]=!1}},X=function(_){for(var A=r.getBCHTypeNumber(x),$=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[Math.floor($/3)][$%3+f-8-3]=N}for(var $=0;$<18;$+=1){var N=!_&&(A>>$&1)==1;h[$%3+f-8-3][Math.floor($/3)]=N}},ce=function(_,A){for(var $=M<<3|A,N=r.getBCHTypeInfo($),T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<6?h[T][8]=j:T<8?h[T+1][8]=j:h[f-15+T][8]=j}for(var T=0;T<15;T+=1){var j=!_&&(N>>T&1)==1;T<8?h[8][f-T-1]=j:T<9?h[8][15-T-1+1]=j:h[8][15-T-1]=j}h[f-8][8]=!_},fe=function(_,A){for(var $=-1,N=f-1,T=7,j=0,Z=r.getMaskFunction(A),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var pe=0;pe<2;pe+=1)if(h[N][V-pe]==null){var be=!1;j<_.length&&(be=(_[j]>>>T&1)==1);var ee=Z(N,V-pe);ee&&(be=!be),h[N][V-pe]=be,T-=1,T==-1&&(j+=1,T=7)}if(N+=$,N<0||f<=N){N-=$,$=-$;break}}},O=function(_,A){for(var $=0,N=0,T=0,j=new Array(A.length),Z=new Array(A.length),V=0;V<A.length;V+=1){var pe=A[V].dataCount,be=A[V].totalCount-pe;N=Math.max(N,pe),T=Math.max(T,be),j[V]=new Array(pe);for(var ee=0;ee<j[V].length;ee+=1)j[V][ee]=255&_.getBuffer()[ee+$];$+=pe;var Se=r.getErrorCorrectPolynomial(be),_e=s(j[V],Se.getLength()-1),eo=_e.mod(Se);Z[V]=new Array(Se.getLength()-1);for(var ee=0;ee<Z[V].length;ee+=1){var to=ee+eo.getLength()-Z[V].length;Z[V][ee]=to>=0?eo.getAt(to):0}}for(var no=0,ee=0;ee<A.length;ee+=1)no+=A[ee].totalCount;for(var Ln=new Array(no),Ut=0,ee=0;ee<N;ee+=1)for(var V=0;V<A.length;V+=1)ee<j[V].length&&(Ln[Ut]=j[V][ee],Ut+=1);for(var ee=0;ee<T;ee+=1)for(var V=0;V<A.length;V+=1)ee<Z[V].length&&(Ln[Ut]=Z[V][ee],Ut+=1);return Ln},U=function(_,A,$){for(var N=l.getRSBlocks(_,A),T=c(),j=0;j<$.length;j+=1){var Z=$[j];T.put(Z.getMode(),4),T.put(Z.getLength(),r.getLengthInBits(Z.getMode(),_)),Z.write(T)}for(var V=0,j=0;j<N.length;j+=1)V+=N[j].dataCount;if(T.getLengthInBits()>V*8)throw"code length overflow. ("+T.getLengthInBits()+">"+V*8+")";for(T.getLengthInBits()+4<=V*8&&T.put(0,4);T.getLengthInBits()%8!=0;)T.putBit(!1);for(;!(T.getLengthInBits()>=V*8||(T.put(S,8),T.getLengthInBits()>=V*8));)T.put(b,8);return O(T,N)};I.addData=function(_,A){A=A||"Byte";var $=null;switch(A){case"Numeric":$=d(_);break;case"Alphanumeric":$=p(_);break;case"Byte":$=u(_);break;case"Kanji":$=w(_);break;default:throw"mode:"+A}C.push($),R=null},I.isDark=function(_,A){if(_<0||f<=_||A<0||f<=A)throw _+","+A;return h[_][A]},I.getModuleCount=function(){return f},I.make=function(){if(x<1){for(var _=1;_<40;_++){for(var A=l.getRSBlocks(_,M),$=c(),N=0;N<C.length;N++){var T=C[N];$.put(T.getMode(),4),$.put(T.getLength(),r.getLengthInBits(T.getMode(),_)),T.write($)}for(var j=0,N=0;N<A.length;N++)j+=A[N].dataCount;if($.getLengthInBits()<=j*8)break}x=_}Q(!1,Y())},I.createTableTag=function(_,A){_=_||2,A=typeof A>"u"?_*4:A;var $="";$+='<table style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: "+A+"px;",$+='">',$+="<tbody>";for(var N=0;N<I.getModuleCount();N+=1){$+="<tr>";for(var T=0;T<I.getModuleCount();T+=1)$+='<td style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: 0px;",$+=" width: "+_+"px;",$+=" height: "+_+"px;",$+=" background-color: ",$+=I.isDark(N,T)?"#000000":"#ffffff",$+=";",$+='"/>';$+="</tr>"}return $+="</tbody>",$+="</table>",$},I.createSvgTag=function(_,A,$,N){var T={};typeof arguments[0]=="object"&&(T=arguments[0],_=T.cellSize,A=T.margin,$=T.alt,N=T.title),_=_||2,A=typeof A>"u"?_*4:A,$=typeof $=="string"?{text:$}:$||{},$.Line truncated
|
||||||
`}return $%2&&_>0?_e.substring(0,_e.length-$-1)+Array($+1).join("▀"):_e.substring(0,_e.length-1)};return I.createASCII=function(_,A){if(_=_||1,_<2)return oe(A);_-=1,A=typeof A>"u"?_*2:A;var $=I.getModuleCount()*_+A*2,N=A,T=$-A,j,Y,J,pe,be=Array(_+1).join("██"),ee=Array(_+1).join(" "),Se="",_e="";for(j=0;j<$;j+=1){for(J=Math.floor((j-N)/_),_e="",Y=0;Y<$;Y+=1)pe=1,N<=Y&&Y<T&&N<=j&&j<T&&I.isDark(J,Math.floor((Y-N)/_))&&(pe=0),_e+=pe?be:ee;for(J=0;J<_;J+=1)Se+=_e+`
|
`}return $%2&&_>0?_e.substring(0,_e.length-$-1)+Array($+1).join("▀"):_e.substring(0,_e.length-1)};return I.createASCII=function(_,A){if(_=_||1,_<2)return oe(A);_-=1,A=typeof A>"u"?_*2:A;var $=I.getModuleCount()*_+A*2,N=A,T=$-A,j,Z,V,pe,be=Array(_+1).join("██"),ee=Array(_+1).join(" "),Se="",_e="";for(j=0;j<$;j+=1){for(V=Math.floor((j-N)/_),_e="",Z=0;Z<$;Z+=1)pe=1,N<=Z&&Z<T&&N<=j&&j<T&&I.isDark(V,Math.floor((Z-N)/_))&&(pe=0),_e+=pe?be:ee;for(V=0;V<_;V+=1)Se+=_e+`
|
||||||
`}return Se.substring(0,Se.length-1)},I.renderTo2dContext=function(_,A){A=A||2;for(var $=I.getModuleCount(),N=0;N<$;N++)for(var T=0;T<$;T++)_.fillStyle=I.isDark(N,T)?"black":"white",_.fillRect(N*A,T*A,A,A)},I};n.stringToBytesFuncs={default:function(E){for(var y=[],S=0;S<E.length;S+=1){var b=E.charCodeAt(S);y.push(b&255)}return y}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,y){var S=(function(){for(var x=k(E),M=function(){var z=x.read();if(z==-1)throw"eof";return z},h=0,f={};;){var R=x.read();if(R==-1)break;var C=M(),I=M(),Q=M(),G=String.fromCharCode(R<<8|C),V=I<<8|Q;f[G]=V,h+=1}if(h!=y)throw h+" != "+y;return f})(),b=63;return function(x){for(var M=[],h=0;h<x.length;h+=1){var f=x.charCodeAt(h);if(f<128)M.push(f);else{var R=S[x.charAt(h)];typeof R=="number"?(R&255)==R?M.push(R):(M.push(R>>>8),M.push(R&255)):M.push(b)}}return M}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],y=1335,S=7973,b=21522,x={},M=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return x.getBCHTypeInfo=function(h){for(var f=h<<10;M(f)-M(y)>=0;)f^=y<<M(f)-M(y);return(h<<10|f)^b},x.getBCHTypeNumber=function(h){for(var f=h<<12;M(f)-M(S)>=0;)f^=S<<M(f)-M(S);return h<<12|f},x.getPatternPosition=function(h){return E[h-1]},x.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(f,R){return(f+R)%2==0};case a.PATTERN001:return function(f,R){return f%2==0};case a.PATTERN010:return function(f,R){return R%3==0};case a.PATTERN011:return function(f,R){return(f+R)%3==0};case a.PATTERN100:return function(f,R){return(Math.floor(f/2)+Math.floor(R/3))%2==0};case a.PATTERN101:return function(f,R){return f*R%2+f*R%3==0};case a.PATTERN110:return function(f,R){return(f*R%2+f*R%3)%2==0};case a.PATTERN111:return function(f,R){return(f*R%3+(f+R)%2)%2==0};default:throw"bad maskPattern:"+h}},x.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),R=0;R<h;R+=1)f=f.multiply(s([1,i.gexp(R)],0));return f},x.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},x.getLostPoint=function(h){for(var f=h.getModuleCount(),R=0,C=0;C<f;C+=1)for(var I=0;I<f;I+=1){for(var Q=0,G=h.isDark(C,I),V=-1;V<=1;V+=1)if(!(C+V<0||f<=C+V))for(var z=-1;z<=1;z+=1)I+z<0||f<=I+z||V==0&&z==0||G==h.isDark(C+V,I+z)&&(Q+=1);Q>5&&(R+=3+Q-5)}for(var C=0;C<f-1;C+=1)for(var I=0;I<f-1;I+=1){var q=0;h.isDark(C,I)&&(q+=1),h.isDark(C+1,I)&&(q+=1),h.isDark(C,I+1)&&(q+=1),h.isDark(C+1,I+1)&&(q+=1),(q==0||q==4)&&(R+=3)}for(var C=0;C<f;C+=1)for(var I=0;I<f-6;I+=1)h.isDark(C,I)&&!h.isDark(C,I+1)&&h.isDark(C,I+2)&&h.isDark(C,I+3)&&h.isDark(C,I+4)&&!h.isDark(C,I+5)&&h.isDark(C,I+6)&&(R+=40);for(var I=0;I<f;I+=1)for(var C=0;C<f-6;C+=1)h.isDark(C,I)&&!h.isDark(C+1,I)&&h.isDark(C+2,I)&&h.isDark(C+3,I)&&h.isDark(C+4,I)&&!h.isDark(C+5,I)&&h.isDark(C+6,I)&&(R+=40);for(var X=0,I=0;I<f;I+=1)for(var C=0;C<f;C+=1)h.isDark(C,I)&&(X+=1);var de=Math.abs(100*X/f/f-50)/5;return R+=de*10,R},x})(),i=(function(){for(var E=new Array(256),y=new Array(256),S=0;S<8;S+=1)E[S]=1<<S;for(var S=8;S<256;S+=1)E[S]=E[S-4]^E[S-5]^E[S-6]^E[S-8];for(var S=0;S<255;S+=1)y[E[S]]=S;var b={};return b.glog=function(x){if(x<1)throw"glog("+x+")";return y[x]},b.gexp=function(x){for(;x<0;)x+=255;for(;x>=256;)x-=255;return E[x]},b})();function s(E,y){if(typeof E.length>"u")throw E.length+"/"+y;var S=(function(){for(var x=0;x<E.length&&E[x]==0;)x+=1;for(var M=new Array(E.length-x+y),h=0;h<E.length-x;h+=1)M[h]=E[h+x];return M})(),b={};return b.getAt=function(x){return S[x]},b.getLength=function(){return S.length},b.multiply=function(x){for(var M=new Array(b.getLength()+x.getLength()-1),h=0;h<b.getLength();h+=1)for(var f=0;f<x.getLength();f+=1)M[h+f]^=i.gexp(i.glog(b.getAt(h))+i.glog(x.getAt(f)));return s(M,0)},b.mod=function(x){if(b.getLength()
Line truncated
|
`}return Se.substring(0,Se.length-1)},I.renderTo2dContext=function(_,A){A=A||2;for(var $=I.getModuleCount(),N=0;N<$;N++)for(var T=0;T<$;T++)_.fillStyle=I.isDark(N,T)?"black":"white",_.fillRect(N*A,T*A,A,A)},I};n.stringToBytesFuncs={default:function(E){for(var y=[],S=0;S<E.length;S+=1){var b=E.charCodeAt(S);y.push(b&255)}return y}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,y){var S=(function(){for(var x=k(E),M=function(){var z=x.read();if(z==-1)throw"eof";return z},h=0,f={};;){var R=x.read();if(R==-1)break;var C=M(),I=M(),Q=M(),G=String.fromCharCode(R<<8|C),Y=I<<8|Q;f[G]=Y,h+=1}if(h!=y)throw h+" != "+y;return f})(),b=63;return function(x){for(var M=[],h=0;h<x.length;h+=1){var f=x.charCodeAt(h);if(f<128)M.push(f);else{var R=S[x.charAt(h)];typeof R=="number"?(R&255)==R?M.push(R):(M.push(R>>>8),M.push(R&255)):M.push(b)}}return M}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],y=1335,S=7973,b=21522,x={},M=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return x.getBCHTypeInfo=function(h){for(var f=h<<10;M(f)-M(y)>=0;)f^=y<<M(f)-M(y);return(h<<10|f)^b},x.getBCHTypeNumber=function(h){for(var f=h<<12;M(f)-M(S)>=0;)f^=S<<M(f)-M(S);return h<<12|f},x.getPatternPosition=function(h){return E[h-1]},x.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(f,R){return(f+R)%2==0};case a.PATTERN001:return function(f,R){return f%2==0};case a.PATTERN010:return function(f,R){return R%3==0};case a.PATTERN011:return function(f,R){return(f+R)%3==0};case a.PATTERN100:return function(f,R){return(Math.floor(f/2)+Math.floor(R/3))%2==0};case a.PATTERN101:return function(f,R){return f*R%2+f*R%3==0};case a.PATTERN110:return function(f,R){return(f*R%2+f*R%3)%2==0};case a.PATTERN111:return function(f,R){return(f*R%3+(f+R)%2)%2==0};default:throw"bad maskPattern:"+h}},x.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),R=0;R<h;R+=1)f=f.multiply(s([1,i.gexp(R)],0));return f},x.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},x.getLostPoint=function(h){for(var f=h.getModuleCount(),R=0,C=0;C<f;C+=1)for(var I=0;I<f;I+=1){for(var Q=0,G=h.isDark(C,I),Y=-1;Y<=1;Y+=1)if(!(C+Y<0||f<=C+Y))for(var z=-1;z<=1;z+=1)I+z<0||f<=I+z||Y==0&&z==0||G==h.isDark(C+Y,I+z)&&(Q+=1);Q>5&&(R+=3+Q-5)}for(var C=0;C<f-1;C+=1)for(var I=0;I<f-1;I+=1){var q=0;h.isDark(C,I)&&(q+=1),h.isDark(C+1,I)&&(q+=1),h.isDark(C,I+1)&&(q+=1),h.isDark(C+1,I+1)&&(q+=1),(q==0||q==4)&&(R+=3)}for(var C=0;C<f;C+=1)for(var I=0;I<f-6;I+=1)h.isDark(C,I)&&!h.isDark(C,I+1)&&h.isDark(C,I+2)&&h.isDark(C,I+3)&&h.isDark(C,I+4)&&!h.isDark(C,I+5)&&h.isDark(C,I+6)&&(R+=40);for(var I=0;I<f;I+=1)for(var C=0;C<f-6;C+=1)h.isDark(C,I)&&!h.isDark(C+1,I)&&h.isDark(C+2,I)&&h.isDark(C+3,I)&&h.isDark(C+4,I)&&!h.isDark(C+5,I)&&h.isDark(C+6,I)&&(R+=40);for(var X=0,I=0;I<f;I+=1)for(var C=0;C<f;C+=1)h.isDark(C,I)&&(X+=1);var ce=Math.abs(100*X/f/f-50)/5;return R+=ce*10,R},x})(),i=(function(){for(var E=new Array(256),y=new Array(256),S=0;S<8;S+=1)E[S]=1<<S;for(var S=8;S<256;S+=1)E[S]=E[S-4]^E[S-5]^E[S-6]^E[S-8];for(var S=0;S<255;S+=1)y[E[S]]=S;var b={};return b.glog=function(x){if(x<1)throw"glog("+x+")";return y[x]},b.gexp=function(x){for(;x<0;)x+=255;for(;x>=256;)x-=255;return E[x]},b})();function s(E,y){if(typeof E.length>"u")throw E.length+"/"+y;var S=(function(){for(var x=0;x<E.length&&E[x]==0;)x+=1;for(var M=new Array(E.length-x+y),h=0;h<E.length-x;h+=1)M[h]=E[h+x];return M})(),b={};return b.getAt=function(x){return S[x]},b.getLength=function(){return S.length},b.multiply=function(x){for(var M=new Array(b.getLength()+x.getLength()-1),h=0;h<b.getLength();h+=1)for(var f=0;f<x.getLength();f+=1)M[h+f]^=i.gexp(i.glog(b.getAt(h))+i.glog(x.getAt(f)));return s(M,0)},b.mod=function(x){if(b.getLength()
Line truncated
|
||||||
`)}function Pr(n){let e=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ue(n,e,o,a="",r=[]){let i=Pr(n),s=[...e.map(p=>({ts:p.ts,category:Tt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Pe(p)??""})),...r.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
|
`)}function Dr(n){let e=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ue(n,e,o,a="",r=[]){let i=Dr(n),s=[...e.map(p=>({ts:p.ts,category:Tt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Pe(p)??""})),...r.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
|
||||||
${p.detail}`:""}`,where:Ct[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){Ee(c,JSON.stringify(s,null,2),"application/json");return}Ee(c,yo(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Dr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],ko=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Ke(n,e,o,a,r,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...gt.map(c=>t("option",{value:c,selected:c===r?"selected":null},rt[c])),i?t("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Dr.map(([c,d])=>t("option",{value:c},d)));re(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[le()," ",D("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await P.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){Z(ve(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await P.serviceLogClear(l.value)).removed}catch(d){ce(),Z(`${s.value==="system"?"":`Activity: ${ko(c).toLowerCase()}. `}The service log was not cleared: ${ve(d)}`,"error",1e4),a();return}ce(),Z(ko(c),"success",3e3),a()},"negative")])}function vt(n,e,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";re(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},r)],[le()," ",D("Reset",async()=>{await W(()=>P.usageClear(n,e),"Traffic history reset")&&(ce(),a())},"negative")])}function ge(n,e,o){let a=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!a.classList.contains("on");Pn(a,r),o?.(r)}},t("i"));return a}function Pn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Me=n=>n.classList.contains("on");function xe(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let a=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function We(n,e,o,a={}){return t("button",{type:"button",...a,class:`dl-chipbtn${e?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Yt(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ar={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:""},zr={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 Hr(n){let e={};for(let[o,a]of Object.entries(zr))n[o]!=null&&n[o]!==""&&(e[a]=String(n[o]));return e}function Nr(n,e){let o=n.amnezia,a=o.obfuscation??{},r=c=>a[c]!=null&&a[c]!==""?String(a[c]):Ar[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Hr(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:Ct[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){Ee(c,JSON.stringify(s,null,2),"application/json");return}Ee(c,ko(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ar=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],$o=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Ke(n,e,o,a,r,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...gt.map(c=>t("option",{value:c,selected:c===r?"selected":null},rt[c])),i?t("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ar.map(([c,d])=>t("option",{value:c},d)));ae(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[le()," ",D("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await P.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){K(ve(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await P.serviceLogClear(l.value)).removed}catch(d){de(),K(`${s.value==="system"?"":`Activity: ${$o(c).toLowerCase()}. `}The service log was not cleared: ${ve(d)}`,"error",1e4),a();return}de(),K($o(c),"success",3e3),a()},"negative")])}function vt(n,e,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},r)],[le()," ",D("Reset",async()=>{await W(()=>P.usageClear(n,e),"Traffic history reset")&&(de(),a())},"negative")])}function ge(n,e,o){let a=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!a.classList.contains("on");Pn(a,r),o?.(r)}},t("i"));return a}function Pn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Me=n=>n.classList.contains("on");function xe(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let a=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function We(n,e,o,a={}){return t("button",{type:"button",...a,class:`dl-chipbtn${e?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Yt(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var zr={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:""},Hr={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 Nr(n){let e={};for(let[o,a]of Object.entries(Hr))n[o]!=null&&n[o]!==""&&(e[a]=String(n[o]));return e}function Rr(n,e){let o=n.amnezia,a=o.obfuscation??{},r=c=>a[c]!=null&&a[c]!==""?String(a[c]):zr[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Nr(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
|
||||||
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Rr(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ir(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),a=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Dn(n,e,o=!0){let a=new TextEncoder().encode(JSON.stringify(Nr(n,e))),r=o?await Ir(a):null;return`vpn://${Rr(r??a)}`}var Eo=[{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"}],Pt=n=>Eo.find(e=>e.id===n),Br={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)."},Or={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function $o(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function Zt(n,e,o,a,r=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,Eo.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===a?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[$o(l.stealth,"Stealth"),$o(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[v("phone"),t("span",{},l.apps)]:[v("alert"),t("span",{},(r?Br:Or)[l.needs])])])}));return s(),i}function Lo(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Mo=[["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 jr(n){let e=d=>n[d]!=null&&n[d]!=="",o=Mo.filter(([d])=>e(d));if(!o.length)return null;let a=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),r=(d,p,u,w)=>{let g=Mo.filter(([m])=>w.includes(m)&&e(m));return g.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},g.map(([m,k])=>a(m,k)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
|
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Ir(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Br(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),a=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function Dn(n,e,o=!0){let a=new TextEncoder().encode(JSON.stringify(Rr(n,e))),r=o?await Br(a):null;return`vpn://${Ir(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"}],Pt=n=>Lo.find(e=>e.id===n),Or={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)."},jr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function Eo(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function Zt(n,e,o,a,r=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,Lo.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===a?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[Eo(l.stealth,"Stealth"),Eo(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[v("phone"),t("span",{},l.apps)]:[v("alert"),t("span",{},(r?Or:jr)[l.needs])])])}));return s(),i}function Mo(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var So=[["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 Ur(n){let e=d=>n[d]!=null&&n[d]!=="",o=So.filter(([d])=>e(d));if(!o.length)return null;let a=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),r=(d,p,u,w)=>{let g=So.filter(([m])=>w.includes(m)&&e(m));return g.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},g.map(([m,k])=>a(m,k)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
|
||||||
`),c=t("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),c])}function So(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",a&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Ur(n){let e=!1,o=t("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
|
`),c=t("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),c])}function _o(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",a&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Wr(n){let e=!1,o=t("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
|
||||||
`).flatMap((s,l)=>l?[`
|
`).flatMap((s,l)=>l?[`
|
||||||
`,So(s,e)]:[So(s,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([v("download")," Download"],()=>Ee(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),o])])}async function Wr(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Dn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>t("div",{class:"dl-qr-pane"},[qe(ft(n.conf),"dl-qr"),t("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),D("Copy",()=>ue(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Ur(n)},r=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(r,a[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,r])}async function Gr(n,e,o,a){let r=Pt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await ae(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await W(()=>P.serverObfuscation(e.id,o),a?"New values applied":`${r.title} applied`)&&(Z("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Fr(n,e){let o=n.st,a=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=`${e.mtus.computer} for computers and routers, ${e.mtus.phone} for phones and tablets`,s=e.mtu?`Now ${i}. Empty = automatic.`:`Automatic by device type and disguise: now ${i}. Lower it if some sites hang.`,l=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),c=Pt(e.preset)?e.preset:void 0,d=c??"standard",p=D("",()=>Gr(n,e,d,d===c),"neutral"),u=()=>dom.content(p,d===c?[v("reset")," Generate new values"]:[`Switch to ${Pt(d).title}`]);u();let w=o.awg_state?.tools!==!1;return _t("",[Lo("AmneziaWG",e.ifname),he("globe","Listening","Where devices reach this core from the internet",[ne("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ne("MTU",r,s),ne("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Zt(o.awg,d,g=>{d=g,u()},c,w),w&&!o.awg.v3?ht("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",jr(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),p])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ne("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ne("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ne("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),D([v("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:l.value},"AmneziaWG saved"),"positive")])}function qr(n){let e=Pt(n.preset),o=n.obf??{},a=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(c=>t("i",{class:c<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2"
Line truncated
|
`,_o(s,e)]:[_o(s,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([v("download")," Download"],()=>Ee(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),o])])}async function Gr(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await Dn(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>t("div",{class:"dl-qr-pane"},[qe(ft(n.conf),"dl-qr"),t("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),D("Copy",()=>ue(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Wr(n)},r=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(r,a[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,r])}async function Fr(n,e,o,a){let r=Pt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await re(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await W(()=>P.serverObfuscation(e.id,o),a?"New values applied":`${r.title} applied`)&&(K("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function qr(n,e){let o=n.st,a=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=`${e.mtus.computer} for computers and routers, ${e.mtus.phone} for phones and tablets`,s=e.mtu?`Now ${i}. Empty = automatic.`:`Automatic by device type and disguise: now ${i}. Lower it if some sites hang.`,l=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),c=Pt(e.preset)?e.preset:void 0,d=c??"standard",p=D("",()=>Fr(n,e,d,d===c),"neutral"),u=()=>dom.content(p,d===c?[v("reset")," Generate new values"]:[`Switch to ${Pt(d).title}`]);u();let w=o.awg_state?.tools!==!1;return _t("",[Mo("AmneziaWG",e.ifname),he("globe","Listening","Where devices reach this core from the internet",[ne("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ne("MTU",r,s),ne("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Zt(o.awg,d,g=>{d=g,u()},c,w),w&&!o.awg.v3?ht("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Ur(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),p])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ne("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ne("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ne("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),D([v("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:l.value},"AmneziaWG saved"),"positive")])}function Kr(n){let e=Pt(n.preset),o=n.obf??{},a=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(c=>t("i",{class:c<s?"on":""}))),r=[];+o.jc&&r.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);let i=["s1","s2"
Line truncated
|
||||||
`),"Log copied"))]),p,u]),[w],"wide"),m([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let H=o??null,B=o?.id,E,y=0,S=h=>{B!==h.id&&(B=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await P.updatesStatus().catch(()=>null);E=h?.job?.id,y=h?.now??0;let f=await P.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==E&&(H=f.job,S(f.job))}catch(h){return g=[ve(h)],p.textContent=g[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},ve(h))])),m([k(!0)]),Z(ve(h),"error"),null}let b=null,x=0;for(;;){if(await oa(1e3),b=await P.updatesStatus().catch(()=>null),!b){if(++x>60)break;continue}x=0;let h=b.job;if(!h||!na(h,B,E,y)){if(Date.now()-i>15e3)break;continue}if(S(h),H=h,h.log.length){g=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=g.join(`
|
`),"Log copied"))]),p,u]),[w],"wide"),m([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let H=o??null,B=o?.id,E,y=0,S=h=>{B!==h.id&&(B=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await P.updatesStatus().catch(()=>null);E=h?.job?.id,y=h?.now??0;let f=await P.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==E&&(H=f.job,S(f.job))}catch(h){return g=[ve(h)],p.textContent=g[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},ve(h))])),m([k(!0)]),K(ve(h),"error"),null}let b=null,x=0;for(;;){if(await aa(1e3),b=await P.updatesStatus().catch(()=>null),!b){if(++x>60)break;continue}x=0;let h=b.job;if(!h||!oa(h,B,E,y)){if(Date.now()-i>15e3)break;continue}if(S(h),H=h,h.log.length){g=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=g.join(`
|
||||||
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ea(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=Xo((h.finished??b.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!H||H.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),m([k()]),e.onDone?.(b),H;if(H.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},H.error??"Operation failed"),r?"":". Nothing else was changed."])])),m([D("Copy log",()=>ue(g.join(`
|
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=ta(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=ea((h.finished??b.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!H||H.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),m([k()]),e.onDone?.(b),H;if(H.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},H.error??"Operation failed"),r?"":". Nothing else was changed."])])),m([D("Copy log",()=>ue(g.join(`
|
||||||
`),"Log copied")),k(!0)]),Z(`${dn[a]??"Update"}: ${H.error??"failed"}`,"error"),e.onDone?.(b),H;if(c.className="dl-pill ok",c.textContent="Finished",r&&b){let h=ta(b,a);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[v(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),Z(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(b),h.update&&e.onUpdate){let f=b;m([k(),D(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else m([k()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return H}if(a==="app"&&H.to){let h=H.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let R=()=>{ui.menu?.flushCache(),location.reload()};m([k(),D("Reload now",R,"positive")]),Z(`Dawnline updated to ${h}`,"success",6e3);for(let C=1;C<=30;C++)if(f.textContent=`Waiting for the router to restart its services (${C} of 30)…`,await oa(1500),(await P.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(R,800),H;return f.textContent="Services restarted. Reload the page to use the new version.",H}let M=a==="pkgs"?`Updated ${[...H.result?.pkgs?.updated??[],...H.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${H.to?` ${H.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},M)])),m([k()]),Z(M,"success"),e.onDone?.(b),H}var wi={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function aa(n,e,o,a){return!await ae(`Install ${e}?`,o,"Install")||(await It(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function pn(n){return aa("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 Bt(n,e,o){return n==="awg"?pn(o):e.length?aa(`pkgs:${e.join(",")}`,wi[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function ra(n,e){if(n==="awg")return pn(e);let o=await W(()=>P.updatesStatus());return o?Bt(n,o.needs?.[n]??[],e):!1}var yi=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],ki={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function ia(n,e,o){let a=n.id,r=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,g=Yo(r,a,o),m=new Set,k="",H=()=>JSON.stringify([p,l,l?"":c,d,[...m].sort()]),B=()=>s.detected.lan||s.saved.lan||"",E=()=>(l?s.detected.wan||s.saved.wan:c)||"",y=()=>new Map(s.devices.map(z=>[z.name,z])),S=()=>{let z=y();return[...d&&B()?[B()]:[],...[...m].filter(X=>X!==B())].filter(X=>X!==E()).map(X=>z.get(X)??{name:X,nets:[],missing:!0})},b=(z,q)=>{s=z,q&&(l=z.config.auto_wan,c=z.config.wan_device||z.detected.wan||z.saved.wan||"",d=z.config.auto_lan,p=z.config.lan_like,u=z.config.mesh??(z.config.device_mesh?"all":"off"),m=new Set(z.config.lan_devices),k=H()),G()},x=async z=>{let q=await P.interfaces(a).catch(X=>(Z(X.message,"error"),null));q&&b(q,z)};function M(z){let q=d&&z.name===B(),X=!!z.own||!!z.master||z.name===E()||q;return q||m.has(z.name)||!X&&(z.nets.length>0||!!z.missing)}function h(z){let q=d&&z.name===B(),X=z.name===E(),de=!q&&m.has(z.name),O=!(!!z.own||!!z.master||X||q)&&(z.nets.length>0||de||!!z.missing),U=(de||q)&&!z.zone&&!z.missing,F=z.missing?"Not present right now":z.own?"This server":z.master?`Port of ${z.master}`:X?`Internet${z.zone?` · zone ${z.zone}`:""}`:z.nets.length?z.nets.join(", "):"No IPv4 network",oe=t("button",{type:"button",class:`dl-if${de?" sel":""}${q?" auto":""}${!O&&!de&&!q?" off":""}${U?" warn":""}`,"aria-pressed":de||q?"true":"false","aria-disabled":O?null:"true",click:()=>{O&&(m.has(z.name)?m.delete(z.name):m.add(z.name),G())}},[t("span",{class:"dl-if-ic"},v(ki[z.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},z.name),t("span",{class:"dl-if-sub"},F)]),q?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return me(oe,()=>[t("div",{class:"dl-tip-title"},z.name),t("div",{class:"dl-muted"},[z.logical?`Interface ${z.logical}`:"No netifd interface",z.zone?` · zone ${z.zone}`:" · no firewall zone"]),z.members.length?t("div",{class:"dl-muted"},`Ports: ${z.members.join(", ")}`):"",z.nets.length?t("div",{class:"dl-mono"},z.nets.join(", ")):"",U?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",z.master?t("div",{class:"dl-muted"},`Choose ${z.master} to include it.`):""]),oe}function f(){let z=s.like_home;return!p||!s.config.lan_like
Line truncated
|
`),"Log copied")),k(!0)]),K(`${dn[a]??"Update"}: ${H.error??"failed"}`,"error"),e.onDone?.(b),H;if(c.className="dl-pill ok",c.textContent="Finished",r&&b){let h=na(b,a);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[v(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),K(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(b),h.update&&e.onUpdate){let f=b;m([k(),D(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else m([k()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&de(),1200);return H}if(a==="app"&&H.to){let h=H.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let R=()=>{ui.menu?.flushCache(),location.reload()};m([k(),D("Reload now",R,"positive")]),K(`Dawnline updated to ${h}`,"success",6e3);for(let C=1;C<=30;C++)if(f.textContent=`Waiting for the router to restart its services (${C} of 30)…`,await aa(1500),(await P.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(R,800),H;return f.textContent="Services restarted. Reload the page to use the new version.",H}let M=a==="pkgs"?`Updated ${[...H.result?.pkgs?.updated??[],...H.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${H.to?` ${H.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},M)])),m([k()]),K(M,"success"),e.onDone?.(b),H}var yi={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function ra(n,e,o,a){return!await re(`Install ${e}?`,o,"Install")||(await It(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function pn(n){return ra("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 Bt(n,e,o){return n==="awg"?pn(o):e.length?ra(`pkgs:${e.join(",")}`,yi[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function ia(n,e){if(n==="awg")return pn(e);let o=await W(()=>P.updatesStatus());return o?Bt(n,o.needs?.[n]??[],e):!1}var ki=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],$i={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function sa(n,e,o){let a=n.id,r=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,g=Zo(r,a,o),m=new Set,k="",H=()=>JSON.stringify([p,l,l?"":c,d,[...m].sort()]),B=()=>s.detected.lan||s.saved.lan||"",E=()=>(l?s.detected.wan||s.saved.wan:c)||"",y=()=>new Map(s.devices.map(z=>[z.name,z])),S=()=>{let z=y();return[...d&&B()?[B()]:[],...[...m].filter(X=>X!==B())].filter(X=>X!==E()).map(X=>z.get(X)??{name:X,nets:[],missing:!0})},b=(z,q)=>{s=z,q&&(l=z.config.auto_wan,c=z.config.wan_device||z.detected.wan||z.saved.wan||"",d=z.config.auto_lan,p=z.config.lan_like,u=z.config.mesh??(z.config.device_mesh?"all":"off"),m=new Set(z.config.lan_devices),k=H()),G()},x=async z=>{let q=await P.interfaces(a).catch(X=>(K(X.message,"error"),null));q&&b(q,z)};function M(z){let q=d&&z.name===B(),X=!!z.own||!!z.master||z.name===E()||q;return q||m.has(z.name)||!X&&(z.nets.length>0||!!z.missing)}function h(z){let q=d&&z.name===B(),X=z.name===E(),ce=!q&&m.has(z.name),O=!(!!z.own||!!z.master||X||q)&&(z.nets.length>0||ce||!!z.missing),U=(ce||q)&&!z.zone&&!z.missing,F=z.missing?"Not present right now":z.own?"This server":z.master?`Port of ${z.master}`:X?`Internet${z.zone?` · zone ${z.zone}`:""}`:z.nets.length?z.nets.join(", "):"No IPv4 network",oe=t("button",{type:"button",class:`dl-if${ce?" sel":""}${q?" auto":""}${!O&&!ce&&!q?" off":""}${U?" warn":""}`,"aria-pressed":ce||q?"true":"false","aria-disabled":O?null:"true",click:()=>{O&&(m.has(z.name)?m.delete(z.name):m.add(z.name),G())}},[t("span",{class:"dl-if-ic"},v($i[z.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},z.name),t("span",{class:"dl-if-sub"},F)]),q?t("span",{class:"dl-if-badge ok"},"Auto"):ce?t("span",{class:"dl-if-check"},v("check")):""]);return me(oe,()=>[t("div",{class:"dl-tip-title"},z.name),t("div",{class:"dl-muted"},[z.logical?`Interface ${z.logical}`:"No netifd interface",z.zone?` · zone ${z.zone}`:" · no firewall zone"]),z.members.length?t("div",{class:"dl-muted"},`Ports: ${z.members.join(", ")}`):"",z.nets.length?t("div",{class:"dl-mono"},z.nets.join(", ")):"",U?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",z.master?t("div",{class:"dl-muted"},`Choose ${z.master} to include it.`):""]),oe}function f(){let z=s.like_home;return!p||!s.config.lan_like
Line truncated
|
||||||
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(`
|
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(`
|
||||||
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(r.length&&s(),a||(a=t("ul",{}),e.push(a)),a.appendChild(t("li",{},o(p[1])))):c.trim()?(a&&(a=null),r.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
|
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(r.length&&s(),a||(a=t("ul",{}),e.push(a)),a.appendChild(t("li",{},o(p[1])))):c.trim()?(a&&(a=null),r.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
|
||||||
`))),s(),e}function Ea(n){let e=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
|
`))),s(),e}function La(n){let e=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
|
||||||
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||e.push(a)}return e.join(`
|
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||e.push(a)}return e.join(`
|
||||||
`).replace(/\n{3,}/g,`
|
`).replace(/\n{3,}/g,`
|
||||||
|
|
||||||
`).trim()}async function jt(n,e,o,a){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";re(o,[i,r],[D([v("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",le("Close")],"wide");try{let l=await P.updatesNotes(n,e,a??"");s=Ea(l.body||"");let c=ka(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ne(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(r,s.trim()?$a(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,t("p",{class:"dl-muted"},ve(l)))}}var La={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Yn=n=>n?Ne(n):"";function Ri(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Sa(n,e){let o=n.st,a=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>jt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ii(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,p=(w,g)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},g)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await ae(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Yn(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Yn(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Bi(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[a.auto?ye("ok","On"):ye("","Off"),t("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${La[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${La[a.interval]}`:"checks off")]),p("Last check",o.check?[ie(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${pt(d-o.now)}`):""]:["Never"]),p("Rollback",r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function Ii(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
`).trim()}async function jt(n,e,o,a){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([v("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",le("Close")],"wide");try{let l=await P.updatesNotes(n,e,a??"");s=La(l.body||"");let c=$a(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ne(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(r,s.trim()?Ea(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,t("p",{class:"dl-muted"},ve(l)))}}var Ma={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Yn=n=>n?Ne(n):"";function Ii(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 o=n.st,a=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>jt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Bi(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,p=(w,g)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},g)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await re(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Yn(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Yn(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Oi(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[a.auto?ye("ok","On"):ye("","Off"),t("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${Ma[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${Ma[a.interval]}`:"checks off")]),p("Last check",o.check?[ie(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${pt(d-o.now)}`):""]:["Never"]),p("Rollback",r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function Bi(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Ri(a(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Bi(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&bn(n,e)}),n.versOpen&&bn(n,e),o}async function bn(n,e){let o=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return Z("Enter a release tag like 0.3.1","warning");Ma(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),a(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),bn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${ve(p)}`),D("Try again",()=>bn(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[r,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[r,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Yn(p.published)),p.prerelease?ye("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},$e("file","What’s new",()=>jt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?ye("ok","Installed"):D("Install",()=>Ma(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function Ma(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await ae(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function _a(n,e){let o=n.st,a=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),s=e?.current??null,l=s?r[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),a&&u.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await ae(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>jt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,R)=>h!==null||f>0&&R[f-1]!==null),g=o.tunnels??[],m=g.length?`Switching restarts ${g.length===1?"the tunnel":`${g.length} tunnels`} for a few seconds: ${g.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",k=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0],H=g.length?`Switching restarts ${k} for a few seconds.`:"Switching takes a few seconds.",B=async h=>{let f=r[h];await ae(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${m}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},E=h=>{let f=r[h],R=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},R?ye("ok","Active"):f.version?D(p?"Switch":"Install",()=>B(h),p?"neutral":"positive",{disabled:n.busy}):ye("","No build"))])},y=i.map(h=>r[h]?.newer?`${r[h].label} moves to ${r[h].newer.gen} with OpenWrt ${r[h].newer.tag.replace(
Line truncated
|
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Ii(a(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Oi(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&bn(n,e)}),n.versOpen&&bn(n,e),o}async function bn(n,e){let o=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return K("Enter a release tag like 0.3.1","warning");Sa(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),a(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),bn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${ve(p)}`),D("Try again",()=>bn(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[r,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[r,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Yn(p.published)),p.prerelease?ye("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},$e("file","What’s new",()=>jt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?ye("ok","Installed"):D("Install",()=>Sa(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function Sa(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await re(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function Ta(n,e){let o=n.st,a=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),s=e?.current??null,l=s?r[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),a&&u.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await re(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>jt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,R)=>h!==null||f>0&&R[f-1]!==null),g=o.tunnels??[],m=g.length?`Switching restarts ${g.length===1?"the tunnel":`${g.length} tunnels`} for a few seconds: ${g.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",k=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0],H=g.length?`Switching restarts ${k} for a few seconds.`:"Switching takes a few seconds.",B=async h=>{let f=r[h];await re(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${m}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},E=h=>{let f=r[h],R=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},R?ye("ok","Active"):f.version?D(p?"Switch":"Install",()=>B(h),p?"neutral":"positive",{disabled:n.busy}):ye("","No build"))])},y=i.map(h=>r[h]?.newer?`${r[h].label} moves to ${r[h].newer.gen} with OpenWrt ${r[h].newer.tag.replace(
Line truncated
|
||||||
`)}r.push(p),l+=d-1}let s=D([v("more")],()=>we(s,[{label:"Export CSV",icon:v("download"),run:()=>Ue(o,a,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Ue(o,a,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>Ke(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),t("span",{class:"dl-spacer"}),s]),r.length?r:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var wn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,a,r]=await Promise.all([P.status(30),e?P.events(5e3).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let a=t("div",{},[t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:wt(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:wt(o.server)},"People"),t("span",{},"/"),t("span",{},o.name)]),this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>Be(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>it(this.p,this.deviceOpts()),50),this.poller=Ve({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=wt(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let a=await W(()=>P.personUpdate(this.p.id,e),o);if(!a)return!1;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);return(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint(),!0}get today(){return Re(this.series.length?this.series:this.st.series)}get core(){return bt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(e=!1){Le(this.parts.head,Ra(this),e),Le(this.parts.traffic,Ia(this),e),Le(this.parts.devices,Ba(this),e),Le(this.parts.limits,qa(this),e),this.paintPlaces(e),Le(this.parts.activity,Ja(this),e)}paintPlaces(e=!1){let o=Ka(this);o&&Le(this.parts.places,o,e&&!this.mapOpen)}};var Vi={ok:"check",warn:"alert",error:"x",skip:"pause"},yn=class{constructor(e,o,a,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(e){let o=e?await fn(e):await P.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,a=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ht("error",`${o} problem${o>1?"s":""} need attention.`):a?ht("warn",`${a} warning${a>1?"s":""}.`):ht("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs
Line truncated
|
`)}r.push(p),l+=d-1}let s=D([v("more")],()=>we(s,[{label:"Export CSV",icon:v("download"),run:()=>Ue(o,a,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Ue(o,a,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>Ke(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),t("span",{class:"dl-spacer"}),s]),r.length?r:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var wn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,a,r]=await Promise.all([P.status(30),e?P.events(5e3).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let a=t("div",{},[t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:wt(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:wt(o.server)},"People"),t("span",{},"/"),t("span",{},o.name)]),this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>Be(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>it(this.p,this.deviceOpts()),50),this.poller=Ve({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=wt(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let a=await W(()=>P.personUpdate(this.p.id,e),o);if(!a)return!1;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);return(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint(),!0}get today(){return Re(this.series.length?this.series:this.st.series)}get core(){return bt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(e=!1){Le(this.parts.head,Ia(this),e),Le(this.parts.traffic,Ba(this),e),Le(this.parts.devices,Oa(this),e),Le(this.parts.limits,Ka(this),e),this.paintPlaces(e),Le(this.parts.activity,Va(this),e)}paintPlaces(e=!1){let o=Ja(this);o&&Le(this.parts.places,o,e&&!this.mapOpen)}};var Yi={ok:"check",warn:"alert",error:"x",skip:"pause"},yn=class{constructor(e,o,a,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(e){let o=e?await fn(e):await P.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,a=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ht("error",`${o} problem${o>1?"s":""} need attention.`):a?ht("warn",`${a} warning${a>1?"s":""}.`):ht("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog.repairs
Line truncated
|
||||||
`);function cr(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=ms,n}function lt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async a=>{let r=await e.render(a),i=document.createElement("div");return i.className="dl-root",i.append(cr(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Mg=lt(Ot),Sg=lt(st),_g=lt(Ot),Tg=lt(vn),Cg=lt(wn),Pg=lt(En),Dg=lt(xn);function pr(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 Ag=pr(""),zg=pr("log");return baseclass.extend({ activity: zg, diagnostics: Pg, health: Ag, overview: Mg, people: Sg, person: Cg, server: _g, settings: Tg, updates: Dg });
|
`);function pr(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=hs,n}function lt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async a=>{let r=await e.render(a),i=document.createElement("div");return i.className="dl-root",i.append(pr(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var _g=lt(Ot),Tg=lt(st),Cg=lt(Ot),Pg=lt(vn),Dg=lt(wn),Ag=lt(En),zg=lt(xn);function ur(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 Hg=ur(""),Ng=ur("log");return baseclass.extend({ activity: Ng, diagnostics: Ag, health: Hg, overview: _g, people: Tg, person: Dg, server: Cg, settings: Pg, updates: zg });
|
||||||
@@ -21,9 +21,11 @@ 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"
|
||||||
|
|
||||||
|
# Four portal processes at once (each loads the whole model: a burst of 16
|
||||||
|
# could empty a 128 MB router); the rest of 64 connections wait their turn.
|
||||||
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 4 -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
|
||||||
|
|||||||
@@ -57,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
|
||||||
@@ -360,7 +360,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');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,7 +394,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) {
|
||||||
@@ -400,7 +405,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();
|
||||||
}
|
}
|
||||||
@@ -491,8 +496,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)
|
||||||
@@ -535,7 +545,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',
|
||||||
|
|||||||
@@ -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,6 +1,6 @@
|
|||||||
"use strict";(()=>{var ct=Object.create;var Ie=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var vt=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ut(t))!ft.call(e,u)&&u!==r&&Ie(e,u,{get:()=>t[u],enumerable:!(i=lt(t,u))||i.enumerable});return e};var pt=(e,t,r)=>(r=e!=null?ct(dt(e)):{},vt(t||!e||!e.__esModule?Ie(r,"default",{value:e,enumerable:!0}):r,e));var ze=ht((Ye,je)=>{"use strict";var Ve=(function(){var e=function(M,A){var b=236,x=17,c=M,m=r[A],s=null,a=0,y=null,f=[],g={},L=function(l,d){a=c*4+17,s=(function(o){for(var h=new Array(o),p=0;p<o;p+=1){h[p]=new Array(o);for(var w=0;w<o;w+=1)h[p][w]=null}return h})(a),E(0,0),E(a-7,0),E(0,a-7),G(),I(),Q(l,d),c>=7&&z(l),y==null&&(y=it(c,m,f)),W(y,d)},E=function(l,d){for(var o=-1;o<=7;o+=1)if(!(l+o<=-1||a<=l+o))for(var h=-1;h<=7;h+=1)d+h<=-1||a<=d+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][d+h]=!0:s[l+o][d+h]=!1)},P=function(){for(var l=0,d=0,o=0;o<8;o+=1){L(!0,o);var h=u.getLostPoint(g);(o==0||l>h)&&(l=h,d=o)}return d},I=function(){for(var l=8;l<a-8;l+=1)s[l][6]==null&&(s[l][6]=l%2==0);for(var d=8;d<a-8;d+=1)s[6][d]==null&&(s[6][d]=d%2==0)},G=function(){for(var l=u.getPatternPosition(c),d=0;d<l.length;d+=1)for(var o=0;o<l.length;o+=1){var h=l[d],p=l[o];if(s[h][p]==null)for(var w=-2;w<=2;w+=1)for(var C=-2;C<=2;C+=1)w==-2||w==2||C==-2||C==2||w==0&&C==0?s[h+w][p+C]=!0:s[h+w][p+C]=!1}},z=function(l){for(var d=u.getBCHTypeNumber(c),o=0;o<18;o+=1){var h=!l&&(d>>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&&(d>>o&1)==1;s[o%3+a-8-3][Math.floor(o/3)]=h}},Q=function(l,d){for(var o=m<<3|d,h=u.getBCHTypeInfo(o),p=0;p<15;p+=1){var w=!l&&(h>>p&1)==1;p<6?s[p][8]=w:p<8?s[p+1][8]=w:s[a-15+p][8]=w}for(var p=0;p<15;p+=1){var w=!l&&(h>>p&1)==1;p<8?s[8][a-p-1]=w:p<9?s[8][15-p-1+1]=w:s[8][15-p-1]=w}s[a-8][8]=!l},W=function(l,d){for(var o=-1,h=a-1,p=7,w=0,C=u.getMaskFunction(d),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var N=0;N<2;N+=1)if(s[h][_-N]==null){var O=!1;w<l.length&&(O=(l[w]>>>p&1)==1);var T=C(h,_-N);T&&(O=!O),s[h][_-N]=O,p-=1,p==-1&&(w+=1,p=7)}if(h+=o,h<0||a<=h){h-=o,o=-o;break}}},ae=function(l,d){for(var o=0,h=0,p=0,w=new Array(d.length),C=new Array(d.length),_=0;_<d.length;_+=1){var N=d[_].dataCount,O=d[_].totalCount-N;h=Math.max(h,N),p=Math.max(p,O),w[_]=new Array(N);for(var T=0;T<w[_].length;T+=1)w[_][T]=255&l.getBuffer()[T+o];o+=N;var Y=u.getErrorCorrectPolynomial(O),j=k(w[_],Y.getLength()-1),Ne=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Re=T+Ne.getLength()-C[_].length;C[_][T]=Re>=0?Ne.getAt(Re):0}}for(var He=0,T=0;T<d.length;T+=1)He+=d[T].totalCount;for(var be=new Array(He),he=0,T=0;T<h;T+=1)for(var _=0;_<d.length;_+=1)T<w[_].length&&(be[he]=w[_][T],he+=1);for(var T=0;T<p;T+=1)for(var _=0;_<d.length;_+=1)T<C[_].length&&(be[he]=C[_][T],he+=1);return be},it=function(l,d,o){for(var h=B.getRSBlocks(l,d),p=D(),w=0;w<o.length;w+=1){var C=o[w];p.put(C.getMode(),4),p.put(C.getLength(),u.getLengthInBits(C.getMode(),l)),C.write(p)}for(var _=0,w=0;w<h.length;w+=1)_+=h[w].dataCount;if(p.getLengthInBits()>_*8)throw"code length overflow. ("+p.getLengthInBits()+">"+_*8+")";for(p.getLengthInBits()+4<=_*8&&p.put(0,4);p.getLengthInBits()%8!=0;)p.putBit(!1);for(;!(p.getLengthInBits()>=_*8||(p.put(b,8),p.getLengthInBits()>=_*8));)p.put(x,8);return ae(p,h)};g.addData=function(l,d){d=d||"Byte";var o=null;switch(d){case"Numeric":o=$(l);break;case"Alphanumeric":o=q(l);break;case"Byte":o=J(l);break;case"Kanji":o=U(l);break;default:throw"mode:"+d}f.push(o),y=null},g.isDark=function(l,d){if(l<0||a<=l||d<0||a<=d)throw l+","+d;return s[l][d]},g.getModuleCount=function(){return a},g.make=function(){if(c<1){for(var l=1;l<40;l++){for(var d=B.getRSBlocks(l,m),o=D(),h=0;h<f.length;h++){var p=f[h];o.put(p.getMode(),4),o.put(p.getLength(),u.getLengthInBits(p.getMode(),l)),p.write(o)}for(var w=0,h=0;h<d.length;h++)w+=d[h].dataCount;if(o.getLengthInBits()<=w*8)break}c=l}L(!1,P())},g.createTableTag=function(l,d){l=l||2,d=typeof d=="undefined"?l*4:d;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+d+"px;",o+='">',o+="<tbody>";for(var h=0;h<g.getModuleCount();h+=1){o+="<tr>";for(var p=0;p<g.getModuleCount();p+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+l+"px;",o+=" height: "+l+"px;",o+=" background-color: ",o+=g.isDark(h,p)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},g.createSvgTag=function(l,d,o,h){var p={};typeof arguments[0]=="object"&&(p=arguments[0],l=p.cellSize,d=p.margin,o=p.alt,h=p.title),l=l||2,d=typeof d=="undefined"?l*4:d,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
"use strict";(()=>{var ut=Object.create;var Ke=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var vt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of ft(t))!pt.call(e,l)&&l!==r&&Ke(e,l,{get:()=>t[l],enumerable:!(s=dt(t,l))||s.enumerable});return e};var mt=(e,t,r)=>(r=e!=null?ut(ht(e)):{},gt(t||!e||!e.__esModule?Ke(r,"default",{value:e,enumerable:!0}):r,e));var Qe=vt((ze,Je)=>{"use strict";var je=(function(){var e=function(x,k){var b=236,f=17,c=x,y=r[k],i=null,a=0,w=null,h=[],m={},L=function(u,d){a=c*4+17,i=(function(o){for(var p=new Array(o),g=0;g<o;g+=1){p[g]=new Array(o);for(var M=0;M<o;M+=1)p[g][M]=null}return p})(a),D(0,0),D(a-7,0),D(0,a-7),G(),K(),J(u,d),c>=7&&z(u),w==null&&(w=ct(c,y,h)),Q(w,d)},D=function(u,d){for(var o=-1;o<=7;o+=1)if(!(u+o<=-1||a<=u+o))for(var p=-1;p<=7;p+=1)d+p<=-1||a<=d+p||(0<=o&&o<=6&&(p==0||p==6)||0<=p&&p<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=p&&p<=4?i[u+o][d+p]=!0:i[u+o][d+p]=!1)},S=function(){for(var u=0,d=0,o=0;o<8;o+=1){L(!0,o);var p=l.getLostPoint(m);(o==0||u>p)&&(u=p,d=o)}return d},K=function(){for(var u=8;u<a-8;u+=1)i[u][6]==null&&(i[u][6]=u%2==0);for(var d=8;d<a-8;d+=1)i[6][d]==null&&(i[6][d]=d%2==0)},G=function(){for(var u=l.getPatternPosition(c),d=0;d<u.length;d+=1)for(var o=0;o<u.length;o+=1){var p=u[d],g=u[o];if(i[p][g]==null)for(var M=-2;M<=2;M+=1)for(var C=-2;C<=2;C+=1)M==-2||M==2||C==-2||C==2||M==0&&C==0?i[p+M][g+C]=!0:i[p+M][g+C]=!1}},z=function(u){for(var d=l.getBCHTypeNumber(c),o=0;o<18;o+=1){var p=!u&&(d>>o&1)==1;i[Math.floor(o/3)][o%3+a-8-3]=p}for(var o=0;o<18;o+=1){var p=!u&&(d>>o&1)==1;i[o%3+a-8-3][Math.floor(o/3)]=p}},J=function(u,d){for(var o=y<<3|d,p=l.getBCHTypeInfo(o),g=0;g<15;g+=1){var M=!u&&(p>>g&1)==1;g<6?i[g][8]=M:g<8?i[g+1][8]=M:i[a-15+g][8]=M}for(var g=0;g<15;g+=1){var M=!u&&(p>>g&1)==1;g<8?i[8][a-g-1]=M:g<9?i[8][15-g-1+1]=M:i[8][15-g-1]=M}i[a-8][8]=!u},Q=function(u,d){for(var o=-1,p=a-1,g=7,M=0,C=l.getMaskFunction(d),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(i[p][_-R]==null){var F=!1;M<u.length&&(F=(u[M]>>>g&1)==1);var T=C(p,_-R);T&&(F=!F),i[p][_-R]=F,g-=1,g==-1&&(M+=1,g=7)}if(p+=o,p<0||a<=p){p-=o,o=-o;break}}},re=function(u,d){for(var o=0,p=0,g=0,M=new Array(d.length),C=new Array(d.length),_=0;_<d.length;_+=1){var R=d[_].dataCount,F=d[_].totalCount-R;p=Math.max(p,R),g=Math.max(g,F),M[_]=new Array(R);for(var T=0;T<M[_].length;T+=1)M[_][T]=255&u.getBuffer()[T+o];o+=R;var Y=l.getErrorCorrectPolynomial(F),j=A(M[_],Y.getLength()-1),He=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ie=T+He.getLength()-C[_].length;C[_][T]=Ie>=0?He.getAt(Ie):0}}for(var Oe=0,T=0;T<d.length;T+=1)Oe+=d[T].totalCount;for(var xe=new Array(Oe),he=0,T=0;T<p;T+=1)for(var _=0;_<d.length;_+=1)T<M[_].length&&(xe[he]=M[_][T],he+=1);for(var T=0;T<g;T+=1)for(var _=0;_<d.length;_+=1)T<C[_].length&&(xe[he]=C[_][T],he+=1);return xe},ct=function(u,d,o){for(var p=E.getRSBlocks(u,d),g=N(),M=0;M<o.length;M+=1){var C=o[M];g.put(C.getMode(),4),g.put(C.getLength(),l.getLengthInBits(C.getMode(),u)),C.write(g)}for(var _=0,M=0;M<p.length;M+=1)_+=p[M].dataCount;if(g.getLengthInBits()>_*8)throw"code length overflow. ("+g.getLengthInBits()+">"+_*8+")";for(g.getLengthInBits()+4<=_*8&&g.put(0,4);g.getLengthInBits()%8!=0;)g.putBit(!1);for(;!(g.getLengthInBits()>=_*8||(g.put(b,8),g.getLengthInBits()>=_*8));)g.put(f,8);return re(g,p)};m.addData=function(u,d){d=d||"Byte";var o=null;switch(d){case"Numeric":o=$(u);break;case"Alphanumeric":o=P(u);break;case"Byte":o=q(u);break;case"Kanji":o=O(u);break;default:throw"mode:"+d}h.push(o),w=null},m.isDark=function(u,d){if(u<0||a<=u||d<0||a<=d)throw u+","+d;return i[u][d]},m.getModuleCount=function(){return a},m.make=function(){if(c<1){for(var u=1;u<40;u++){for(var d=E.getRSBlocks(u,y),o=N(),p=0;p<h.length;p++){var g=h[p];o.put(g.getMode(),4),o.put(g.getLength(),l.getLengthInBits(g.getMode(),u)),g.write(o)}for(var M=0,p=0;p<d.length;p++)M+=d[p].dataCount;if(o.getLengthInBits()<=M*8)break}c=u}L(!1,S())},m.createTableTag=function(u,d){u=u||2,d=typeof d=="undefined"?u*4:d;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+d+"px;",o+='">',o+="<tbody>";for(var p=0;p<m.getModuleCount();p+=1){o+="<tr>";for(var g=0;g<m.getModuleCount();g+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+u+"px;",o+=" height: "+u+"px;",o+=" background-color: ",o+=m.isDark(p,g)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},m.createSvgTag=function(u,d,o,p){var g={};typeof arguments[0]=="object"&&(g=arguments[0],u=g.cellSize,d=g.margin,o=g.alt,p=g.title),u=u||2,d=typeof d=="undefined"?u*4:d,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
||||||
`}return o%2&&l>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(l,d){if(l=l||1,l<2)return ot(d);l-=1,d=typeof d=="undefined"?l*2:d;var o=g.getModuleCount()*l+d*2,h=d,p=o-d,w,C,_,N,O=Array(l+1).join("██"),T=Array(l+1).join(" "),Y="",j="";for(w=0;w<o;w+=1){for(_=Math.floor((w-h)/l),j="",C=0;C<o;C+=1)N=1,h<=C&&C<p&&h<=w&&w<p&&g.isDark(_,Math.floor((C-h)/l))&&(N=0),j+=N?O:T;for(_=0;_<l;_+=1)Y+=j+`
|
`}return o%2&&u>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return m.createASCII=function(u,d){if(u=u||1,u<2)return lt(d);u-=1,d=typeof d=="undefined"?u*2:d;var o=m.getModuleCount()*u+d*2,p=d,g=o-d,M,C,_,R,F=Array(u+1).join("██"),T=Array(u+1).join(" "),Y="",j="";for(M=0;M<o;M+=1){for(_=Math.floor((M-p)/u),j="",C=0;C<o;C+=1)R=1,p<=C&&C<g&&p<=M&&M<g&&m.isDark(_,Math.floor((C-p)/u))&&(R=0),j+=R?F:T;for(_=0;_<u;_+=1)Y+=j+`
|
||||||
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(l,d){d=d||2;for(var o=g.getModuleCount(),h=0;h<o;h++)for(var p=0;p<o;p++)l.fillStyle=g.isDark(h,p)?"black":"white",l.fillRect(h*d,p*d,d,d)},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 f=m(),g=m(),L=m(),E=String.fromCharCode(y<<8|f),P=g<<8|L;a[E]=P,s+=1}if(s!=A)throw s+" != "+A;return a})(),x=63;return function(c){for(var m=[],s=0;s<c.length;s+=1){var a=c.charCodeAt(s);if(a<128)m.push(a);else{var y=b[c.charAt(s)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(x)}}return m}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},i={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},u=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],A=1335,b=7973,x=21522,c={},m=function(s){for(var a=0;s!=0;)a+=1,s>>>=1;return a};return c.getBCHTypeInfo=function(s){for(var a=s<<10;m(a)-m(A)>=0;)a^=A<<m(a)-m(A);return(s<<10|a)^x},c.getBCHTypeNumber=function(s){for(var a=s<<12;m(a)-m(b)>=0;)a^=b<<m(a)-m(b);return s<<12|a},c.getPatternPosition=function(s){return M[s-1]},c.getMaskFunction=function(s){switch(s){case i.PATTERN000:return function(a,y){return(a+y)%2==0};case i.PATTERN001:return function(a,y){return a%2==0};case i.PATTERN010:return function(a,y){return y%3==0};case i.PATTERN011:return function(a,y){return(a+y)%3==0};case i.PATTERN100:return function(a,y){return(Math.floor(a/2)+Math.floor(y/3))%2==0};case i.PATTERN101:return function(a,y){return a*y%2+a*y%3==0};case i.PATTERN110:return function(a,y){return(a*y%2+a*y%3)%2==0};case i.PATTERN111:return function(a,y){return(a*y%3+(a+y)%2)%2==0};default:throw"bad maskPattern:"+s}},c.getErrorCorrectPolynomial=function(s){for(var a=k([1],0),y=0;y<s;y+=1)a=a.multiply(k([1,v.gexp(y)],0));return a},c.getLengthInBits=function(s,a){if(1<=a&&a<10)switch(s){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+s}else if(a<27)switch(s){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+s}else if(a<41)switch(s){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+s}else throw"type:"+a},c.getLostPoint=function(s){for(var a=s.getModuleCount(),y=0,f=0;f<a;f+=1)for(var g=0;g<a;g+=1){for(var L=0,E=s.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||a<=f+P))for(var I=-1;I<=1;I+=1)g+I<0||a<=g+I||P==0&&I==0||E==s.isDark(f+P,g+I)&&(L+=1);L>5&&(y+=3+L-5)}for(var f=0;f<a-1;f+=1)for(var g=0;g<a-1;g+=1){var G=0;s.isDark(f,g)&&(G+=1),s.isDark(f+1,g)&&(G+=1),s.isDark(f,g+1)&&(G+=1),s.isDark(f+1,g+1)&&(G+=1),(G==0||G==4)&&(y+=3)}for(var f=0;f<a;f+=1)for(var g=0;g<a-6;g+=1)s.isDark(f,g)&&!s.isDark(f,g+1)&&s.isDark(f,g+2)&&s.isDark(f,g+3)&&s.isDark(f,g+4)&&!s.isDark(f,g+5)&&s.isDark(f,g+6)&&(y+=40);for(var g=0;g<a;g+=1)for(var f=0;f<a-6;f+=1)s.isDark(f,g)&&!s.isDark(f+1,g)&&s.isDark(f+2,g)&&s.isDark(f+3,g)&&s.isDark(f+4,g)&&!s.isDark(f+5,g)&&s.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<a;g+=1)for(var f=0;f<a;f+=1)s.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/a/a-50)/5;return y+=Q*10,y},c})(),v=(function(){for(var M=new Array(256),A=new Array(256),b=0;b<8;b+=1)M[b]=1<<b;for(var b=8;b<256;b+=1)M[b]=M[b-4]^M[b-5]^M[b-6]^M[b-8];for(var b=0;b<255;b+=1)A[M[b]]=b;var x={};return x.glog=function(c){if(c<1)throw"glog("+c+")";return A[c]},x.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return M[c]},x})();function k(M,A){if(typeof M.length=="undefined")throw M.length+"/"+A;var b=(function(){for(var c=0;c<M.length&&M[c]==0;)c+=1;for(var m=new Array(M.length-c+A),s=0;s<M.length-c;s+=1)m[s]=M[s+c];return m})(),x={};return x.getAt=function(c){return b[c]},x.getLength=function(){return b.length},x.multiply=function(c){for(var m=new Array(x.getLength()+c.getLength()-1),s=0;s<x.getLength();s+=1)for(var a=0;a<c.getLength();a+=1)m[s+a]^=v.gexp(v.glog(x.getAt(s))+v.glog(c.getAt(a)));return k(m,0)},x.mod=function(c){if(x.getLen
Line truncated
|
`}return Y.substring(0,Y.length-1)},m.renderTo2dContext=function(u,d){d=d||2;for(var o=m.getModuleCount(),p=0;p<o;p++)for(var g=0;g<o;g++)u.fillStyle=m.isDark(p,g)?"black":"white",u.fillRect(p*d,g*d,d,d)},m};e.stringToBytesFuncs={default:function(x){for(var k=[],b=0;b<x.length;b+=1){var f=x.charCodeAt(b);k.push(f&255)}return k}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(x,k){var b=(function(){for(var c=le(x),y=function(){var K=c.read();if(K==-1)throw"eof";return K},i=0,a={};;){var w=c.read();if(w==-1)break;var h=y(),m=y(),L=y(),D=String.fromCharCode(w<<8|h),S=m<<8|L;a[D]=S,i+=1}if(i!=k)throw i+" != "+k;return a})(),f=63;return function(c){for(var y=[],i=0;i<c.length;i+=1){var a=c.charCodeAt(i);if(a<128)y.push(a);else{var w=b[c.charAt(i)];typeof w=="number"?(w&255)==w?y.push(w):(y.push(w>>>8),y.push(w&255)):y.push(f)}}return y}};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},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},l=(function(){var x=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,b=7973,f=21522,c={},y=function(i){for(var a=0;i!=0;)a+=1,i>>>=1;return a};return c.getBCHTypeInfo=function(i){for(var a=i<<10;y(a)-y(k)>=0;)a^=k<<y(a)-y(k);return(i<<10|a)^f},c.getBCHTypeNumber=function(i){for(var a=i<<12;y(a)-y(b)>=0;)a^=b<<y(a)-y(b);return i<<12|a},c.getPatternPosition=function(i){return x[i-1]},c.getMaskFunction=function(i){switch(i){case s.PATTERN000:return function(a,w){return(a+w)%2==0};case s.PATTERN001:return function(a,w){return a%2==0};case s.PATTERN010:return function(a,w){return w%3==0};case s.PATTERN011:return function(a,w){return(a+w)%3==0};case s.PATTERN100:return function(a,w){return(Math.floor(a/2)+Math.floor(w/3))%2==0};case s.PATTERN101:return function(a,w){return a*w%2+a*w%3==0};case s.PATTERN110:return function(a,w){return(a*w%2+a*w%3)%2==0};case s.PATTERN111:return function(a,w){return(a*w%3+(a+w)%2)%2==0};default:throw"bad maskPattern:"+i}},c.getErrorCorrectPolynomial=function(i){for(var a=A([1],0),w=0;w<i;w+=1)a=a.multiply(A([1,v.gexp(w)],0));return a},c.getLengthInBits=function(i,a){if(1<=a&&a<10)switch(i){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:"+i}else if(a<27)switch(i){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:"+i}else if(a<41)switch(i){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:"+i}else throw"type:"+a},c.getLostPoint=function(i){for(var a=i.getModuleCount(),w=0,h=0;h<a;h+=1)for(var m=0;m<a;m+=1){for(var L=0,D=i.isDark(h,m),S=-1;S<=1;S+=1)if(!(h+S<0||a<=h+S))for(var K=-1;K<=1;K+=1)m+K<0||a<=m+K||S==0&&K==0||D==i.isDark(h+S,m+K)&&(L+=1);L>5&&(w+=3+L-5)}for(var h=0;h<a-1;h+=1)for(var m=0;m<a-1;m+=1){var G=0;i.isDark(h,m)&&(G+=1),i.isDark(h+1,m)&&(G+=1),i.isDark(h,m+1)&&(G+=1),i.isDark(h+1,m+1)&&(G+=1),(G==0||G==4)&&(w+=3)}for(var h=0;h<a;h+=1)for(var m=0;m<a-6;m+=1)i.isDark(h,m)&&!i.isDark(h,m+1)&&i.isDark(h,m+2)&&i.isDark(h,m+3)&&i.isDark(h,m+4)&&!i.isDark(h,m+5)&&i.isDark(h,m+6)&&(w+=40);for(var m=0;m<a;m+=1)for(var h=0;h<a-6;h+=1)i.isDark(h,m)&&!i.isDark(h+1,m)&&i.isDark(h+2,m)&&i.isDark(h+3,m)&&i.isDark(h+4,m)&&!i.isDark(h+5,m)&&i.isDark(h+6,m)&&(w+=40);for(var z=0,m=0;m<a;m+=1)for(var h=0;h<a;h+=1)i.isDark(h,m)&&(z+=1);var J=Math.abs(100*z/a/a-50)/5;return w+=J*10,w},c})(),v=(function(){for(var x=new Array(256),k=new Array(256),b=0;b<8;b+=1)x[b]=1<<b;for(var b=8;b<256;b+=1)x[b]=x[b-4]^x[b-5]^x[b-6]^x[b-8];for(var b=0;b<255;b+=1)k[x[b]]=b;var f={};return f.glog=function(c){if(c<1)throw"glog("+c+")";return k[c]},f.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return x[c]},f})();function A(x,k){if(typeof x.length=="undefined")throw x.length+"/"+k;var b=(function(){for(var c=0;c<x.length&&x[c]==0;)c+=1;for(var y=new Array(x.length-c+k),i=0;i<x.length-c;i+=1)y[i]=x[i+c];return y})(),f={};return f.getAt=function(c){return b[c]},f.getLength=function(){return b.length},f.multiply=function(c){for(var y=new Array(f.getLength()+c.getLength()-1),i=0;i<f.getLength();i+=1)for(var a=0;a<c.getLength();a+=1)y[i+a]^=v.gexp(v.glog(f.getAt(i))+v.glog(c.getAt(a)));return A(y,0)},f.mod=function(c){if(f.getLe
Line truncated
|
||||||
`),hostName:v,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},B={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(k),port:String(r.port),protocol_version:i.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:v};return r.dns[0]&&(B.dns1=r.dns[0]),r.dns[1]&&(B.dns2=r.dns[1]),B}function kt(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 At(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 _e(e,t,r=!0){let i=new TextEncoder().encode(JSON.stringify(Mt(e,t))),u=r?await At(i):null;return`vpn://${kt(u!=null?u:i)}`}var Ee=()=>{var e;return(e=S==null?void 0:S.today)!=null?e:ve(new Date)};function n(e,t={},...r){let i=document.createElement(e);for(let[v,k]of Object.entries(t))k==null||k===!1||(v.startsWith("on")&&typeof k=="function"?i.addEventListener(v.slice(2),k):v==="class"?i.className=String(k):k===!0?i.setAttribute(v,""):i.setAttribute(v,String(k)));let u=v=>{v==null||v===!1||(Array.isArray(v)?v.forEach(u):i.appendChild(typeof v=="string"?document.createTextNode(v):v))};return r.forEach(u),i}function K(e){let t=n("span",{class:"ic"});return t.innerHTML=qe(e,"ic-svg"),t}var _t='<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>',Be=document.getElementById("app"),Xe,me=(Xe=Be.dataset.base)!=null?Xe:"",Ct=Be.dataset.title||"Dawnline",Te=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),S=null,Tt=/^\/[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 et(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 tt(e,t){let r=i=>{Z!=null||(Z=document.body.appendChild(n("div",{class:"tip"}))),Z.replaceChildren(...t().map((u,v)=>n("div",{class:v?"muted":"tip-title"},u))),Z.style.display="",Z.style.left=`${i.clientX}px`,Z.style.top=`${i.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function Lt(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((i,u)=>{let v=n("i",{class:i?"":"zero"});v.style.height=`${Math.max(8,i/t*100)}%`;let k=e.length-1-u;tt(v,()=>[k===0?"Today":k===1?"Yesterday":pe(Oe(Ee(),-k)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ie(i)]),r.appendChild(v)}),r}async function $e(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 de(e,t,...r){let i=!!oe;ee(!0);let u=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},K("x"))),n("div",{class:"sheet-body"},...r)),v=n("div",{class:"sheet",onclick:k=>{k.target===v&&ee()}},u);return document.body.appendChild(v),document.body.classList.add("locked"),i?v.classList.add("open"):requestAnimationFrame(()=>v.classList.add("open")),o
Line truncated
|
`),hostName:v,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},E={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(A),port:String(r.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:v};return r.dns[0]&&(E.dns1=r.dns[0]),r.dns[1]&&(E.dns2=r.dns[1]),E}function _t(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 Ct(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),s=new Uint8Array(await new t.Response(r).arrayBuffer()),l=new Uint8Array(4+s.length);return new DataView(l.buffer).setUint32(0,e.length,!1),l.set(s,4),l}catch{return null}}async function Te(e,t,r=!0){let s=new TextEncoder().encode(JSON.stringify(At(e,t))),l=r?await Ct(s):null;return`vpn://${_t(l!=null?l:s)}`}var $e=()=>{var e;return(e=B==null?void 0:B.today)!=null?e:pe(new Date)};function n(e,t={},...r){let s=document.createElement(e);for(let[v,A]of Object.entries(t))A==null||A===!1||(v.startsWith("on")&&typeof A=="function"?s.addEventListener(v.slice(2),A):v==="class"?s.className=String(A):A===!0?s.setAttribute(v,""):s.setAttribute(v,String(A)));let l=v=>{v==null||v===!1||(Array.isArray(v)?v.forEach(l):s.appendChild(typeof v=="string"?document.createTextNode(v):v))};return r.forEach(l),s}function U(e){let t=n("span",{class:"ic"});return t.innerHTML=Ye(e,"ic-svg"),t}var Tt='<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>',Se=document.getElementById("app"),tt,me=(tt=Se.dataset.base)!=null?tt:"",Lt=Se.dataset.title||"Dawnline",De=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),B=null,Dt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Ee=class extends Error{constructor(r,s,l){super(s);this.status=r;this.httpsUrl=l}};async function ne(e,t){var l;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"}),s=null;try{s=await r.json()}catch{}if(!r.ok)throw new Ee(r.status,(l=s==null?void 0:s.error)!=null?l:`Request failed (${r.status})`,(s==null?void 0:s.https_url)||void 0);return s}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 oe(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let s=document.execCommand("copy");if(r.remove(),!s)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function nt(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),s=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(r),s.remove()},1e3)}var W=null;function rt(e,t){let r=s=>{W!=null||(W=document.body.appendChild(n("div",{class:"tip"}))),W.replaceChildren(...t().map((l,v)=>n("div",{class:v?"muted":"tip-title"},l))),W.style.display="",W.style.left=`${s.clientX}px`,W.style.top=`${s.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>W&&(W.style.display="none"))}function Et(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((s,l)=>{let v=n("i",{class:s?"":"zero"});v.style.height=`${Math.max(8,s/t*100)}%`;let A=e.length-1-l;rt(v,()=>[A===0?"Today":A===1?"Yesterday":ve(Ue($e(),-A)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),se(s)]),r.appendChild(v)}),r}async function Pe(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var ie=null,ue=null;function ee(e=!1){if(!ie)return;let t=ie;if(ie=null,document.body.classList.remove("locked"),ue==null||ue(),ue=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function ce(e,t,...r){let s=!!ie;ee(!0);let l=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()},U("x"))),n("div",{class:"sheet-body"},...r)),v=n("div",{class:"sheet",onclick:A=>{A.target===v&&ee()}},l);return document.body.appendChild(v),document.body.classList.add("locked"),s?v.classList.add("open
Line truncated
|
||||||
`).flatMap((v,k)=>k?[`
|
`).flatMap((v,A)=>A?[`
|
||||||
`,Ze(v,t)]:[Ze(v,t)])),u=n("button",{class:"btn small",onclick:v=>{v.preventDefault(),t=!t,u.replaceChildren(K(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),i()}},K("key"),n("span",{},"Show key"));return i(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>et(e.filename,e.conf)},K("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},K("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),u,n("button",{class:"btn small",onclick:v=>{v.preventDefault(),ce(e.conf,"Configuration copied")}},K("copy"),n("span",{},"Copy"))),r))}async function ue(e,t,r){let i=r!=null?r:await Pe(e);if(!i)return;let u=await _e(i,`${i.server} · ${i.name}`),v=Te(),k={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:u},K("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=n("div",{class:"qr"});return H.innerHTML=Qe(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:()=>Ot(i)},B=v?["app","qr","key","file"]:["qr","key","file"],D={app:"Open in app",qr:"QR code",key:"Key",file:"File"},$=n("div",{class:"tab-body"}),q=n("div",{class:"tabs",role:"tablist"}),J=H=>{q.querySelectorAll("button").forEach(re=>re.classList.toggle("on",re.dataset.id===H)),$.replaceChildren(k[H]())};for(let H of B)q.appendChild(n("button",{role:"tab","data-id":H,onclick:()=>J(H)},D[H]));J(t&&B.includes(t)?t:B[0]);let U=n("div",{class:"waiting"}),R=H=>{H!=null&&H.online?U.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(n("span",{class:"muted"},`Last connected ${xe(H.handshake)}`)):U.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};R(e);let F=window.setInterval(async()=>{try{let H=await ne("state");S=H,R(H.person.devices.find(re=>re.id===e.id))}catch{}},5e3);de(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,v?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",q,$,U),le=()=>{clearInterval(F),S&&fe(S)}}function Kt(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");de(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:i=>{i.preventDefault(),$e(r,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),fe(S),te("Renamed")}catch(u){te(u.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Ut(e,t){let r=t.here===e.id;de(`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=>$e(i.currentTarget,async()=>{try{let u=await ne(`devices/${e.id}`,{action:"rotate"});S=u.state,fe(S),await ue(e,void 0,u.config)}catch(u){te(u.message,!0)}})},"New keys")))}function Ft(e){de(`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=>$e(t.currentTarget,async()=>{try{S=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),fe(S),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,at=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function Ce(){return at||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var Gt=[[/^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
|
`,et(v,t)]:[et(v,t)])),l=n("button",{class:"btn small",onclick:v=>{v.preventDefault(),t=!t,l.replaceChildren(U(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),s()}},U("key"),n("span",{},"Show key"));return s(),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:()=>nt(e.filename,e.conf)},U("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},U("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),l,n("button",{class:"btn small",onclick:v=>{v.preventDefault(),oe(e.conf,"Configuration copied")}},U("copy"),n("span",{},"Copy"))),r))}async function de(e,t,r){let s=r!=null?r:await Re(e);if(!s)return;let l=await Te(s,`${s.server} · ${s.name}`),v=De(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:l},U("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 f=n("div",{class:"qr"});return f.innerHTML=Ze(s.conf),n("div",{class:"pane center"},f,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"},l),n("button",{class:"btn small",onclick:()=>oe(l,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Ut(s)},E=v?["app","qr","key","file"]:["qr","key","file"],N={app:"Open in app",qr:"QR code",key:"Key",file:"File"},$=n("div",{class:"tab-body"}),P=n("div",{class:"tabs",role:"tablist"}),q=f=>{P.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===f)),$.replaceChildren(A[f]())};for(let f of E)P.appendChild(n("button",{role:"tab","data-id":f,onclick:()=>q(f)},N[f]));q(t&&E.includes(t)?t:E[0]);let O=n("div",{class:"waiting"}),H=f=>{f!=null&&f.online?O.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):f!=null&&f.handshake?O.replaceChildren(n("span",{class:"muted"},`Last connected ${Me(f.handshake)}`)):O.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};H(e);let I=0,le=0,Z=!!e.handshake||e.disabled,we=Date.now(),x=async()=>{if(I=0,!(Z||Date.now()-we>6e5)){if(document.hidden){k();return}try{let f=await ne("state");B=f;let c=f.person.devices.find(y=>y.id===e.id);if(H(c),c!=null&&c.online||c!=null&&c.handshake){Z=!0;return}}catch(f){if(f.status===404||f.status===401){Z=!0;return}}le++,k()}},k=()=>{!Z&&!I&&(I=window.setTimeout(x,le<6?5e3:le<12?15e3:3e4))},b=()=>{!document.hidden&&!Z&&!I&&x()};document.addEventListener("visibilitychange",b),k(),ce(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,v?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",P,$,O),ue=()=>{Z=!0,I&&clearTimeout(I),document.removeEventListener("visibilitychange",b),B&&fe(B)}}function Ft(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");ce(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:s=>{s.preventDefault(),Pe(r,async()=>{try{B=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),fe(B),te("Renamed")}catch(l){te(l.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Gt(e,t){let r=t.here===e.id;ce(`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:s=>Pe(s.currentTarget,async()=>{try{let l=await ne(`devices/${e.id}`,{action:"rotate"});B=l.state,fe(B),await de(e,void 0,l.config)}catch(l){te(l.message,!0)}})},"New keys")))}function qt(e){ce(`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=>Pe(t.currentTarget,async()=>{try{B=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),fe(B),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,ot=/iPad/.test(V)||/Macintosh/.test(V)&&navi
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,49 @@
|
|||||||
#!/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]'
|
||||||
|
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
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,37 +82,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 +138,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 +241,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, 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 = {
|
||||||
@@ -132,22 +134,94 @@ 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:
|
||||||
@@ -164,7 +238,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',
|
||||||
@@ -299,8 +373,10 @@ export function client_config(m, dev) {
|
|||||||
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,
|
||||||
@@ -361,7 +437,9 @@ 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).
|
||||||
|
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !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)
|
||||||
@@ -381,17 +459,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],
|
||||||
@@ -401,10 +486,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;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -41,9 +41,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();
|
||||||
};
|
};
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
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';
|
||||||
@@ -68,28 +69,31 @@ 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',
|
portal_title: g('portal_title'),
|
||||||
// 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'),
|
||||||
default_device_limit: toint(s.default_device_limit, 3),
|
default_device_limit: g('default_device_limit'),
|
||||||
geo_enabled: bool(s.geo_enabled, false),
|
geo_enabled: g('geo_enabled'),
|
||||||
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is',
|
geo_provider: g('geo_provider'),
|
||||||
hostnames: bool(s.hostnames, true),
|
hostnames: g('hostnames'),
|
||||||
domain: s.domain ?? 'lan',
|
domain: g('domain'),
|
||||||
log_connections: bool(s.log_connections, true),
|
log_connections: g('log_connections'),
|
||||||
// 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.
|
||||||
@@ -158,6 +162,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',
|
||||||
@@ -236,23 +242,23 @@ function within_hours(h, ts) {
|
|||||||
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
|
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;
|
||||||
};
|
};
|
||||||
@@ -272,8 +278,8 @@ export function own_state(m, p, usage, ts) {
|
|||||||
// "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))
|
||||||
@@ -512,6 +518,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);
|
||||||
@@ -750,6 +757,69 @@ export function server_errors(m, srv, others_subnets) {
|
|||||||
return errs;
|
return errs;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What is wrong inside a model as a whole, beyond each server: devices with
|
||||||
|
* an address outside their server's subnet, the server's own address, a
|
||||||
|
* prefix on it or one shared with another device (the access sets are keyed
|
||||||
|
* by address, and one bad peer line makes `awg syncconf` refuse the whole
|
||||||
|
* server), malformed keys, people and devices pointing at servers, people,
|
||||||
|
* circles or services that do not exist, and two people with one link. [] when
|
||||||
|
* it is consistent. Import, restore and Health check it; the runtime sync
|
||||||
|
* skips what it would reject (dawnline.awg, dawnline.nft).
|
||||||
|
*/
|
||||||
|
export function model_errors(m) {
|
||||||
|
let errs = [];
|
||||||
|
let codes = {}, addrs = {};
|
||||||
|
for (let id, p in m.people) {
|
||||||
|
let who = `Person ${p.name}`;
|
||||||
|
if (p.server != '' && !m.servers[p.server])
|
||||||
|
push(errs, `${who}: server ${p.server} does not exist.`);
|
||||||
|
if (p.circle != '' && !m.circles[p.circle])
|
||||||
|
push(errs, `${who}: circle ${p.circle} does not exist.`);
|
||||||
|
for (let sid in p.services)
|
||||||
|
if (!m.services[sid])
|
||||||
|
push(errs, `${who}: home service ${sid} does not exist.`);
|
||||||
|
if (p.code != '') {
|
||||||
|
if (codes[p.code])
|
||||||
|
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`);
|
||||||
|
codes[p.code] = p.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let id, d in m.devices) {
|
||||||
|
let p = m.people[d.person];
|
||||||
|
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
|
||||||
|
if (!p) {
|
||||||
|
push(errs, `${who}: person ${d.person} does not exist.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!valid_key(d.public_key))
|
||||||
|
push(errs, `${who}: the public key is not a key.`);
|
||||||
|
if (d.private_key != '' && !valid_key(d.private_key))
|
||||||
|
push(errs, `${who}: the private key is not a key.`);
|
||||||
|
if (d.preshared_key != '' && !valid_key(d.preshared_key))
|
||||||
|
push(errs, `${who}: the preshared key is not a key.`);
|
||||||
|
let n = ip2int(d.address);
|
||||||
|
if (n == null) {
|
||||||
|
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let srv = m.servers[p.server];
|
||||||
|
let t = srv ? parse_cidr(srv.subnet) : null;
|
||||||
|
if (t && (n < t.first || n > t.last))
|
||||||
|
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`);
|
||||||
|
else if (t && n == t.first)
|
||||||
|
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`);
|
||||||
|
let key = `${p.server} ${d.address}`;
|
||||||
|
if (addrs[key])
|
||||||
|
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`);
|
||||||
|
addrs[key] = who;
|
||||||
|
}
|
||||||
|
for (let id, ci in m.circles)
|
||||||
|
if (!m.servers[ci.server])
|
||||||
|
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`);
|
||||||
|
return errs;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
|
* 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.
|
* A forwarded port never reaches the router itself, so nothing here can listen on it.
|
||||||
|
|||||||
@@ -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,19 @@ 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;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 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 ],
|
||||||
|
|||||||
@@ -403,9 +403,16 @@ 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'));
|
||||||
|
|
||||||
|
// 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');
|
||||||
|
|
||||||
|
|||||||
@@ -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 ---------- */
|
||||||
|
|
||||||
@@ -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;
|
||||||
|
|||||||
@@ -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__';
|
||||||
@@ -216,6 +224,21 @@ 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 ---------- */
|
||||||
|
|
||||||
/** 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. */
|
||||||
@@ -295,6 +318,26 @@ function need_open(r) {
|
|||||||
fail(r, '403 Forbidden', 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 });
|
||||||
|
}
|
||||||
|
|
||||||
/** 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;
|
||||||
@@ -318,6 +361,8 @@ function state(r) {
|
|||||||
},
|
},
|
||||||
can_add: length(person.devices) < person.device_limit,
|
can_add: length(person.devices) < person.device_limit,
|
||||||
locked: LOCKED[v.state] != null,
|
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(),
|
||||||
@@ -339,9 +384,11 @@ function api_state(r) {
|
|||||||
|
|
||||||
function api_add(r) {
|
function api_add(r) {
|
||||||
need_open(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) });
|
||||||
@@ -350,6 +397,7 @@ 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_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));
|
||||||
}
|
}
|
||||||
@@ -361,6 +409,7 @@ const ACTIONS = {
|
|||||||
return {};
|
return {};
|
||||||
},
|
},
|
||||||
rotate: (r, d, b) => {
|
rotate: (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.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
|
||||||
@@ -379,6 +428,7 @@ function api_device(r, id) {
|
|||||||
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) });
|
||||||
@@ -425,7 +475,7 @@ 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),
|
||||||
|
|||||||
@@ -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 ---------- */
|
||||||
@@ -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 ---------- */
|
||||||
|
|||||||
@@ -48,10 +48,10 @@ function person_update(a) {
|
|||||||
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 +67,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. */
|
||||||
@@ -142,7 +160,7 @@ export const methods = {
|
|||||||
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) },
|
||||||
|
|||||||
@@ -312,7 +312,7 @@ function server_create(a) {
|
|||||||
// after that (by hand, or by an older installer) needs a network restart.
|
// after that (by hand, or by an older installer) needs a network restart.
|
||||||
let network_restart = !awg.state().handler;
|
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');
|
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
|
||||||
return { id, applied: r, network_restart };
|
return { id, applied: r, network_restart, warning: r.warning };
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- interfaces ---------- */
|
/* ---------- interfaces ---------- */
|
||||||
|
|||||||
@@ -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 = {
|
||||||
|
|||||||
@@ -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'`);
|
||||||
|
|||||||
@@ -114,8 +114,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}'`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.5.2';
|
export const VERSION = '0.6.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';
|
||||||
|
|||||||
@@ -96,6 +96,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;
|
||||||
};
|
};
|
||||||
|
|||||||
+2
-1
@@ -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"
|
||||||
|
|||||||
+5
-19
@@ -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
|
|
||||||
Executable
+30
@@ -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
|
||||||
+43
-5
@@ -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)
|
||||||
Executable
+51
@@ -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,90 @@
|
|||||||
|
// dawnline.awg: disguise presets against their own validation, and the parser
|
||||||
|
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
|
||||||
|
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP).
|
||||||
|
import { readfile, writefile, unlink } from 'fs';
|
||||||
|
import * as awg from 'dawnline.awg';
|
||||||
|
|
||||||
|
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
|
||||||
|
let fixtures = sourcepath(0, true) + '/fixtures';
|
||||||
|
|
||||||
|
test('obf_preset off', () => {
|
||||||
|
let o = awg.obf_preset('off');
|
||||||
|
eq(o, { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }, 'plain WireGuard headers');
|
||||||
|
eq(awg.obf_errors(o), [], 'valid');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('obf_preset standard and strong', () => {
|
||||||
|
for (let name in [ 'standard', 'strong' ])
|
||||||
|
for (let i = 0; i < 25; i++) {
|
||||||
|
let o = awg.obf_preset(name);
|
||||||
|
eq(awg.obf_errors(o), [], `${name} is valid`);
|
||||||
|
let jc = +o.jc, jmin = +o.jmin, jmax = +o.jmax;
|
||||||
|
ok(name == 'strong' ? jc >= 6 && jc <= 10 : jc >= 3 && jc <= 6, `${name} jc=${o.jc}`);
|
||||||
|
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `${name} 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`);
|
||||||
|
eq(o.s3, null, 'no 2.0 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');
|
||||||
|
ok(o.i1 != awg.obf_preset('max').i1, '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');
|
||||||
|
});
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// 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');
|
||||||
|
});
|
||||||
@@ -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
|
||||||
Executable
+10
@@ -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,43 @@
|
|||||||
|
# Test fixture: a small installation (one server, two people, one device).
|
||||||
|
# migrate.test.uc expects bob's random code, the server's stored MTU 1380 and
|
||||||
|
# uhttpd's error_page: the one-time steps remove them.
|
||||||
|
|
||||||
|
config settings 'settings'
|
||||||
|
option portal_enabled '1'
|
||||||
|
option portal_port '8443'
|
||||||
|
option portal_host 'vpn.example.com'
|
||||||
|
option log_connections '0'
|
||||||
|
option update_interval '7d'
|
||||||
|
list update_targets 'app'
|
||||||
|
|
||||||
|
config server 'main'
|
||||||
|
option name 'Main'
|
||||||
|
option ifname 'awgmain'
|
||||||
|
option port '51820'
|
||||||
|
option subnet '10.9.0.0/29'
|
||||||
|
option private_key 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='
|
||||||
|
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
|
||||||
|
option mtu '1380'
|
||||||
|
option jc '4'
|
||||||
|
option jmin '64'
|
||||||
|
option jmax '128'
|
||||||
|
option s4 '12'
|
||||||
|
|
||||||
|
config person 'alice'
|
||||||
|
option server 'main'
|
||||||
|
option name 'Alice'
|
||||||
|
option code 'abcdef-ghijkl-mnopqr'
|
||||||
|
option access 'both'
|
||||||
|
|
||||||
|
config person 'bob'
|
||||||
|
option server 'main'
|
||||||
|
option name 'Bob'
|
||||||
|
option code 'XyZ12345'
|
||||||
|
option quota_gb '2'
|
||||||
|
|
||||||
|
config device 'alice_phone'
|
||||||
|
option person 'alice'
|
||||||
|
option name 'Phone'
|
||||||
|
option kind 'phone'
|
||||||
|
option address '10.9.0.2'
|
||||||
|
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
|
||||||
@@ -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,47 @@
|
|||||||
|
// 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');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('policy ranges', () => {
|
||||||
|
eq(live.policy({ log_max: '50' }).max, 100, 'max floor');
|
||||||
|
eq(live.policy({ log_max: '99999' }).max, 20000, 'max ceiling');
|
||||||
|
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, 7, 'usage days floor');
|
||||||
|
eq(live.policy({ usage_keep_months: '500' }).usage_months, 120, 'usage months ceiling');
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
});
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// dawnline.migrate: the one-time steps on the fixture config (real libuci):
|
||||||
|
// each changes what it must the first time and nothing the second time.
|
||||||
|
// This test rewrites /etc/config/dawnline and /etc/config/uhttpd.
|
||||||
|
import { cursor } from 'uci';
|
||||||
|
import { stat } from 'fs';
|
||||||
|
import * as core from 'dawnline.core';
|
||||||
|
import * as migrate from 'dawnline.migrate';
|
||||||
|
|
||||||
|
function conf(name) {
|
||||||
|
let c = cursor();
|
||||||
|
c.load(name);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('before: the fixture holds the old state', () => {
|
||||||
|
let c = conf('dawnline');
|
||||||
|
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
|
||||||
|
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
|
||||||
|
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('run: the steps change what they must', () => {
|
||||||
|
migrate.run();
|
||||||
|
let c = conf('dawnline');
|
||||||
|
ok(match(c.get('dawnline', 'bob', 'code'), core.WORD_CODE), 'bob has a word code');
|
||||||
|
eq(c.get('dawnline', 'alice', 'code'), 'abcdef-ghijkl-mnopqr', 'alice keeps hers');
|
||||||
|
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
|
||||||
|
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
|
||||||
|
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
|
||||||
|
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
|
||||||
|
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
|
||||||
|
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
|
||||||
|
user_read: true, user_write: true, user_exec: false,
|
||||||
|
group_read: false, group_write: false, group_exec: false,
|
||||||
|
other_read: false, other_write: false, other_exec: false }, 'config stays private');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('run again: a step runs once', () => {
|
||||||
|
let before = conf('dawnline').get('dawnline', 'bob', 'code');
|
||||||
|
let mtime = stat('/etc/config/dawnline').mtime;
|
||||||
|
migrate.run();
|
||||||
|
eq(conf('dawnline').get('dawnline', 'bob', 'code'), before, 'the code is not drawn again');
|
||||||
|
eq(stat('/etc/config/dawnline').mtime, mtime, 'nothing written');
|
||||||
|
});
|
||||||
Executable
+17
@@ -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,145 @@
|
|||||||
|
// 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 ', 'bad host', 'b.example.com' ]),
|
||||||
|
[ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, bad ones dropped');
|
||||||
|
eq(schema.validate('portal_alt', []), null, 'empty list removes the option');
|
||||||
|
eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: url', () => {
|
||||||
|
eq(schema.validate('portal_redirect', 'https://example.com/x?y=1'), 'https://example.com/x?y=1', 'https with path');
|
||||||
|
eq(schema.validate('portal_redirect', 'http://example.com:8080'), 'http://example.com:8080', 'http with port');
|
||||||
|
throws(() => schema.validate('portal_redirect', 'ftp://example.com'), /full http/, 'scheme');
|
||||||
|
throws(() => schema.validate('portal_redirect', 'https://example.com/<x>'), /full http/, 'angle brackets');
|
||||||
|
throws(() => schema.validate('portal_redirect', 'https://example.com/' + replace(sprintf('%300s', ''), ' ', 'a')), /full http/, 'over 300 characters');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: file', () => {
|
||||||
|
eq(schema.validate('portal_cert', '/etc/passwd'), '/etc/passwd', 'existing file');
|
||||||
|
throws(() => schema.validate('portal_cert', '/nonexistent/cert.pem'), /does not exist/, 'missing');
|
||||||
|
throws(() => schema.validate('portal_cert', 'cert.pem'), /does not exist/, 'relative');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: domain', () => {
|
||||||
|
eq(schema.validate('domain', 'lan'), 'lan', 'single');
|
||||||
|
eq(schema.validate('domain', 'home.arpa'), 'home.arpa', 'dotted');
|
||||||
|
throws(() => schema.validate('domain', 'Lan'), /lowercase/, 'upper case');
|
||||||
|
throws(() => schema.validate('domain', replace(sprintf('%33s', ''), ' ', 'a')), /lowercase/, '33-char label');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: ipv4', () => {
|
||||||
|
eq(schema.validate('home_dns_fallback', '9.9.9.9'), '9.9.9.9', 'address');
|
||||||
|
eq(schema.validate('home_dns_fallback', ''), 'none', 'empty means no fallback');
|
||||||
|
throws(() => schema.validate('home_dns_fallback', '999.1.1.1'), /IPv4/, 'bad octet');
|
||||||
|
throws(() => schema.validate('home_dns_fallback', 'dns.example'), /IPv4/, 'name');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: time', () => {
|
||||||
|
eq(schema.validate('update_time', '04:00'), '04:00', 'padded');
|
||||||
|
eq(schema.validate('update_time', '4:00'), '4:00', 'unpadded');
|
||||||
|
eq(schema.validate('update_time', '23:59'), '23:59', 'last minute');
|
||||||
|
throws(() => schema.validate('update_time', '24:00'), /HH:MM/, 'hour 24');
|
||||||
|
throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: text', () => {
|
||||||
|
eq(schema.validate('portal_title', 'My VPN'), 'My VPN', 'plain');
|
||||||
|
eq(schema.validate('portal_title', replace(sprintf('%64s', ''), ' ', 'a')), replace(sprintf('%64s', ''), ' ', 'a'), '64 characters');
|
||||||
|
throws(() => schema.validate('portal_title', replace(sprintf('%65s', ''), ' ', 'a')), /64 characters/, '65 characters');
|
||||||
|
throws(() => schema.validate('portal_title', 'a\nb'), /64 characters/, 'control character');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: targets', () => {
|
||||||
|
eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once');
|
||||||
|
eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice');
|
||||||
|
eq(schema.validate('update_targets', 'app'), [ 'none' ], 'not a list');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validate: unknown key', () => {
|
||||||
|
throws(() => schema.validate('nonsense', '1'), /Unknown setting/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('get', () => {
|
||||||
|
eq(schema.get({ portal_enabled: 'on' }, 'portal_enabled'), true, 'bool synonyms');
|
||||||
|
eq(schema.get({ portal_enabled: 'maybe' }, 'portal_enabled'), false, 'bad bool is the default');
|
||||||
|
eq(schema.get({}, 'portal_enabled'), false, 'missing bool');
|
||||||
|
eq(schema.get({ portal_port: '443' }, 'portal_port'), 443, 'int');
|
||||||
|
eq(schema.get({ portal_port: '99999' }, 'portal_port'), 8443, 'int out of range is the default');
|
||||||
|
eq(schema.get({ portal_port: 'x' }, 'portal_port'), 8443, 'bad int');
|
||||||
|
eq(schema.get({}, 'portal_alt'), [], 'missing list');
|
||||||
|
eq(schema.get({ portal_alt: 'a.example.com' }, 'portal_alt'), [ 'a.example.com' ], 'single value as list');
|
||||||
|
eq(schema.get({ portal_alt: [ 'a', '' ] }, 'portal_alt'), [ 'a' ], 'empty entries dropped');
|
||||||
|
eq(schema.get({}, 'update_targets'), [ 'app', 'packages' ], 'default targets');
|
||||||
|
eq(schema.get({ geo_provider: 'ipapi.co' }, 'geo_provider'), 'ipapi.co', 'enum');
|
||||||
|
eq(schema.get({ geo_provider: 'x' }, 'geo_provider'), 'ipwho.is', 'bad enum is the default');
|
||||||
|
eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty');
|
||||||
|
eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4');
|
||||||
|
eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4');
|
||||||
|
eq(schema.get({}, 'portal_title'), 'Dawnline', 'missing text');
|
||||||
|
eq(schema.get({ portal_title: '' }, 'portal_title'), 'Dawnline', 'empty text');
|
||||||
|
eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through');
|
||||||
|
eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value');
|
||||||
|
eq(schema.get(null, 'portal_port'), 8443, 'no section');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parsing helpers', () => {
|
||||||
|
eq(schema.bool('TRUE', false), true, 'case-insensitive');
|
||||||
|
eq(schema.bool(' 0 ', true), false, 'trimmed');
|
||||||
|
eq(schema.bool(null, true), true, 'default');
|
||||||
|
eq(schema.to_int('-5', 0, 0, 10), 0, 'below min');
|
||||||
|
eq(schema.to_int('7', 0, 0, 10), 7, 'in range');
|
||||||
|
eq(schema.to_int('7.5', 0), 0, 'not whole');
|
||||||
|
ok(schema.valid_port('65535'), 'max port');
|
||||||
|
ok(!schema.valid_port('0'), 'port 0');
|
||||||
|
ok(!schema.valid_port('65536'), 'port 65536');
|
||||||
|
ok(!schema.valid_port('12a'), 'letters');
|
||||||
|
ok(!schema.valid_port(null), 'null');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('addresses', () => {
|
||||||
|
ok(schema.ipv4('10.0.0.1') && !schema.ipv4('10.0.0.256') && !schema.ipv4(null), 'ipv4');
|
||||||
|
eq(schema.ipv6_groups('::1'), [ 0, 0, 0, 0, 0, 0, 0, 1 ], 'loopback');
|
||||||
|
eq(schema.ipv6_groups('2001:db8::1'), [ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1 ], 'compressed');
|
||||||
|
eq(schema.ipv6_groups('::ffff:192.0.2.1'), [ 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x0201 ], 'embedded IPv4');
|
||||||
|
eq(schema.ipv6_groups('1:2:3:4:5:6:7:8'), [ 1, 2, 3, 4, 5, 6, 7, 8 ], 'full');
|
||||||
|
eq(schema.ipv6_groups('1:2:3:4:5:6:7:8:9'), null, 'nine groups');
|
||||||
|
eq(schema.ipv6_groups('1:2:3:4:5:6:7'), null, 'seven groups, no gap');
|
||||||
|
eq(schema.ipv6_groups('1::2::3'), null, 'two gaps');
|
||||||
|
eq(schema.ipv6_groups('fe80::1%eth0'), null, 'zone id');
|
||||||
|
eq(schema.ipv6_groups('12345::'), null, 'group too long');
|
||||||
|
ok(schema.ip('10.0.0.1') && schema.ip('fe80::1') && !schema.ip('nope'), 'ip');
|
||||||
|
});
|
||||||
@@ -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,114 @@
|
|||||||
|
// 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 bytes');
|
||||||
|
ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 bytes');
|
||||||
|
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('Мама'), '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');
|
||||||
|
});
|
||||||
@@ -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
|
||||||
|
|||||||
Generated
+20
-2
@@ -1,17 +1,18 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.5.2",
|
"version": "0.6.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.5.2",
|
"version": "0.6.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",
|
||||||
|
|||||||
+3
-2
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.5.2",
|
"version": "0.6.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",
|
||||||
|
|||||||
+17
-10
@@ -1,15 +1,23 @@
|
|||||||
// luci.dawnline RPC bindings. The backend reports failures as { error }.
|
// luci.dawnline RPC bindings. The backend reports failures as { error }, and
|
||||||
|
// a change the router saved but could not fully put into effect (access rules
|
||||||
|
// that did not load, a server that refused its devices) as { warning }.
|
||||||
|
|
||||||
import type { Network, PortHold } from './netcheck';
|
import type { 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 {
|
||||||
@@ -360,9 +368,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
|
|||||||
'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];
|
||||||
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']);
|
||||||
@@ -459,7 +465,8 @@ 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']),
|
||||||
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
deviceCreate: call<{ id: string; config: ClientConfig }>('device_create', ['person', 'name', 'kind']),
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { E } from './e';
|
|||||||
import { icon } from '../shared/icons';
|
import { icon } from '../shared/icons';
|
||||||
|
|
||||||
export type Method = 'standard' | 'strong' | 'max' | 'off';
|
export type Method = 'standard' | 'strong' | 'max' | 'off';
|
||||||
|
/** The router features a method may need (the boolean ones of AwgCaps). */
|
||||||
|
export type AwgNeed = 'v2' | 'v3';
|
||||||
|
|
||||||
export interface MethodInfo {
|
export interface MethodInfo {
|
||||||
id: Method;
|
id: Method;
|
||||||
@@ -19,7 +21,7 @@ export interface MethodInfo {
|
|||||||
/** The same, short (server header). */
|
/** The same, short (server header). */
|
||||||
short: string;
|
short: string;
|
||||||
/** Router capability it needs. */
|
/** Router capability it needs. */
|
||||||
needs?: keyof AwgCaps;
|
needs?: AwgNeed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const METHODS: MethodInfo[] = [
|
export const METHODS: MethodInfo[] = [
|
||||||
@@ -68,13 +70,13 @@ export const METHODS: MethodInfo[] = [
|
|||||||
|
|
||||||
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
|
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
|
||||||
|
|
||||||
const NEEDS: Record<keyof AwgCaps, string> = {
|
const NEEDS: Record<AwgNeed, string> = {
|
||||||
v2: 'Needs AmneziaWG 1.5 or newer on the router.',
|
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).',
|
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The same while no AmneziaWG is installed at all ("newer" would be misleading). */
|
/** The same while no AmneziaWG is installed at all ("newer" would be misleading). */
|
||||||
const NEEDS_NONE: Record<keyof AwgCaps, string> = {
|
const NEEDS_NONE: Record<AwgNeed, string> = {
|
||||||
v2: 'Needs AmneziaWG on the router.',
|
v2: 'Needs AmneziaWG on the router.',
|
||||||
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
|
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -18,11 +18,40 @@ export function invite(page: PersonPage) {
|
|||||||
void inviteCard(page.p, server);
|
void inviteCard(page.p, server);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A new link locks the old one out of the portal, but not what it already
|
||||||
|
* got: devices added through it keep their tunnel. They are offered for
|
||||||
|
* removal here, ticked, so a leaked link is really contained.
|
||||||
|
*/
|
||||||
export async function newLink(page: PersonPage) {
|
export async function newLink(page: PersonPage) {
|
||||||
const p = page.p;
|
const p = page.p;
|
||||||
if (!(await confirmDialog('Create a new link?', 'The old link stops working right away.', 'Create new link', true))) return;
|
const since = p.code_set ?? 0;
|
||||||
const r = await attempt(() => api.personRegen(p.id), 'New link created');
|
const suspect = p.devices.filter((d) => d.created_by === 'portal' && d.created >= since);
|
||||||
if (r?.link) await copyText(r.link, 'New link copied');
|
const boxes = suspect.map(
|
||||||
|
(d) => E('input', { type: 'checkbox', id: `dl-rm-${d.id}`, checked: 'checked', 'data-id': d.id }) as HTMLInputElement,
|
||||||
|
);
|
||||||
|
const body: Node[] = [E('p', {}, 'The old link stops working right away.')];
|
||||||
|
if (suspect.length)
|
||||||
|
body.push(
|
||||||
|
E('p', {}, 'Devices added through the old link keep working until they are removed. Remove them too:'),
|
||||||
|
E(
|
||||||
|
'div',
|
||||||
|
{ class: 'dl-checklist' },
|
||||||
|
suspect.map((d, i) => E('label', { for: `dl-rm-${d.id}` }, [boxes[i], ` ${d.name}`])),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const go = async () => {
|
||||||
|
const remove = boxes.filter((b) => b.checked).map((b) => b.dataset.id as string);
|
||||||
|
const r = await attempt(
|
||||||
|
() => api.personRegen(p.id, remove),
|
||||||
|
remove.length ? `New link created, ${remove.length} device${remove.length === 1 ? '' : 's'} removed` : 'New link created',
|
||||||
|
);
|
||||||
|
if (!r) return;
|
||||||
|
closeModal();
|
||||||
|
if (remove.length) await page.refresh();
|
||||||
|
if (r.link) await copyText(r.link, 'New link copied');
|
||||||
|
};
|
||||||
|
modal('Create a new link?', body, [cancelButton(), ' ', button('Create new link', go, 'negative')]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function editNote(page: PersonPage) {
|
export function editNote(page: PersonPage) {
|
||||||
|
|||||||
@@ -16,6 +16,10 @@
|
|||||||
|
|
||||||
/* dialogs */
|
/* dialogs */
|
||||||
.dl-modal .cbi-tabmenu { margin-bottom: 16px; }
|
.dl-modal .cbi-tabmenu { margin-bottom: 16px; }
|
||||||
|
/* A list of things to tick (devices to remove with an old link). */
|
||||||
|
.dl-checklist { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 8px; }
|
||||||
|
.dl-checklist label { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; }
|
||||||
|
.dl-checklist input { margin: 0; }
|
||||||
.dl-invite { display: grid; grid-template-columns: 250px minmax(0, 1fr); gap: 22px; align-items: start; }
|
.dl-invite { display: grid; grid-template-columns: 250px minmax(0, 1fr); gap: 22px; align-items: start; }
|
||||||
.dl-invite img { display: block; width: 100%; border-radius: 18px; box-shadow: 0 0 0 1px var(--dl-line); }
|
.dl-invite img { display: block; width: 100%; border-radius: 18px; box-shadow: 0 0 0 1px var(--dl-line); }
|
||||||
.dl-invite-side { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
.dl-invite-side { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ function checkIcon(id: string): string {
|
|||||||
if (id === 'clock') return 'clock';
|
if (id === 'clock') return 'clock';
|
||||||
if (id === 'agent') return 'activity';
|
if (id === 'agent') return 'activity';
|
||||||
if (id === 'nft') return 'lock';
|
if (id === 'nft') return 'lock';
|
||||||
|
if (id === 'data') return 'users';
|
||||||
return 'alert';
|
return 'alert';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+88
-8
@@ -34,6 +34,8 @@ interface State {
|
|||||||
can_add: boolean;
|
can_add: boolean;
|
||||||
/** The admin stopped the person (paused, access ended): the page only shows. */
|
/** The admin stopped the person (paused, access ended): the page only shows. */
|
||||||
locked?: boolean;
|
locked?: boolean;
|
||||||
|
/** Over plain HTTP: the same link over HTTPS, where the connection settings are. */
|
||||||
|
https_url?: string | null;
|
||||||
kinds: Kind[];
|
kinds: Kind[];
|
||||||
version: string;
|
version: string;
|
||||||
/** The router's day (YYYY-MM-DD) when it sends one; the browser's otherwise. */
|
/** The router's day (YYYY-MM-DD) when it sends one; the browser's otherwise. */
|
||||||
@@ -87,6 +89,8 @@ class ApiError extends Error {
|
|||||||
constructor(
|
constructor(
|
||||||
public status: number,
|
public status: number,
|
||||||
message: string,
|
message: string,
|
||||||
|
/** The HTTPS twin of this link, when the answer was "not over plain HTTP". */
|
||||||
|
public httpsUrl?: string,
|
||||||
) {
|
) {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
@@ -106,7 +110,7 @@ async function call<T>(path: string, body?: unknown): Promise<T> {
|
|||||||
} catch {
|
} catch {
|
||||||
/* empty */
|
/* empty */
|
||||||
}
|
}
|
||||||
if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`);
|
if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`, data?.https_url || undefined);
|
||||||
return data as T;
|
return data as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -682,11 +686,44 @@ function main(st: State) {
|
|||||||
|
|
||||||
/* ---------- device flows ---------- */
|
/* ---------- device flows ---------- */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A plain-HTTP link (an IP address) shows the page, but keys only travel
|
||||||
|
* encrypted: the connection settings are on the HTTPS twin. Its certificate
|
||||||
|
* is the router's own, so the browser warns once; say so.
|
||||||
|
*/
|
||||||
|
function secureSheet(url: string) {
|
||||||
|
sheet(
|
||||||
|
'Open the link securely',
|
||||||
|
'Connection settings only travel encrypted',
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'stack gap' },
|
||||||
|
h('p', { class: 'muted' }, 'This page is open without encryption. To add or set up a device, open the same link over HTTPS:'),
|
||||||
|
h('a', { class: 'btn primary block big', href: url }, ic('lock'), h('span', {}, 'Open securely')),
|
||||||
|
h(
|
||||||
|
'p',
|
||||||
|
{ class: 'faint s' },
|
||||||
|
'The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The secure twin when this page is plain HTTP, else null. */
|
||||||
|
const httpsTwin = () => state?.https_url || null;
|
||||||
|
|
||||||
async function getConfig(d: Device): Promise<ClientConfig | null> {
|
async function getConfig(d: Device): Promise<ClientConfig | null> {
|
||||||
|
const twin = httpsTwin();
|
||||||
|
if (twin) {
|
||||||
|
secureSheet(twin);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return await call<ClientConfig>(`devices/${d.id}/config`);
|
return await call<ClientConfig>(`devices/${d.id}/config`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast((e as Error).message, true);
|
const er = e as ApiError;
|
||||||
|
if (er.httpsUrl) secureSheet(er.httpsUrl);
|
||||||
|
else toast(er.message, true);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -844,15 +881,47 @@ async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn
|
|||||||
else live.replaceChildren(h('span', { class: 'warn' }, 'Waiting for the first connection…'));
|
else live.replaceChildren(h('span', { class: 'warn' }, 'Waiting for the first connection…'));
|
||||||
};
|
};
|
||||||
paintLive(d);
|
paintLive(d);
|
||||||
const watch = window.setInterval(async () => {
|
// Only while the first connection is awaited (every poll is a process on
|
||||||
|
// the router): 5 s at first, then slower, for ten minutes at most, not
|
||||||
|
// while the tab is hidden, and never again once the link stopped working
|
||||||
|
// (a replaced link would otherwise count as guesses from this network).
|
||||||
|
let timer = 0,
|
||||||
|
polls = 0,
|
||||||
|
done = !!d.handshake || d.disabled;
|
||||||
|
const started = Date.now();
|
||||||
|
const poll = async () => {
|
||||||
|
timer = 0;
|
||||||
|
if (done || Date.now() - started > 600_000) return;
|
||||||
|
if (document.hidden) {
|
||||||
|
schedule();
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const st = await call<State>('state');
|
const st = await call<State>('state');
|
||||||
state = st;
|
state = st;
|
||||||
paintLive(st.person.devices.find((x) => x.id === d.id));
|
const dev = st.person.devices.find((x) => x.id === d.id);
|
||||||
} catch {
|
paintLive(dev);
|
||||||
/* ignore */
|
if (dev?.online || dev?.handshake) {
|
||||||
|
done = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as ApiError).status === 404 || (e as ApiError).status === 401) {
|
||||||
|
done = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, 5000);
|
polls++;
|
||||||
|
schedule();
|
||||||
|
};
|
||||||
|
const schedule = () => {
|
||||||
|
if (!done && !timer) timer = window.setTimeout(poll, polls < 6 ? 5000 : polls < 12 ? 15000 : 30000);
|
||||||
|
};
|
||||||
|
const onVisible = () => {
|
||||||
|
if (!document.hidden && !done && !timer) void poll();
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', onVisible);
|
||||||
|
schedule();
|
||||||
sheet(
|
sheet(
|
||||||
d.handshake ? `Connect ${d.name}` : `${d.name} is ready`,
|
d.handshake ? `Connect ${d.name}` : `${d.name} is ready`,
|
||||||
mobile ? 'Add it to AmneziaVPN on this phone' : 'Scan with the phone’s camera or AmneziaVPN',
|
mobile ? 'Add it to AmneziaVPN on this phone' : 'Scan with the phone’s camera or AmneziaVPN',
|
||||||
@@ -861,7 +930,9 @@ async function connect(d: Device, initial?: 'app' | 'qr' | 'key' | 'file', cfgIn
|
|||||||
live,
|
live,
|
||||||
);
|
);
|
||||||
sheetClosed = () => {
|
sheetClosed = () => {
|
||||||
clearInterval(watch);
|
done = true;
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
document.removeEventListener('visibilitychange', onVisible);
|
||||||
if (state) main(state);
|
if (state) main(state);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1023,6 +1094,11 @@ function guessName(kind: Kind): string {
|
|||||||
|
|
||||||
function addDevice() {
|
function addDevice() {
|
||||||
if (!state) return;
|
if (!state) return;
|
||||||
|
const twin = httpsTwin();
|
||||||
|
if (twin) {
|
||||||
|
secureSheet(twin);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let kind: Kind = guessKind();
|
let kind: Kind = guessKind();
|
||||||
const taken = new Set(state.person.devices.map((d) => d.name.toLowerCase()));
|
const taken = new Set(state.person.devices.map((d) => d.name.toLowerCase()));
|
||||||
const suggest = (k: Kind) => {
|
const suggest = (k: Kind) => {
|
||||||
@@ -1084,6 +1160,10 @@ function addDevice() {
|
|||||||
const dev = r.state.person.devices.find((d) => d.id === r.id)!;
|
const dev = r.state.person.devices.find((d) => d.id === r.id)!;
|
||||||
await connect(dev, undefined, r.config);
|
await connect(dev, undefined, r.config);
|
||||||
} catch (er) {
|
} catch (er) {
|
||||||
|
if ((er as ApiError).httpsUrl) {
|
||||||
|
secureSheet((er as ApiError).httpsUrl as string);
|
||||||
|
return;
|
||||||
|
}
|
||||||
err.textContent = (er as Error).message;
|
err.textContent = (er as Error).message;
|
||||||
submit.disabled = false;
|
submit.disabled = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ export interface Person {
|
|||||||
/** Circle id on their server (when the server uses circles); admin only. */
|
/** Circle id on their server (when the server uses circles); admin only. */
|
||||||
circle?: string;
|
circle?: string;
|
||||||
created?: number;
|
created?: number;
|
||||||
|
/** When the personal link was last made (0: unknown); admin only. */
|
||||||
|
code_set?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type MeshMode = 'off' | 'all' | 'circles';
|
export type MeshMode = 'off' | 'all' | 'circles';
|
||||||
@@ -170,6 +172,11 @@ export interface Geo {
|
|||||||
export interface AwgCaps {
|
export interface AwgCaps {
|
||||||
v2: boolean;
|
v2: boolean;
|
||||||
v3: boolean;
|
v3: boolean;
|
||||||
|
/** Generations of the tools and the kernel module ('1.0' | '2.0' | '3.1'; null unknown). */
|
||||||
|
tools?: string | null;
|
||||||
|
kmod?: string | null;
|
||||||
|
/** The two differ: a feature counts only when both have it. */
|
||||||
|
mismatch?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Whether AmneziaWG can run here: tools and kernel module installed, the module loaded, netifd's proto handler present. */
|
/** Whether AmneziaWG can run here: tools and kernel module installed, the module loaded, netifd's proto handler present. */
|
||||||
|
|||||||
+2
-1
@@ -9,7 +9,8 @@
|
|||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"forceConsistentCasingInFileNames": true,
|
"forceConsistentCasingInFileNames": true,
|
||||||
"noEmit": true
|
"noEmit": true,
|
||||||
|
"types": []
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": { "types": ["node"] },
|
||||||
|
"include": ["src", "tests"]
|
||||||
|
}
|
||||||
Reference in new issue
Block a user