Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2388603322 | ||
|
|
750564ab7e | ||
|
|
3fadee87d3 | ||
|
|
ba231e7187 | ||
|
|
a1915f070b | ||
|
|
dc0f159447 | ||
|
|
58492be021 | ||
|
|
db9657c01c | ||
|
|
fb73ac3a9f |
No files matched your search
@@ -33,7 +33,7 @@ jobs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -63,14 +63,14 @@ jobs:
|
||||
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '26'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
@@ -87,7 +87,7 @@ jobs:
|
||||
run: scripts/build-packages.sh ${{ matrix.type }}
|
||||
|
||||
- name: Upload
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: package-${{ matrix.type }}
|
||||
# The app and its translation packages (luci-i18n-dawnline-<lang>).
|
||||
@@ -105,7 +105,7 @@ jobs:
|
||||
steps:
|
||||
# The whole history and the tags: the notes list the commits since the previous tag.
|
||||
- name: Checkout
|
||||
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
@@ -116,7 +116,7 @@ jobs:
|
||||
cat notes.md
|
||||
|
||||
- name: Download packages
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
pattern: package-*
|
||||
path: release
|
||||
@@ -129,7 +129,7 @@ jobs:
|
||||
cat sha256sums.txt
|
||||
|
||||
- name: Publish the release
|
||||
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
|
||||
with:
|
||||
name: Dawnline ${{ github.ref_name }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
|
||||
@@ -24,14 +24,14 @@ jobs:
|
||||
working-directory: web
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v5
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: '22'
|
||||
node-version: '26'
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
@@ -51,6 +51,20 @@ jobs:
|
||||
id: types
|
||||
run: npm run --silent typecheck
|
||||
|
||||
# oxlint's correctness rules: what the types let through (a stray expression, a needless escape).
|
||||
- name: Lint
|
||||
id: lint
|
||||
run: npm run --silent lint
|
||||
|
||||
# Exports nobody imports, files nobody reaches, dependencies used but not listed (or listed but unused).
|
||||
- name: Unused code
|
||||
id: knip
|
||||
run: |
|
||||
if ! npm run --silent knip; then
|
||||
echo "::error::knip found unused code or a dependency problem: remove it, or drop the export when only its own file uses it."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The catalogs follow the code: every string collected, translated, its placeholders kept.
|
||||
- name: Translations
|
||||
id: i18n
|
||||
@@ -64,17 +78,17 @@ jobs:
|
||||
id: tests
|
||||
run: npm test
|
||||
|
||||
# The bundles under package/ are committed: a build must change nothing
|
||||
# and leave no new file behind (an output nobody added to git would be
|
||||
# missing from the package).
|
||||
- name: Build bundles and check they are committed
|
||||
# The bundles under package/ are not committed (build.yml builds them
|
||||
# before packaging): a build must touch no tracked file and leave every
|
||||
# output it writes ignored by .gitignore, so none ends up in a commit.
|
||||
- name: Build bundles and check they stay out of git
|
||||
id: build
|
||||
run: |
|
||||
npm run --silent build
|
||||
changed="$(git status --porcelain --untracked-files=all -- ../package)"
|
||||
if [ -n "$changed" ]; then
|
||||
echo "$changed"
|
||||
echo "::error::The committed bundles are out of date or the build left new files. Run 'npm run build' in web/ and commit the result."
|
||||
echo "::error::The build changed a tracked file under package/ or wrote one .gitignore does not cover."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -88,6 +102,8 @@ jobs:
|
||||
echo "|---|---|"
|
||||
echo "| Formatting | ${{ steps.format.outcome }} |"
|
||||
echo "| Types | ${{ steps.types.outcome }} |"
|
||||
echo "| Lint | ${{ steps.lint.outcome }} |"
|
||||
echo "| Unused code | ${{ steps.knip.outcome }} |"
|
||||
echo "| Translations | ${{ steps.i18n.outcome }} |"
|
||||
echo "| Tests | ${{ steps.tests.outcome }} |"
|
||||
echo "| Bundles | ${{ steps.build.outcome }} |"
|
||||
@@ -98,7 +114,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -127,7 +143,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -174,7 +190,7 @@ jobs:
|
||||
release: ['24.10', '25.12']
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
|
||||
@@ -2,3 +2,6 @@ node_modules/
|
||||
dist/
|
||||
.DS_Store
|
||||
web/coverage/
|
||||
# The web bundles: web/ builds them (npm run build), CI before packaging.
|
||||
package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/
|
||||
package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/
|
||||
@@ -9,6 +9,7 @@ Guidance for coding agents working in this repository (`tickcount/luci-app-dawnl
|
||||
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
|
||||
- `rules/shell.md` — install, uninstall, init and CI scripts.
|
||||
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
|
||||
- `DESIGN.md` — the personal portal's design system: tokens, components, layout and motion, measured on the live page. Read it before any work on the portal (`web/src/portal`, and what it uses from `web/src/shared`); a change to how the portal looks or moves updates it in the same change.
|
||||
- `rules/i18n.md` — translations: every visible string and backend message wrapped, the catalogs, the Russian style guide and glossary. Anything added to the admin UI or the portal is localized in the same change; anything removed takes its catalog entries with it.
|
||||
|
||||
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
|
||||
@@ -16,7 +17,7 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
|
||||
## Layout
|
||||
|
||||
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
|
||||
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`. `web/i18n/` — the string catalogs' tools (`extract.ts`, `po.ts`, `lmo.ts`).
|
||||
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; `npm run build` writes the bundles under `package/` (git-ignored: CI builds them before packaging). `web/i18n/` — the string catalogs' tools (`extract.ts`, `po.ts`, `lmo.ts`).
|
||||
- `package/luci-app-dawnline/po/` — the admin's catalog (`templates/dawnline.pot`, `ru/dawnline.po`): luci.mk builds the `luci-i18n-dawnline-ru` package from it. The portal's catalog is `web/src/portal/i18n/ru.po`, bundled into the portal.
|
||||
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
|
||||
- `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`.
|
||||
@@ -26,7 +27,7 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
|
||||
|
||||
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
|
||||
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
|
||||
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run i18n:check` (after changing visible text: `npm run i18n`, translate the new entries in each `ru.po`), `npm test`, `npm run build` — and commit the rebuilt bundles and the catalogs (CI fails on a changed or new file under `package/`).
|
||||
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run lint` (oxlint), `npm run knip` (unused exports and dependencies), `npm run i18n:check` (after changing visible text: `npm run i18n`, translate the new entries in each `ru.po`), `npm test`, `npm run build` — and commit the catalogs (the bundles stay out of git; CI fails when the build leaves a file under `package/` that `.gitignore` does not cover).
|
||||
- `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`).
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ follows a modern design.
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🏠 Internet like a home device</h3>
|
||||
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
|
||||
<p>Turn it on and people's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too. Off by default: it costs speed.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🗺️ Overview and places</h3>
|
||||
@@ -400,19 +400,21 @@ scripts/ build, deploy and check scripts
|
||||
cd web
|
||||
npm ci
|
||||
npm run format # Prettier
|
||||
npm run ci # format check, types, catalogs, tests, minified bundles
|
||||
npm run ci # format check, types, lint, unused code, catalogs, tests, minified bundles
|
||||
npm run i18n # collect new strings into the catalogs (then translate them in ru.po)
|
||||
|
||||
scripts/lint-ucode.py # static ucode checks
|
||||
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
||||
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
||||
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
||||
scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
|
||||
scripts/capture-screenshots.mjs --demo # the admin's README screenshots from a router, a demo cast in place of its people
|
||||
scripts/capture-portal.mjs # the portal's from its demo, in English and Russian
|
||||
scripts/frame-screenshots.py # frame them for this README
|
||||
```
|
||||
|
||||
The web bundles and the catalogs are committed: CI fails when they are out of
|
||||
date or a string is untranslated (`rules/i18n.md`). Pushing a tag `vX.Y.Z`
|
||||
The web bundles are built, not committed (`npm run build` before
|
||||
`scripts/build-packages.sh`); the catalogs are committed, and CI fails when they
|
||||
are out of date or a string is untranslated (`rules/i18n.md`). Pushing a tag `vX.Y.Z`
|
||||
(matching `PKG_VERSION`) builds the packages and their translations with the
|
||||
OpenWrt SDK and publishes a release with `sha256sums.txt`.
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
|
||||
**на какой срок, сколько трафика и в какие часы**.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
|
||||
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal-ru.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
|
||||
<br>
|
||||
<sub>Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился.
|
||||
<a href="https://dawnline-demo.vercel.app"><b>Попробуйте в демо</b></a>: ничего не устанавливается и никуда не подключается.</sub>
|
||||
@@ -110,7 +110,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
|
||||
<tr>
|
||||
<td valign="top">
|
||||
<h3>🏠 Интернет как у домашних устройств</h3>
|
||||
<p>Устройства людей выходят в интернет так же, как домашние, поэтому ваши прокси, фильтры рекламы и DNS работают и для них.</p>
|
||||
<p>Включите, и устройства людей выйдут в интернет так же, как домашние: ваши прокси, фильтры рекламы и DNS сработают и для них. По умолчанию выключено: это стоит скорости.</p>
|
||||
</td>
|
||||
<td valign="top">
|
||||
<h3>🗺️ Обзор и места</h3>
|
||||
@@ -161,7 +161,7 @@ flowchart LR
|
||||
## 📸 Как это выглядит
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/screenshots/overview.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
|
||||
<img src="docs/screenshots/overview-ru.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
|
||||
<br>
|
||||
<sub><b>Обзор</b>: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.</sub>
|
||||
</p>
|
||||
@@ -169,11 +169,11 @@ flowchart LR
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people.png">
|
||||
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people-ru.png">
|
||||
<p align="center"><sub><b>Люди</b>: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.</sub></p>
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person.png">
|
||||
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person-ru.png">
|
||||
<p align="center"><sub><b>Человек</b>: его устройства, трафик, места и лимиты.</sub></p>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -404,19 +404,21 @@ scripts/ скрипты сборки, деплоя и
|
||||
cd web
|
||||
npm ci
|
||||
npm run format # Prettier
|
||||
npm run ci # форматирование, типы, каталоги, тесты, минифицированные бандлы
|
||||
npm run ci # форматирование, типы, линтер, неиспользуемый код, каталоги, тесты, бандлы
|
||||
npm run i18n # собрать новые строки в каталоги (затем перевести их в ru.po)
|
||||
|
||||
scripts/lint-ucode.py # статические проверки ucode
|
||||
scripts/check-ucode.sh root@router # скомпилировать все файлы ucode на роутере
|
||||
scripts/deploy.sh root@router # поставить рабочую копию (сначала сохраняет конфиги)
|
||||
scripts/build-packages.sh all # .ipk и .apk в OpenWrt SDK в Docker
|
||||
scripts/capture-screenshots.mjs --demo # скриншоты для README с роутера, с демо-людьми вместо настоящих
|
||||
scripts/capture-screenshots.mjs --demo # скриншоты админки для README с роутера, с демо-людьми вместо настоящих
|
||||
scripts/capture-portal.mjs # скриншоты портала для README из его демо, на английском и русском
|
||||
scripts/frame-screenshots.py # оформить их для README
|
||||
```
|
||||
|
||||
Бандлы и каталоги лежат в репозитории: CI падает, если они устарели или строка
|
||||
не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
|
||||
Бандлы не лежат в репозитории, они собираются (`npm run build` перед
|
||||
`scripts/build-packages.sh`); каталоги лежат, и CI падает, если они устарели или
|
||||
строка не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
|
||||
собирает пакеты и переводы в OpenWrt SDK и публикует релиз с `sha256sums.txt`.
|
||||
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Builds luci-app-dawnline with the OpenWrt SDK.
|
||||
# docker build -f build/Dockerfile --build-arg SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6 .
|
||||
# The web bundles (htdocs/.../app.js, portal assets) are built by npm first and
|
||||
# committed; the SDK only packs files, so the package is the same on every arch.
|
||||
# The web bundles (htdocs/.../app.js, portal assets) are built by npm first
|
||||
# (not committed); the SDK only packs files, so the package is the same on every arch.
|
||||
ARG SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6
|
||||
FROM ${SDK_IMAGE}
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 446 KiB |
|
After Width: | Height: | Size: 419 KiB |
|
After Width: | Height: | Size: 436 KiB |
|
After Width: | Height: | Size: 403 KiB |
|
Before Width: | Height: | Size: 363 KiB After Width: | Height: | Size: 387 KiB |
|
After Width: | Height: | Size: 423 KiB |
|
After Width: | Height: | Size: 395 KiB |
|
After Width: | Height: | Size: 412 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 79 KiB After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 184 KiB |
|
Before Width: | Height: | Size: 187 KiB After Width: | Height: | Size: 186 KiB |
@@ -6,7 +6,7 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-dawnline
|
||||
PKG_VERSION:=0.11.0
|
||||
PKG_VERSION:=0.16.0
|
||||
PKG_RELEASE:=1
|
||||
PKG_LICENSE:=MIT
|
||||
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
// Generated from dawnline/web — do not edit by hand.
|
||||
'use strict';
|
||||
'require baseclass';
|
||||
'require dom';
|
||||
'require poll';
|
||||
'require rpc';
|
||||
'require ui';
|
||||
var Ha=Object.create;var Go=Object.defineProperty;var za=Object.getOwnPropertyDescriptor;var Ra=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,Ba=Object.prototype.hasOwnProperty;var Oa=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ja=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ra(e))!Ba.call(n,r)&&r!==o&&Go(n,r,{get:()=>e[r],enumerable:!(s=za(e,r))||s.enumerable});return n};var Ua=(n,e,o)=>(o=n!=null?Ha(Ia(n)):{},ja(e||!n||!n.__esModule?Go(o,"default",{value:n,enumerable:!0}):o,n));var os=Oa((ts,ns)=>{"use strict";var es=(function(){var n=function(S,$){var b=236,C=17,w=S,z=o[$],y=null,f=0,x=null,T=[],I={},Y=function(R,O){f=w*4+17,y=(function(P){for(var U=new Array(P),D=0;D<P;D+=1){U[D]=new Array(P);for(var G=0;G<P;G+=1)U[D][G]=null}return U})(f),J(0,0),J(f-7,0),J(0,f-7),Q(),B(),fe(R,O),w>=7&&ne(R),x==null&&(x=V(w,z,T)),se(x,O)},J=function(R,O){for(var P=-1;P<=7;P+=1)if(!(R+P<=-1||f<=R+P))for(var U=-1;U<=7;U+=1)O+U<=-1||f<=O+U||(0<=P&&P<=6&&(U==0||U==6)||0<=U&&U<=6&&(P==0||P==6)||2<=P&&P<=4&&2<=U&&U<=4?y[R+P][O+U]=!0:y[R+P][O+U]=!1)},te=function(){for(var R=0,O=0,P=0;P<8;P+=1){Y(!0,P);var U=r.getLostPoint(I);(P==0||R>U)&&(R=U,O=P)}return O},B=function(){for(var R=8;R<f-8;R+=1)y[R][6]==null&&(y[R][6]=R%2==0);for(var O=8;O<f-8;O+=1)y[6][O]==null&&(y[6][O]=O%2==0)},Q=function(){for(var R=r.getPatternPosition(w),O=0;O<R.length;O+=1)for(var P=0;P<R.length;P+=1){var U=R[O],D=R[P];if(y[U][D]==null)for(var G=-2;G<=2;G+=1)for(var ee=-2;ee<=2;ee+=1)G==-2||G==2||ee==-2||ee==2||G==0&&ee==0?y[U+G][D+ee]=!0:y[U+G][D+ee]=!1}},ne=function(R){for(var O=r.getBCHTypeNumber(w),P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;y[Math.floor(P/3)][P%3+f-8-3]=U}for(var P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;y[P%3+f-8-3][Math.floor(P/3)]=U}},fe=function(R,O){for(var P=z<<3|O,U=r.getBCHTypeInfo(P),D=0;D<15;D+=1){var G=!R&&(U>>D&1)==1;D<6?y[D][8]=G:D<8?y[D+1][8]=G:y[f-15+D][8]=G}for(var D=0;D<15;D+=1){var G=!R&&(U>>D&1)==1;D<8?y[8][f-D-1]=G:D<9?y[8][15-D-1+1]=G:y[8][15-D-1]=G}y[f-8][8]=!R},se=function(R,O){for(var P=-1,U=f-1,D=7,G=0,ee=r.getMaskFunction(O),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var be=0;be<2;be+=1)if(y[U][X-be]==null){var Le=!1;G<R.length&&(Le=(R[G]>>>D&1)==1);var re=ee(U,X-be);re&&(Le=!Le),y[U][X-be]=Le,D-=1,D==-1&&(G+=1,D=7)}if(U+=P,U<0||f<=U){U-=P,P=-P;break}}},j=function(R,O){for(var P=0,U=0,D=0,G=new Array(O.length),ee=new Array(O.length),X=0;X<O.length;X+=1){var be=O[X].dataCount,Le=O[X].totalCount-be;U=Math.max(U,be),D=Math.max(D,Le),G[X]=new Array(be);for(var re=0;re<G[X].length;re+=1)G[X][re]=255&R.getBuffer()[re+P];P+=be;var Ie=r.getErrorCorrectPolynomial(Le),Be=i(G[X],Ie.getLength()-1),jo=Be.mod(Ie);ee[X]=new Array(Ie.getLength()-1);for(var re=0;re<ee[X].length;re+=1){var Uo=re+jo.getLength()-ee[X].length;ee[X][re]=Uo>=0?jo.getAt(Uo):0}}for(var Wo=0,re=0;re<O.length;re+=1)Wo+=O[re].totalCount;for(var Vn=new Array(Wo),rn=0,re=0;re<U;re+=1)for(var X=0;X<O.length;X+=1)re<G[X].length&&(Vn[rn]=G[X][re],rn+=1);for(var re=0;re<D;re+=1)for(var X=0;X<O.length;X+=1)re<ee[X].length&&(Vn[rn]=ee[X][re],rn+=1);return Vn},V=function(R,O,P){for(var U=l.getRSBlocks(R,O),D=d(),G=0;G<P.length;G+=1){var ee=P[G];D.put(ee.getMode(),4),D.put(ee.getLength(),r.getLengthInBits(ee.getMode(),R)),ee.write(D)}for(var X=0,G=0;G<U.length;G+=1)X+=U[G].dataCount;if(D.getLengthInBits()>X*8)throw"code length overflow. ("+D.getLengthInBits()+">"+X*8+")";for(D.getLengthInBits()+4<=X*8&&D.put(0,4);D.getLengthInBits()%8!=0;)D.putBit(!1);for(;!(D.getLengthInBits()>=X*8||(D.put(b,8),D.getLengthInBits()>=X*8));)D.put(C,8);return j(D,U)};I.addData=function(R,O){O=O||"Byte";var P=null;switch(O){case"Numeric":P=c(R);break;case"Alphanumeric":P=p(R);break;case"Byte":P=u(R);break;case"Kanji":P=k(R);break;default:throw"mode:"+O}T.push(P),x=null},I.isDark=function(R,O){if(R<0||f<=R||O<0||f<=O)throw R+","+O;return y[R][O]},I.getModuleCount=function(){return f},I.make=function(){if(w<1){for(var R=1;R<40;R++){for(var O=l.getRSBlocks(R,z),P=d(),U=0;U<T.length;U++){var D=T[U];P.put(D.getMode(),4),P.put(D.getLength(),r.getLengthInBits(D.getMode(),R)),D.write(P)}for(var G=0,U=0;U<O.length;U++)G+=O[U].dataCount;if(P.getLengthInBits()<=G*8)break}w=R}Y(!1,te())},I.createTableTag=function(R,O){R=R||2,O=typeof O>"u"?R*4:O;var P="";P+='<table style="',P+=" border-width: 0px; border-style: none;",P+=" border-collapse: collapse;",P+=" padding: 0px; margin: "+O+"px;",P+='">',P+="<tbody>";for(var U=0;U<I.getModuleCount();U+=1){P+="<tr>";for(var D=0;D<I.getModuleCount();D+=1)P+='<td style="',P+=" border-width: 0px; border-style: none;",P+=" border-collapse: collapse;",P+=" padding: 0px; margin: 0px;",P+=" width: "+R+"px;",P+=" height: "+R+"px;",P+=" background-color: ",P+=I.isDark(U,D)?"#000000":"#ffffff",P+=";",P+='"/>';P+="</tr>"}return P+="</tbody>",P+="</table>",P},I.createSvgTag=function(R,O,P,U){var D={};typeof arguments[0]=="object"&&(D=arguments[0],R=D.cellSize,O=D.margin,P=D.alt,U=D.title),R=R||2,O=typeof O>"u"?R*4:O,P=typeof P==Line truncated
|
||||
`}return P%2&&R>0?Be.substring(0,Be.length-P-1)+Array(P+1).join("▀"):Be.substring(0,Be.length-1)};return I.createASCII=function(R,O){if(R=R||1,R<2)return ve(O);R-=1,O=typeof O>"u"?R*2:O;var P=I.getModuleCount()*R+O*2,U=O,D=P-O,G,ee,X,be,Le=Array(R+1).join("██"),re=Array(R+1).join(" "),Ie="",Be="";for(G=0;G<P;G+=1){for(X=Math.floor((G-U)/R),Be="",ee=0;ee<P;ee+=1)be=1,U<=ee&&ee<D&&U<=G&&G<D&&I.isDark(X,Math.floor((ee-U)/R))&&(be=0),Be+=be?Le:re;for(X=0;X<R;X+=1)Ie+=Be+`
|
||||
`}return Ie.substring(0,Ie.length-1)},I.renderTo2dContext=function(R,O){O=O||2;for(var P=I.getModuleCount(),U=0;U<P;U++)for(var D=0;D<P;D++)R.fillStyle=I.isDark(U,D)?"black":"white",R.fillRect(U*O,D*O,O,O)},I};n.stringToBytesFuncs={default:function(S){for(var $=[],b=0;b<S.length;b+=1){var C=S.charCodeAt(b);$.push(C&255)}return $}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(S,$){var b=(function(){for(var w=h(S),z=function(){var B=w.read();if(B==-1)throw"eof";return B},y=0,f={};;){var x=w.read();if(x==-1)break;var T=z(),I=z(),Y=z(),J=String.fromCharCode(x<<8|T),te=I<<8|Y;f[J]=te,y+=1}if(y!=$)throw y+" != "+$;return f})(),C=63;return function(w){for(var z=[],y=0;y<w.length;y+=1){var f=w.charCodeAt(y);if(f<128)z.push(f);else{var x=b[w.charAt(y)];typeof x=="number"?(x&255)==x?z.push(x):(z.push(x>>>8),z.push(x&255)):z.push(C)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var S=[[],[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]],$=1335,b=7973,C=21522,w={},z=function(y){for(var f=0;y!=0;)f+=1,y>>>=1;return f};return w.getBCHTypeInfo=function(y){for(var f=y<<10;z(f)-z($)>=0;)f^=$<<z(f)-z($);return(y<<10|f)^C},w.getBCHTypeNumber=function(y){for(var f=y<<12;z(f)-z(b)>=0;)f^=b<<z(f)-z(b);return y<<12|f},w.getPatternPosition=function(y){return S[y-1]},w.getMaskFunction=function(y){switch(y){case s.PATTERN000:return function(f,x){return(f+x)%2==0};case s.PATTERN001:return function(f,x){return f%2==0};case s.PATTERN010:return function(f,x){return x%3==0};case s.PATTERN011:return function(f,x){return(f+x)%3==0};case s.PATTERN100:return function(f,x){return(Math.floor(f/2)+Math.floor(x/3))%2==0};case s.PATTERN101:return function(f,x){return f*x%2+f*x%3==0};case s.PATTERN110:return function(f,x){return(f*x%2+f*x%3)%2==0};case s.PATTERN111:return function(f,x){return(f*x%3+(f+x)%2)%2==0};default:throw"bad maskPattern:"+y}},w.getErrorCorrectPolynomial=function(y){for(var f=i([1],0),x=0;x<y;x+=1)f=f.multiply(i([1,a.gexp(x)],0));return f},w.getLengthInBits=function(y,f){if(1<=f&&f<10)switch(y){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:"+y}else if(f<27)switch(y){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:"+y}else if(f<41)switch(y){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:"+y}else throw"type:"+f},w.getLostPoint=function(y){for(var f=y.getModuleCount(),x=0,T=0;T<f;T+=1)for(var I=0;I<f;I+=1){for(var Y=0,J=y.isDark(T,I),te=-1;te<=1;te+=1)if(!(T+te<0||f<=T+te))for(var B=-1;B<=1;B+=1)I+B<0||f<=I+B||te==0&&B==0||J==y.isDark(T+te,I+B)&&(Y+=1);Y>5&&(x+=3+Y-5)}for(var T=0;T<f-1;T+=1)for(var I=0;I<f-1;I+=1){var Q=0;y.isDark(T,I)&&(Q+=1),y.isDark(T+1,I)&&(Q+=1),y.isDark(T,I+1)&&(Q+=1),y.isDark(T+1,I+1)&&(Q+=1),(Q==0||Q==4)&&(x+=3)}for(var T=0;T<f;T+=1)for(var I=0;I<f-6;I+=1)y.isDark(T,I)&&!y.isDark(T,I+1)&&y.isDark(T,I+2)&&y.isDark(T,I+3)&&y.isDark(T,I+4)&&!y.isDark(T,I+5)&&y.isDark(T,I+6)&&(x+=40);for(var I=0;I<f;I+=1)for(var T=0;T<f-6;T+=1)y.isDark(T,I)&&!y.isDark(T+1,I)&&y.isDark(T+2,I)&&y.isDark(T+3,I)&&y.isDark(T+4,I)&&!y.isDark(T+5,I)&&y.isDark(T+6,I)&&(x+=40);for(var ne=0,I=0;I<f;I+=1)for(var T=0;T<f;T+=1)y.isDark(T,I)&&(ne+=1);var fe=Math.abs(100*ne/f/f-50)/5;return x+=fe*10,x},w})(),a=(function(){for(var S=new Array(256),$=new Array(256),b=0;b<8;b+=1)S[b]=1<<b;for(var b=8;b<256;b+=1)S[b]=S[b-4]^S[b-5]^S[b-6]^S[b-8];for(var b=0;b<255;b+=1)$[S[b]]=b;var C={};return C.glog=function(w){if(w<1)throw"glog("+w+")";return $[w]},C.gexp=function(w){for(;w<0;)w+=255;for(;w>=256;)w-=255;return S[w]},C})();function i(S,$){if(typeof S.length>"u")throw S.length+"/"+$;var b=(function(){for(var w=0;w<S.length&&S[w]==0;)w+=1;for(var z=new Array(S.length-w+$),y=0;y<S.length-w;y+=1)z[y]=S[y+w];return z})(),C={};return C.getAt=function(w){return b[w]},C.getLength=function(){return b.length},C.multiply=function(w){for(var z=new Array(C.getLength()+w.getLength()-1),y=0;y<C.getLength();y+=1)for(var f=0;f<w.getLength();f+=1)z[y+f]^=a.gexp(a.glog(C.getAt(y))+a.glog(w.getAt(f)));return i(z,0)},C.mod=function(w){if(C
Line truncated
|
||||
`)}function hi(n){let e=new Map(n.people.map(s=>[s.id,s.name])),o=new Map(n.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Qe(n,e,o,s="",r=[]){let a=hi(n),i=[...e.map(u=>({ts:u.ts,category:qt(u.type),type:u.type,person:u.person?a.people.get(u.person)??u.pname??u.person:"",device:u.device?a.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?`
|
||||
${u.detail}`:""}`,where:Ft(u.src),by:""}))].sort((u,k)=>u.ts-k.ts).map(({ts:u,...k})=>({time:new Date(u*1e3).toISOString(),...k})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ne(d,JSON.stringify(i,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ne(d,Ss(c,i,p),"text/csv")}var fi=["","7","30","90"],gi=n=>n?W(Number(n),"Older than %s day","Older than %s days"):_("Everything"),Ps=n=>n?W(n,"%s event removed","%s events removed"):_("Nothing matched");function lt(n,e,o,s,r,a=!1){let i=t("select",{class:"cbi-input-select"},[t("option",{value:""},_("All categories")),...Nt.map(d=>t("option",{value:d,selected:d===r?"selected":null},Ye(d))),a?t("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=t("select",{class:"cbi-input-select"},fi.map(d=>t("option",{value:d},gi(d))));de(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")),i]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Which events")),l])],[ue()," ",A(_("Clear"),async()=>{let d=0;if(i.value!=="system")try{d+=(await N.logsClear({...o,category:i.value,older_days:l.value})).removed}catch(c){q(Ce(c),"error",1e4);return}if(a&&(i.value==="system"||i.value===""))try{d+=(await N.serviceLogClear(l.value)).removed}catch(c){ce();let p=m(_("The service log was not cleared: %s"),Ce(c));q(i.value==="system"?p:`${m(_("Activity: %s."),Ps(d).toLowerCase())} ${p}`,"error",1e4),s();return}ce(),q(Ps(d),"success",3e3),s()},"negative")])}function Ht(n,e,o,s){let r=n==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):n==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");de(n==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[t("p",{class:"dl-muted"},r)],[ue()," ",A(_("Reset"),async()=>{await F(()=>N.usageClear(n,e),_("Traffic history reset"))&&(ce(),s())},"negative")])}function ye(n,e,o){let s=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!s.classList.contains("on");uo(s,r),o?.(r)}},t("i"));return s}function uo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var ze=n=>n.classList.contains("on");function Me(n,e,o={}){n.some(([a])=>a===e)||(n=[...n,[e,e]]);let s=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>s.querySelectorAll(":scope > button").forEach(a=>{let i=a.dataset.v===s.dataset.value;a.classList.toggle("on",i),a.setAttribute("aria-checked",i?"true":"false")});for(let[a,i]of n)s.appendChild(t("button",{type:"button",role:"radio","data-v":a,click:()=>{a!==s.dataset.value&&(o.optimistic!==!1&&(s.dataset.value=a,r()),o.onChange?.(a))}},i));return r(),s}function Xe(n,e,o,s={}){return t("button",{type:"button",...s,class:`dl-chipbtn${e?" on":""}${s.class?` ${s.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function xn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function he(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var vi={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},bi={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 xi(n){let e={};for(let[o,s]of Object.entries(bi))n[o]!=null&&n[o]!==""&&(e[s]=String(n[o]));return e}function wi(n,e){let o=n.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):vi[d],a=o.host.replace(/^\[(.*)\]$/,"$1"),i={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"),...xi(s),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:a,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(i),port:String(o.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function yi(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 ki(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(s,4),r}catch{return null}}async function mo(n,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(wi(n,e))),r=o?await ki(s):null;return`vpn://${yi(r??s)}`}function Ds(){return[{id:"off",title:_("Off"),ic:"zap",stealth:0,speed:4,text:_("Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block."),apps:_("Any WireGuard app"),short:_("Any WireGuard app")},{id:"balanced",title:_("Balanced"),ic:"shield",stealth:3,speed:4,needs:"v2",text:_("AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk."),apps:_("AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps"),short:_("AmneziaWG 2.0+ apps")},{id:"max",title:_("Maximum"),ic:"lock",stealth:4,speed:3,needs:"v3",text:_("AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS."),apps:_("Apps with AmneziaWG 3.1 (current AmneziaVPN)"),short:_("AmneziaWG 3.1 apps")}]}var Kt=n=>Ds().find(e=>e.id===n),wn=n=>n.v3?"max":n.v2?"balanced":"off",Yt=n=>n==="standard"?_("Standard (old)"):n==="strong"?_("Strong (old)"):null;function _i(n,e){return e?n==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):n==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function $s(n,e){return t("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,n)},[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 yn(n,e,o,s,r=!0){let a=t("div",{class:"dl-methods",role:"radiogroup","aria-label":_("Disguise method")}),i=()=>dom.content(a,Ds().map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,i(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===s?t("span",{class:"dl-pill ok"},_("Current")):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[$s(l.stealth,_("Stealth")),$s(l.speed,_("Speed"))]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},_i(l.needs,r))])])}));return i(),a}function As(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Ns=[["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 Ci(n){let e=c=>n[c]!=null&&n[c]!=="",o=Ns.filter(([c])=>e(c));if(!o.length)return null;let s=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),r=(c,p,u,k)=>{let M=Ns.filter(([g])=>k.includes(g)&&e(g));return M.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},M.map(([g,h])=>s(g,h)))]):""},a=Number(n.jc||0),i=(n.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),l=o.map(([c,p])=>`${p} = ${n[c]}`).join(`
|
||||
`),d=t("div",{class:"dl-pgrid"},[r(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),K(a),n.jmin,n.jmax):_("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",i,["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:c=>{c.preventDefault(),xe(l,_("Parameters copied"))}},_("Copy as config"))]),d])}function Hs(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 s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",s&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Li(n){let e=!1,o=t("pre",{class:"dl-conf"}),s=()=>dom.content(o,n.conf.split(`
|
||||
`).flatMap((i,l)=>l?[`
|
||||
`,Hs(i,e)]:[Hs(i,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("key"),_("Show key")]);s();let a=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 · ${W(a,"%s byte","%s bytes")}`)]),A([v("download")," ",_("Download")],()=>Ne(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:i=>{i.preventDefault(),xe(n.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function ho(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function Mi(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 mo(n,n.server),s={qr:()=>t("div",{class:"dl-qr-pane"},[un(n.conf),t("span",{class:"dl-sub"},ho(n)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),A(_("Copy"),()=>xe(o,_("Key copied")))]),t("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>Li(n)},r=t("div",{class:"dl-connect-body"}),a=t("div",{class:"dl-seg"}),i=l=>{a.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])a.appendChild(t("button",{type:"button","data-id":l,click:()=>i(l)},d));return i(e),t("div",{class:"dl-stack gap12"},[a,r])}async function Ei(n,e,o,s){let r=Kt(o),i=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await me(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[W(i,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices 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."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",n.st.servers.length===1&&i?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await F(()=>N.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(q(_("Devices are marked “Update config” until they import again."),"info",6e3),await n.refresh())}function Ti(n,e){let o=n.st,s=he(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=he(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=he(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=Kt(e.preset)?e.preset:void 0,l=i??wn(o.awg),d=A("",()=>Ei(n,e,l,l===i),"neutral"),c=()=>dom.content(d,l===i?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Kt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],k=_e(_("UDP port"),s,()=>Gt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));N.serverPorts(e.id).then(h=>{u=h.udp_taken??[],k.refresh()}).catch(()=>{});let M=_e("MTU",r,()=>ps(r.value,e.mtus)),g=_e(_("Keep-alive"),a,()=>us(a.value));return Wt("",[As("AmneziaWG",e.ifname),ke("globe",_("Listening"),_("Where devices reach this core from the internet"),[k]),ke("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,g]),ke("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[Yt(e.preset)?bt("warn",ae(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),t("b",{},Yt(e.preset)),t("b",{},_("Balanced")),t("b",{},_("Maximum")))):"",yn(o.awg,l,h=>{l=h,c()},i,p),p&&!o.awg.v3?bt("info",ae(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),t("b",{},_("Maximum")))):"",Ci(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},_("Applies at once: every AmneziaWG device imports its configuration again.")),d])]),t("deta
Line truncated
|
||||
`),_("Log copied")))]),p,u]),[k],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let E=o??null,H=o?.id,S,$=0,b=x=>{H!==x.id&&(H=x.id,e.onJob?.(x))};if(o)e.onJob?.(o);else try{let x=await N.updatesStatus().catch(()=>null);S=x?.job?.id,$=x?.now??0;let T=await N.updatesRun(n);T.job&&T.job.state==="running"&&T.job.id!==S&&(E=T.job,b(T.job))}catch(x){return M=[Ce(x)],p.textContent=M[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},Ce(x))])),g([h(!0)]),q(Ce(x),"error"),null}let C=null,w=0;for(;;){if(await $o(1e3),C=await N.updatesStatus().catch(()=>null),!C){if(++w>60)break;continue}w=0;let x=C.job;if(!x||!Lr(x,H,S,$)){if(Date.now()-a>15e3)break;continue}if(b(x),E=x,x.log.length){M=x.log;let T=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(`
|
||||
`),T&&(p.scrollTop=p.scrollHeight)}if(l.textContent=_r(x,e.version??""),!l.isConnected&&l.textContent&&i.after(l),c.textContent=kr((x.finished??C.now)-x.started),x.state==="running"){d.hidden=!x.phase,d.textContent=x.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),g([h()]),e.onDone?.(C),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},(E.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),g([A(_("Copy log"),()=>xe(M.join(`
|
||||
`),_("Log copied"))),h(!0)]),q(`${Dn(s)??_("Update","noun")}: ${E.error??_("failed")}`,"error"),e.onDone?.(C),E;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&C){let x=Cr(C,s);if(dom.content(u,t("div",{class:`dl-comp-status ${x.tone}`},[v(x.tone==="ok"?"check":x.tone==="warn"?"alert":"download"),t("span",{},x.text)])),q(x.text,x.tone==="warn"?"warning":"success"),e.onDone?.(C),x.update&&e.onUpdate){let T=C;g([h(),A(m(_("Update to %s"),x.update),()=>e.onUpdate(T),"positive")])}else g([h()]),x.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return E}let z=/^app:(lang:|nolang$)/.exec(E.component??"");if(z){let x=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},z[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),g([h(),A(_("Reload now"),x,"positive")]),await $o(4e3),u.isConnected&&x(),E}if(s==="app"&&E.to){let x=E.to,T=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",{},m(_("Dawnline %s is installed."),x))," ",T])]));let I=()=>{ui.menu?.flushCache(),location.reload()};g([h(),A(_("Reload now"),I,"positive")]),q(m(_("Dawnline updated to %s"),x),"success",6e3);for(let Y=1;Y<=30;Y++)if(T.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),Y),await $o(1500),(await N.updatesStatus().catch(()=>null))?.version===x)return T.textContent=_("Services are back. Reloading…"),setTimeout(I,800),E;return T.textContent=_("Services restarted. Reload the page to use the new version."),E}let y=[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]],f=s==="pkgs"?y.length?m(_("Updated %s"),y.join(", ")):_("Updated system packages"):s==="amneziawg"?E.to?m(_("AmneziaWG %s is installed"),E.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},f)])),g([h()]),q(f,"success"),e.onDone?.(C),E}function el(n){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[n]}async function Mr(n,e,o,s){let[r,a]=el(e);return!await me(r,o,_("Install"))||(await tn(n,{title:a}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function Nn(n){return Mr("amneziawg:auto","awg",_("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 nn(n,e,o){return n==="awg"?Nn(o):e.length?Mr(`pkgs:${e.join(",")}`,n,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function Er(n,e){if(n==="awg")return Nn(e);let o=await F(()=>N.updatesStatus());return o?nn(n,o.needs?.[n]??[],e):!1}var tl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],nl={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Tr(n,e,o){let s=n.id,r=e,a=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},_("Loading interfaces…"))))),i,l=!0,d="",c=!0,p=!0,u="all",k=!1,M=xr(r,s,o),g=new Set,h="",E=()=>JSON.stringify([p,l,l?"":d,c,[...g].sort()]),H=()=>i.detected.lan||i.saved.lan||"",S=()=>(l?i.detected.wan||i.saved.wan:d)||"",$=()=>new Map(i.devices.map(B=>[B.name,B])),b=()=>{let B=$();return[...c&&H()?[H()]:[],...[...g].filter(ne=>ne!==H())].filter(ne=>ne!==S()).map(ne=>B.get(ne)??{name:ne,nets:[],missing:!0})},C=(B,Q)=>{i=B,Q&&(l=B.config.auto_wan,d=B.config.wan_device||B.detected.wan||B.saved.wan||"",c=B.config.auto_lan,p=B.config.lan_like,u=B.config.mesh??(B.config.device_mesh?"all":"off"),g=new Set(B.config.lan_devices),h=E()),J()},w=async B=>{let Q=await N.interfaces(s).catch(ne=>(q(ne.message,"error"),null));Q&&C(Q,B)};function z(B){let Q=c&&B.name===H(),ne=!!B.own||!!B.master||B.name===S()||Q;return Q||g.has(B.name)||!ne&&(B.nets.length>0||!!B.missing)}function y(B){let Q=c&&B.name===H(),ne=B.name===S(),fe=!Q&&g.has(B.name),j=!(!!B.own||!!B.master||ne||Q)&&(B.nets.length>0||fe||!!B.missing),V=(fe||Q)&&!B.zone&&!B.missing,le=B.missing?_("Not present right now"):B.own?_("This server"):B.master?m(_("Port of %s"),B.master):ne?`${_("Internet")}${B.zone?` · ${m(_("zone %s"),B.zone)}`:""}`:B.nets.length?B.nets.join(", "):_("No IPv4 network"),ve=t("button",{type:"button",class:`dl-if${fe?" sel":""}${Q?" auto":""}${!j&&!fe&&!Q?" off":""}${V?" warn":""}`,"aria-pressed":fe||Q?"true":"false","aria-disabled":j?null:"true",click:()=>{j&&(g.has(B.name)?g.delete(B.name):g.add(B.name),J())}},[t("span",{class:"dl-if-ic"},v(nl[B.kind]??"link")),t(
Line truncated
|
||||
`).map(e=>At(e)).join(`
|
||||
`);function Hn(n,e,o,s){let r=n.by==="admin",a=At(n.msg),i=t("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${dl[n.level]??""}`}${n.detail?" has-detail":""}`},[r?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):t("span",{class:"dl-ev-tile sys",title:pl(n.level)},v(cl[n.src]??"zap")),t("span",{class:"dl-row-main"},r?[...ul(n),n.note?t("span",{class:"dl-muted"},` · ${Ms(n.note)}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},`${_("Server")} `):"",t("b",{class:"dl-sys-src",title:Ft(n.src)},n.who?n.src==="awg"?n.who:At(n.who):Ft(n.src)),/^[:,]/.test(a)?"":" ",t("span",{class:"dl-muted"},a),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]),t("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString(ie())},s)]);return n.detail&&i.addEventListener("click",l=>{l.target.closest("pre")||o()}),i}function Pr(n){let e=new Date(n*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(ie(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(ie())+r.slice(1)}var Ot=n=>Mt(n).toLocaleDateString(ie(),{day:"numeric",month:"short"});function zn(n,e,o,s=!1){let r=n.slice(-15),a=r[r.length-1],i=a&&e-a[0]<180,l=i?a[2]:0,d=i?a[1]:0,[c,p]=o,u=200,k=40,M=Math.max(1,...r.map($=>Math.max($[1],$[2]))),g=$=>r.map((b,C)=>`${r.length>1?C/(r.length-1)*u:u},${k-2-b[$]/M*(k-6)}`),h=g(2),E=g(1),H=r.length>1&&!s?Tt(`<svg viewBox="0 0 ${u} ${k}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path d="M${h.join(" L")} L${u},${k} L0,${k}Z" class="area"/><path d="M${h.join(" L")}" class="line"/><path d="M${E.join(" L")}" class="line up"/></svg>`):t("div",{class:"dl-speed-wait"},[t("i"),s?"":t("span",{},_("Collecting… 1 point a minute"))]),S=($,b,C,w)=>t("div",{class:"dl-speed-col"},[t("span",{class:"dl-sub"},[t("span",{class:C},b),` ${$}`]),s?t("span",{class:"dl-speed-val off"},"—"):t("span",{class:"dl-speed-val"},Fe(w))]);return r.length>1&&!s&&we(H,()=>{let $=r[r.length-1];return[t("div",{class:"dl-tip-title"},new Date($[0]*1e3).toLocaleTimeString(ie(),{hour:"2-digit",minute:"2-digit"})),t("div",{},`↓ ${Fe($[2])} · ↑ ${Fe($[1])}`)]}),t("div",{class:"dl-bento-tile"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},_("Speed now")),s?"":t("span",{class:"dl-sub"},_("last 15 min"))]),t("div",{class:"dl-speed-cols"},[S(_("Download","speed"),"↓","dl-dn",l),S(_("Upload","speed"),"↑","dl-up",d)]),H,t("div",{class:"dl-speed-today"},[t("span",{},ae(_("Today %s"),t("b",{},oe(c+p)))),t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${oe(p)} `,t("span",{class:"dl-up"},"↑"),` ${oe(c)}`])])])}function Rn(n,e){let o=n.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),a=s.reduce((d,c)=>d+c,0),i=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=t("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=t("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`});return we(u,()=>[t("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${Ot(d.day)}`:Ot(d.day)),t("div",{},oe(p)),t("div",{class:"dl-muted dl-mono"},`↓ ${oe(d.tx)} ↑ ${oe(d.rx)}`)]),u}));return t("div",{class:"dl-bento-tile month"},[t("div",{class:"dl-bento-head"},[t("span",{},[t("span",{class:"dl-metric-label"},_("Last 30 days")),t("b",{class:"dl-bento-total"},oe(a))]),s[i]>0?t("span",{class:"dl-sub"},`${m(_("peak %s"),oe(s[i]))} · ${Ot(o[i].day)}`):""]),o.length?l:t("p",{class:"dl-muted"},_("No traffic yet.")),t("div",{class:"dl-bento-head"},[t("span",{class:"dl-sub"},o.length?Ot(o[0].day):""),t("span",{class:"dl-sub"},e),t("span",{class:"dl-sub"},_("today"))])])}function $r(n){let e=n.slice(-30),o=e.map(r=>r.rx+r.tx),s=Math.max(1,...o);return t("div",{class:"dl-dbars"},e.map((r,a)=>{let i=t("i",{class:`${o[a]?"":"zero"}${a===e.length-1?" hi":""}`});return i.style.height=`${Math.max(8,o[a]/s*100)}%`,we(i,()=>[t("div",{class:"dl-tip-title"},a===e.length-1?`${_("Today")} · ${Ot(r.day)}`:Ot(r.day)),t("div",{},oe(o[a]))]),i}))}function Dr(n){return{apply:_("Repair"),sync:_("Reload devices"),restart:_("Restart service"),netrestart:_("Restart network"),updates:_("Open Components")}[n]??_("Fix")}async function In(n){return n==="netrestart"&&!await me(_("Restart the network?"),_("Every interface restarts. Connections drop for a few seconds."),_("Restart network"))?null:await F(()=>N.healthFix(n),_("Done"))??null}function Ao(n,e,o,s="action"){let r=n.fix;return r?r.startsWith("install:")?A(_("Install"),()=>Er(r.slice(8),o),s):r==="updates"?t("a",{class:`cbi-button cbi-button-${s}`,href:L.url("admin/network/dawnline/updates")},Dr(r)):A(Dr(r),()=>e(r),s):""}fuLine truncated
|
||||
`)){let d=l.trimEnd();if(a){/^```/.test(d.trim())?(e.push(t("pre",{},a.join(`
|
||||
`))),a=null):a.push(l);continue}if(/^```/.test(d.trim())){i(),a=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(i(),e.push(t("h5",{},o(c[2])))):p?(r.length&&i(),s||(s=t("ul",{}),e.push(s)),s.appendChild(t("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):i()}return a&&e.push(t("pre",{},a.join(`
|
||||
`))),i(),e}function Kr(n){let e=[],o=!1;for(let s of n.replace(/\r/g,"").split(`
|
||||
`)){let r=/^#{1,6}\s+(.*)$/.exec(s);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(s)&&(o=!1);o||e.push(s)}return e.join(`
|
||||
`).replace(/\n{3,}/g,`
|
||||
|
||||
`).trim()}async function sn(n,e,o,s){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),a=t("div",{class:"dl-op-head"}),i="";de(o,[a,r],[A([v("copy")," ",_("Copy")],()=>xe(i,_("Release notes copied")))," ",ue(_("Close"))],"wide");try{let l=await N.updatesNotes(n,e,s??"");i=Kr(l.body||"");let d=qr(l.url);dom.content(a,[l.published?t("span",{class:"dl-pill"},Oe(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},_("Pre-release")):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",v("open")]):""]),dom.content(r,i.trim()?Fr(i):t("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,t("p",{class:"dl-muted"},Ce(l)))}}function yl(n){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[n]??e["1d"]}var Ro=n=>n?Oe(n):"";function kl(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Vr(n,e){let o=n.st,s=o.policy,r=o.kept?.app,a=e?.update&&e.tag?e.tag:o.version,i=k=>()=>sn("app",k,m(_("What’s new in Dawnline %s"),k.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?_l(n,e.tag,e.update?o.version:""):null,d=e?.tag??a,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(k,M)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},k),t("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:i(a)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>n.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("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"},m(_("release %s"),e.latest)):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),Ro(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),Ro(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(k=>t("li",{},k))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:i(d)},W(l.total-l.items.length,"+%s more in What’s new","+%s 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"},[A(_("Update now"),()=>n.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:n.busy}),A(_("What’s new"),i(a))]):"",Ll(n),Cl(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"),[s.auto?Pe("ok",_("On")):Pe("",_("Off")),t("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?yl(s.interval):_("checks off"))]),p(_("Last check"),o.check?[pe(o.check.time,o.now),c>o.now?t("span",{class:"dl-faint"},`· ${m(_("next in %s"),ot(c-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"},s.keep?_("Kept after the next update"):_("Off"))])])])}function _l(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(a,i)=>i??"").trim();return(async()=>{let a=((await N.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);a.length||(a=(await N.updatesChanges(o,e).catch(()=>null))?.items??[]);let i={items:a.slice(0,3).map(l=>kl(s(l))),total:a.length};n.notes.set(e,i),i.items.length&&n.root.isConnected&&n.paint()})(),null}function jn(n){return n==="ru"?_("Russian translation"):n}function Cl(n){let e=(n.st.translations??[]).includes("ru"),o=ye(e,jn("ru"),r=>{n.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),n.st.version)});o.disabled=n.busy;let s=t("details",{class:"dl-params dl-comp-fold",open:n.langOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},_("Translation")),t("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),t("div",{class:"dl-params-body"},[t("div",{class:"dl-list"},[t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},jn("ru")),t("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),t("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>n.langOpen=s.open),s}function Ll(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&&Un(n,e)}),n.versOpen&&Un(n,e),o}async function Un(n,e){let o=he("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return q(_("Enter a release tag like 0.3.1"),"warning");Yr(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,A(_("Install"),()=>s(o.value),"neutral",{disabled:n.busy})]),a=n.versPage,i=p=>{n.versPage=Math.max(1,n.versPage+p),Un(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:a<=1?"disabled":null,click:()=>i(-1)},_("← Newer")),t("span",{class:"dl-faint"},m(_("Page %s"),a)),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>i(1)},_("Older →"))]),d=n.versCache.get(a);if(!d){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await N.updatesReleases(a)).releases}catch(p){if(a!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),Ce(p))),A(_("Try again"),()=>Un(n,e))]),l(!1)]);return}if(n.versCache.set(a,d),a!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,t("p",{class:"dl-muted"},a>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=n.st.version;dom.content(e,[r,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Ro(p.published)),p.prerelease?Pe("warn",_("Pre-release")):"",t("span",{class:"dl-comp-ic"},$e("file",_("What’s new"),()=>sn("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Pe("ok",_("Installed")):A(_("Install"),()=>Yr(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Yr(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await me(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),n.st.version),_("Install"))||n.op(`app@${e}`,m(_("Installing Dawnline %s"),o),n.st.version)}function Jr(n,e){let o=n.st,s=o.kept?.amneziawg,r=e?.sources??{},a=Object.keys(r),i=e?.current??null,l=i?r[i]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];i&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${i}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back AmneziaWG to %s?"),s.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 k=[e?.release?{label:_("What’s new"),ic:"file",run:()=>sn("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),i??"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((y,f,x)=>y!==null||f>0&&x[f-1]!==null),M=o.tunnels??[],g=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),K(M.length),M.join(", ")):_("Switching takes a few
Line truncated
|
||||
`)}r.push(p),l+=c-1}let i=A([v("more")],()=>Se(i,[{label:_("Export CSV"),icon:v("download"),run:()=>Qe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Qe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("trash"),danger:!0,run:()=>lt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{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"},s.length>10?m(_("latest 10 of %s"),K(s.length)):""),t("span",{class:"dl-spacer"}),i]),r.length?r:t("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var Gn=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,s,r]=await Promise.all([N.status(30),e?N.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?N.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.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(i=>i.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 i of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[i]=t("div",{});this.parts.devices.className="dl-person-devices";let s=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),a=r.get("device")&&o.devices.find(i=>i.id===r.get("device"));return a?setTimeout(()=>Je(this.p,a,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ct(this.p,this.deviceOpts()),50),this.poller=pt({fetch:i=>{let l=i||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(i,l)=>this.apply(i,l)}),s}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 s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=It(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var a;this.poller?.claim();let s=await F(()=>N.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(i=>i.id===this.p.id);return(a=s.person).rate??(a.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return Ge(this.series.length?this.series:this.st.series)}get core(){return zt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[t("a",{href:It(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),t("span",{},"/"),t("a",{href:It(e.server)},_("People")),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Ae(this.parts.crumbs,this.crumbs(),e),Ae(this.parts.head,aa(this),e),Ae(this.parts.traffic,ia(this),e),Ae(this.parts.devices,la(this),e),Ae(this.parts.limits,fa(this),e),this.paintPlaces(e),Ae(this.parts.activity,va(this),e)}paintPlaces(e=!1){let o=ga(this);o&&Ae(this.parts.places,o,e&&!this.mapOpen)}};var zl={ok:"check",warn:"alert",error:"x",skip:"pause"},qn=class{constructor(e,o,s,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=s,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,s)}async run(e){let o=e?await In(e):await N.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(i=>i.status==="error").length,s=e.filter(i=>i.status==="warn").length;dom.content(this.summary,o?bt("error",W
Line truncated
|
||||
`);function Aa(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=td,n}function yt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),a=document.createElement("div");return a.className="dl-root",a.append(Aa(),r),a},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Jb=yt(on),Zb=yt(wt),Qb=yt(on),Xb=yt(On),e0=yt(Gn),t0=yt(Yn),n0=yt(Wn);function Na(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 o0=Na(""),s0=Na("log");return baseclass.extend({ activity: s0, diagnostics: t0, health: o0, overview: Jb, people: Zb, person: e0, server: Qb, settings: Xb, updates: n0 });
|
||||
@@ -101,6 +101,20 @@ msgstr "%s - %s"
|
||||
msgid "%s - not repaired again (%d repairs didn't help)"
|
||||
msgstr "%s - больше не исправляется (исправления не помогли: %d)"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record."
|
||||
msgid_plural "%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records."
|
||||
msgstr[0] "%s AAAA → %s: это не публичный адрес роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эту запись AAAA."
|
||||
msgstr[1] "%s AAAA → %s: это не публичные адреса роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эти записи AAAA."
|
||||
msgstr[2] "%s AAAA → %s: это не публичные адреса роутера, поэтому устройства, которые предпочитают IPv6, не смогут подключиться. Исправьте или удалите эти записи AAAA."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router."
|
||||
msgid_plural "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router."
|
||||
msgstr[0] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эту запись AAAA или настройте IPv6 на роутере."
|
||||
msgstr[1] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эти записи AAAA или настройте IPv6 на роутере."
|
||||
msgstr[2] "%s AAAA → %s, но у роутера нет публичного IPv6-адреса: устройства, которые предпочитают IPv6, не смогут подключиться. Удалите эти записи AAAA или настройте IPv6 на роутере."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you)."
|
||||
msgid_plural "%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."
|
||||
@@ -158,6 +172,10 @@ msgstr "%s и %s"
|
||||
msgid "%s and %s are not in one circle"
|
||||
msgstr "%s и %s не в одном круге"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s and %s overlap: each packet type needs values of its own."
|
||||
msgstr "%s и %s пересекаются: у каждого типа пакетов должны быть свои значения."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s applied"
|
||||
msgstr "Маскировка «%s» применена"
|
||||
@@ -446,6 +464,10 @@ msgstr "%s: доступ «Только интернет»."
|
||||
msgid "%s has Internet only: only DNS and the portal on the router."
|
||||
msgstr "%s: доступ «Только интернет», на роутере доступны только DNS и портал."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has a tag that is not closed with >."
|
||||
msgstr "%s: тег не закрыт символом >."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has an invalid interface name \"%s\"."
|
||||
msgstr "У сервера %s недопустимое имя интерфейса «%s»."
|
||||
@@ -550,6 +572,10 @@ msgstr "%s теперь без круга"
|
||||
msgid "%s is kept down."
|
||||
msgstr "Сервер %s остановлен."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s"
|
||||
msgstr "Сервер %s остановлен: в его маскировке есть значения, которые AmneziaWG не примет. %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)."
|
||||
msgstr "Сервер %s остановлен: для его маскировки нужен AmneziaWG %s (установлен %s)."
|
||||
@@ -569,6 +595,10 @@ msgstr[2] "Не установлено: %s."
|
||||
msgid "%s is not a bridge, so Dawnline cannot join the LAN as a device."
|
||||
msgstr "%s - не мост, поэтому Dawnline не может подключиться к LAN как устройство."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is not a common home subnet: the networks people connect from rarely use the same addresses."
|
||||
msgstr "%s: не самая частая домашняя подсеть: сети, из которых подключаются люди, редко используют те же адреса."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc
|
||||
msgid "%s is not a package Dawnline manages"
|
||||
@@ -602,6 +632,10 @@ msgstr "%s на другом сервере"
|
||||
msgid "%s is on the internet"
|
||||
msgstr "%s в интернете"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24."
|
||||
msgstr "%s: одна из самых распространённых домашних подсетей. В сети с такими же адресами люди с доступом к дому попадают к вам домой, а не в свою сеть: их принтер или телевизор там недоступен, пока они подключены, даже с обходом локальной сети. Это исправит более редкая подсеть для вашей домашней сети, например 10.37.12.0/24."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "%s is part of %s; choose %s instead."
|
||||
msgstr "%s входит в %s, выберите %s."
|
||||
@@ -658,6 +692,10 @@ msgstr[2] "%s пакетов мусора"
|
||||
msgid "%s left"
|
||||
msgstr "осталось %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s may not contain # or a line break."
|
||||
msgstr "%s не может содержать # или перенос строки."
|
||||
|
||||
#: web/src/shared/format.ts
|
||||
msgid "%s min ago"
|
||||
msgstr "%s мин назад"
|
||||
@@ -678,8 +716,32 @@ msgid "%s moves to %s with OpenWrt %s."
|
||||
msgstr "Сборка %s перейдёт на AmneziaWG %s с OpenWrt %s."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or range"
|
||||
msgstr "%s: нужно число или диапазон"
|
||||
msgid "%s must be a number or a range like 10-100, up to 65535."
|
||||
msgstr "%s: нужно число или диапазон вида 10-100, не больше 65535."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 100-200, up to 4294967295."
|
||||
msgstr "%s: нужно число или диапазон вида 100-200, не больше 4294967295."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 5-15, from 1 to 65535."
|
||||
msgstr "%s: нужно число или диапазон вида 5-15, от 1 до 65535."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a whole number from 0 to 65535."
|
||||
msgstr "%s: нужно целое число от 0 до 65535."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be at least 12 with header protection."
|
||||
msgstr "%s: с защитой заголовков нужно не меньше 12."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be from %d to %d."
|
||||
msgstr "%s: от %d до %d."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be on or off."
|
||||
msgstr "%s: нужно on или off."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
msgid "%s needs a manual switch in Components"
|
||||
@@ -846,6 +908,10 @@ msgstr[2] "%s исправлений сегодня, последнее - %s в
|
||||
msgid "%s resumed"
|
||||
msgstr "%s: доступ возобновлён"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "%s s"
|
||||
msgstr "%s с"
|
||||
|
||||
#: web/src/admin/pages/settings/logs.ts
|
||||
msgid "%s since %s"
|
||||
msgstr "%s с %s"
|
||||
@@ -928,6 +994,10 @@ msgstr[0] "%s год"
|
||||
msgstr[1] "%s года"
|
||||
msgstr[2] "%s лет"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · interface settings"
|
||||
msgstr "%s · настройки интерфейса"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · restored"
|
||||
msgstr "%s · восстановлено"
|
||||
@@ -944,6 +1014,17 @@ msgstr "%s → %s (Cloudflare). %s дойдёт до роутера, тольк
|
||||
msgid "%s → %s (this router)."
|
||||
msgstr "%s → %s (этот роутер)."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgid_plural "%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgstr[0] "%s → %s: только IPv6, и это не публичный адрес роутера: ни одно устройство не подключится. Проверьте DNS / DDNS."
|
||||
msgstr[1] "%s → %s: только IPv6, и это не публичные адреса роутера: ни одно устройство не подключится. Проверьте DNS / DDNS."
|
||||
msgstr[2] "%s → %s: только IPv6, и это не публичные адреса роутера: ни одно устройство не подключится. Проверьте DNS / DDNS."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router."
|
||||
msgstr "%s → %s: только IPv6, но у роутера нет публичного IPv6-адреса: ни одно устройство не подключится. Проверьте DNS / DDNS или настройте IPv6 на роутере."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."
|
||||
msgstr "%s → %s: только IPv6, поэтому подключатся лишь устройства с IPv6 (у IPv4-адреса роутера %s нет имени)."
|
||||
@@ -983,6 +1064,10 @@ msgstr[2] "%s: %s устройств, город неизвестен"
|
||||
msgid "%s: %s of 4"
|
||||
msgstr "%s: %s из 4"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>."
|
||||
msgstr "%s: тег <%s> не примут приложения AmneziaWG: используйте <b 0x…> с чётным числом шестнадцатеричных цифр, <r N>, <rc N> или <rd N> с N от 1 до 1000 либо <t>."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "%s: the device's own network handles it."
|
||||
msgstr "%s: этот трафик идёт через собственную сеть устройства."
|
||||
@@ -1650,6 +1735,10 @@ msgstr "Приложения с AmneziaWG 3.1 (актуальный AmneziaVPN)"
|
||||
msgid "As soon as found"
|
||||
msgstr "Сразу"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "As the server: %s"
|
||||
msgstr "Как у сервера: %s"
|
||||
|
||||
#: web/src/admin/pages/settings/updates.ts
|
||||
msgid "At a set time"
|
||||
msgstr "В заданное время"
|
||||
@@ -1699,6 +1788,10 @@ msgstr "Автообновление компонентов"
|
||||
msgid "Automatic update: system packages"
|
||||
msgstr "Автообновление системных пакетов"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Automatic: %s"
|
||||
msgstr "Автоматически: %s"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "B"
|
||||
@@ -1806,8 +1899,8 @@ msgid "Blocked"
|
||||
msgstr "Заблокировано"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Blocked portal sign-ins (tunnels and services are in the service log)"
|
||||
msgstr "Заблокированные входы на портал (туннели и службы - в журнале служб)"
|
||||
msgid "Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)"
|
||||
msgstr "Заблокированные входы на портал и устройства, которые не могут нормально подключиться (туннели и службы - в журнале служб)"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/pages/person/limits.ts
|
||||
@@ -1893,6 +1986,7 @@ msgid "Certificates (ACME)"
|
||||
msgstr "Сертификаты (ACME)"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/limits.ts
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
@@ -1904,6 +1998,14 @@ msgstr "Изменить"
|
||||
msgid "Change limit"
|
||||
msgstr "Изменить лимит"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the MTU"
|
||||
msgstr "Изменить MTU"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the keep-alive"
|
||||
msgstr "Изменить keep-alive"
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Change the tunnel network"
|
||||
msgstr "Сменить сеть туннеля"
|
||||
@@ -1912,6 +2014,10 @@ msgstr "Сменить сеть туннеля"
|
||||
msgid "Changed network"
|
||||
msgstr "Сменило сеть"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "Changed: %s."
|
||||
msgstr "Изменено: %s."
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Changing it marks devices “Update config” until they import again"
|
||||
msgstr "После изменения устройства помечаются «Обновить конфигурацию», пока не импортируют её заново"
|
||||
@@ -2005,6 +2111,10 @@ msgstr "Выберите %s, чтобы включить его."
|
||||
msgid "Choose a device on at least one side."
|
||||
msgstr "Выберите устройство хотя бы с одной стороны."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Choose a disguise on the Server page: it replaces the values set by hand."
|
||||
msgstr "Выберите маскировку на странице сервера: она заменит значения, заданные вручную."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
|
||||
msgid "Choose a free port between 1 and 65535 (not 22, 53, 80 or 443)."
|
||||
@@ -2099,6 +2209,10 @@ msgstr "Закрыть"
|
||||
msgid "Collecting… 1 point a minute"
|
||||
msgstr "Сбор данных… 1 точка в минуту"
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Collecting… 1 point a second"
|
||||
msgstr "Сбор данных… 1 точка в секунду"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "Colour"
|
||||
msgstr "Цвет"
|
||||
@@ -2154,6 +2268,10 @@ msgstr "Подключено с %s"
|
||||
msgid "Connection"
|
||||
msgstr "Подключение"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connection keeps dropping"
|
||||
msgstr "Связь постоянно рвётся"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/agent
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connections"
|
||||
@@ -2228,6 +2346,10 @@ msgstr "Сервер %s не принял устройства: %s."
|
||||
msgid "Couldn't read the devices at home."
|
||||
msgstr "Не удалось получить список домашних устройств."
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Couldn't read the live speed: %s"
|
||||
msgstr "Не удалось получить скорость: %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc
|
||||
msgid "Couldn't save /etc/config/dawnline: %s. Is the flash full?"
|
||||
msgstr "Не удалось сохранить /etc/config/dawnline: %s. Возможно, заполнена флеш-память?"
|
||||
@@ -2453,6 +2575,7 @@ msgstr "Сведения"
|
||||
|
||||
#: web/src/admin/logs.ts
|
||||
#: web/src/admin/map.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "Device"
|
||||
msgstr "Устройство"
|
||||
|
||||
@@ -2468,6 +2591,18 @@ msgstr "Устройство %s подключилось"
|
||||
msgid "Device %s connected from %s"
|
||||
msgstr "Устройство %s подключилось с %s"
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s connects normally again"
|
||||
msgstr "Устройство %s снова подключается нормально"
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s has a connection problem"
|
||||
msgstr "У устройства %s проблема с подключением"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: MTU %d is not between 1280 and 1500."
|
||||
msgstr "Устройство %s (%s): MTU %d вне пределов от 1280 до 1500."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: address %s is also used by device %s of %s."
|
||||
msgstr "Устройство %s (%s): адрес %s уже занят устройством %s (%s)."
|
||||
@@ -2488,6 +2623,10 @@ msgstr "Устройство %s (%s): адрес %s принадлежит са
|
||||
msgid "Device %s of %s: address (none) is not a plain IPv4 address."
|
||||
msgstr "Устройство %s (%s): нет IPv4-адреса."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds."
|
||||
msgstr "Устройство %s (%s): keep-alive %d вне пределов от 0 до 600 секунд."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the preshared key is not a key."
|
||||
msgstr "Устройство %s (%s): общий ключ (PSK) некорректен."
|
||||
@@ -2500,6 +2639,10 @@ msgstr "Устройство %s (%s): приватный ключ некорре
|
||||
msgid "Device %s of %s: the public key is not a key."
|
||||
msgstr "Устройство %s (%s): публичный ключ некорректен."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the public key is the server's own."
|
||||
msgstr "Устройство %s (%s): публичный ключ совпадает с ключом сервера."
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s went offline"
|
||||
msgstr "Устройство %s отключилось"
|
||||
@@ -2768,6 +2911,10 @@ msgstr "Пусто - адрес портала (%s)."
|
||||
msgid "Empty = the portal’s address."
|
||||
msgstr "Пусто - адрес портала."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Empty: automatic. Lower it when big pages hang on this device."
|
||||
msgstr "Пусто: автоматически. Уменьшите, если на этом устройстве зависают большие страницы."
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Enable"
|
||||
msgstr "Включить"
|
||||
@@ -2805,8 +2952,8 @@ msgid "Enter a circle name: up to 32 characters, without < > \" or \\."
|
||||
msgstr "Введите название круга: до 32 символов, без < > \" и обратной косой черты."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Enter a device name (up to 48 characters)."
|
||||
msgstr "Введите название устройства (до 48 символов)."
|
||||
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
|
||||
msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Enter a hostname or IP address."
|
||||
@@ -3028,6 +3175,14 @@ msgstr "Свободное место на роутере"
|
||||
msgid "From"
|
||||
msgstr "С"
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 0 to 600 seconds."
|
||||
msgstr "От 0 до 600 секунд."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 1280 to 1500."
|
||||
msgstr "От 1280 до 1500."
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "From the rules on this server"
|
||||
msgstr "По правилам этого сервера"
|
||||
@@ -3113,6 +3268,10 @@ msgstr "HTTPS на этом порту, открыт на WAN."
|
||||
msgid "Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."
|
||||
msgstr "Таймеры рукопожатия и ключей меняются в этих пределах вместо фиксированных значений WireGuard."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Handshake complete, but no data"
|
||||
msgstr "Рукопожатие есть, но данных нет"
|
||||
|
||||
#: web/src/admin/pages/diagnostics/index.ts
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Health"
|
||||
@@ -3190,6 +3349,10 @@ msgstr "Домашняя сеть"
|
||||
msgid "Home network + Internet"
|
||||
msgstr "Домашняя сеть и интернет"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "Home network addresses"
|
||||
msgstr "Адреса домашней сети"
|
||||
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
msgid "Home networks %s reaches. Networks added to the server later stay out."
|
||||
msgstr "%s: доступны отмеченные домашние сети. Сети, добавленные на сервер позже, останутся недоступны."
|
||||
@@ -3246,10 +3409,18 @@ msgstr "Как часто"
|
||||
msgid "How the portal listens (80 and 443 stay free)"
|
||||
msgstr "Как портал принимает подключения (80 и 443 остаются свободны)"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "I1-I5 together must be at most 2000 characters, not %d."
|
||||
msgstr "I1–I5 вместе: не больше 2000 символов, сейчас %d."
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Idle right now"
|
||||
msgstr "Сейчас без трафика"
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "If the router’s DNS hands out proxy addresses, those sites won’t open without it."
|
||||
msgstr "Если DNS роутера выдаёт адреса прокси, без этого такие сайты не откроются."
|
||||
|
||||
#: web/src/admin/pages/settings/backups.ts
|
||||
msgid "Import"
|
||||
msgstr "Импортировать"
|
||||
@@ -3334,6 +3505,10 @@ msgstr "Устанавливать автоматически"
|
||||
msgid "Install it in Dawnline → Components."
|
||||
msgstr "Установите его в Dawnline → Компоненты."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page."
|
||||
msgstr "Установите эту сборку AmneziaWG в Dawnline → Компоненты или смените маскировку на странице сервера."
|
||||
|
||||
#: web/src/admin/pkgs.ts
|
||||
msgid "Install the home-like link?"
|
||||
msgstr "Установить домашний маршрут?"
|
||||
@@ -3517,6 +3692,10 @@ msgstr "Карточка приглашения"
|
||||
msgid "Invite card for %s"
|
||||
msgstr "Карточка приглашения: %s"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "It connects, but the connection breaks every few minutes: the network may be cutting it."
|
||||
msgstr "Устройство подключается, но связь рвётся каждые несколько минут: возможно, её обрывает сеть."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "It is in the tunnel network %s."
|
||||
msgstr "Он входит в сеть туннеля %s."
|
||||
@@ -3545,6 +3724,10 @@ msgstr "Конфигурация устройства не направляет
|
||||
msgid "Its configuration sends it to the router"
|
||||
msgstr "Конфигурация устройства направляет этот трафик на роутер"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Jmin must not be larger than Jmax."
|
||||
msgstr "Jmin не может быть больше Jmax."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Junk packets"
|
||||
msgstr "Мусорные пакеты"
|
||||
@@ -3582,13 +3765,19 @@ msgid "Keep the previous version"
|
||||
msgstr "Хранить прошлую версию"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive"
|
||||
msgstr "Keep-alive"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "Keep-alive must be 0-600 seconds."
|
||||
msgstr "Keep-alive: от 0 до 600 секунд."
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive of %s"
|
||||
msgstr "Keep-alive для «%s»"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "Keeping AmneziaWG %s for rollback"
|
||||
msgstr "Сохранение AmneziaWG %s для отката"
|
||||
@@ -3635,6 +3824,12 @@ msgstr "Не удалось создать ключ (нет случайных
|
||||
msgid "Key generation failed."
|
||||
msgstr "Не удалось создать ключ."
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "LAN Bypass"
|
||||
msgstr "Обход локальной сети"
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Last 30 days"
|
||||
msgstr "За 30 дней"
|
||||
@@ -3669,6 +3864,10 @@ msgstr "Установлена последняя версия"
|
||||
msgid "Leave out https:// - just the name."
|
||||
msgstr "Без https:// - только имя."
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Letters, digits, spaces and - _ . only."
|
||||
msgstr "Только буквы, цифры, пробелы и - _ ."
|
||||
|
||||
#: web/src/admin/pages/components/packages.ts
|
||||
msgid "Let’s Encrypt certificate for the portal"
|
||||
msgstr "Сертификат Let’s Encrypt для портала"
|
||||
@@ -3834,6 +4033,7 @@ msgstr "МБ"
|
||||
msgid "MTU is now automatic"
|
||||
msgstr ": MTU теперь выбирается автоматически"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "MTU must be 1280-1500."
|
||||
msgstr "MTU: от 1280 до 1500."
|
||||
@@ -3842,6 +4042,10 @@ msgstr "MTU: от 1280 до 1500."
|
||||
msgid "MTU must be 1280–1500, or empty for automatic."
|
||||
msgstr "MTU - от 1280 до 1500 или пусто для автоматического выбора."
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "MTU of %s"
|
||||
msgstr "MTU для «%s»"
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Made by the router: browsers warn until a certificate covers the address."
|
||||
msgstr "Создан роутером: браузеры будут предупреждать, пока у адреса нет настоящего сертификата."
|
||||
@@ -4327,6 +4531,7 @@ msgid "Nobody is connected"
|
||||
msgstr "Никто не подключён"
|
||||
|
||||
#: web/src/admin/pages/settings/defaults.ts
|
||||
#: web/src/admin/ui/controls.ts
|
||||
msgid "None"
|
||||
msgstr "Нет"
|
||||
|
||||
@@ -4477,6 +4682,7 @@ msgstr "Сейчас: %s."
|
||||
msgid "OK"
|
||||
msgstr "Работает"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/disguise.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
@@ -4489,8 +4695,8 @@ msgid "Off: NAT may close the tunnel when idle, and “Connected” lags."
|
||||
msgstr "Выкл.: NAT может закрыть туннель при простое, а статус «Подключено» будет запаздывать."
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."
|
||||
msgstr "Выкл.: интернет-трафик идёт прямо в WAN, минуя всё, что обрабатывает домашний трафик на этом роутере."
|
||||
msgid "Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."
|
||||
msgstr "Выкл.: интернет-трафик идёт прямо в WAN, это самый быстрый путь. DNS по-прежнему через роутер. Прокси и фильтры на роутере обработают туннель, только если вы %s."
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Off: only you add devices, from LuCI. On: people manage their devices within the limits you set."
|
||||
@@ -4523,6 +4729,7 @@ msgstr "Возраст нужно указать числом дней."
|
||||
msgid "Older →"
|
||||
msgstr "Старше →"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "On"
|
||||
@@ -4536,6 +4743,14 @@ msgstr "На GitHub"
|
||||
msgid "On one of the networks %s reaches."
|
||||
msgstr "В одной из сетей, доступных для %s."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "On two devices at once"
|
||||
msgstr "На двух устройствах сразу"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "On, except %s (home)"
|
||||
msgstr "Вкл., кроме %s (дом)"
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page."
|
||||
msgstr "Ещё один сервер: другой порт или маскировка для сетей, где первый не проходит, или свои правила доступа к домашней сети. Людей переносят между серверами на их странице."
|
||||
@@ -4565,10 +4780,18 @@ msgstr "Доступны только устройства людей с дос
|
||||
msgid "Only home devices reach people's devices."
|
||||
msgstr "Связаться с устройствами людей могут только домашние устройства."
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Only letters, digits, - _ ."
|
||||
msgstr "Только буквы, цифры, - _ ."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "Only people with home access reach other devices."
|
||||
msgstr "Связаться с другими устройствами могут только люди с доступом к домашней сети."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can change how a device connects."
|
||||
msgstr "Менять настройки подключения устройства может только администратор."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can turn devices off."
|
||||
msgstr "Отключать устройства может только администратор."
|
||||
@@ -4726,6 +4949,10 @@ msgstr "Страница %s"
|
||||
msgid "Parameters copied"
|
||||
msgstr "Параметры скопированы"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Parameters copied. The header protection key is in each device’s file."
|
||||
msgstr "Параметры скопированы. Ключ защиты заголовков есть в файле каждого устройства."
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Paths on the router. Leave both empty to pick a certificate automatically."
|
||||
msgstr "Пути на роутере. Оставьте оба поля пустыми, чтобы сертификат выбирался автоматически."
|
||||
@@ -5208,6 +5435,10 @@ msgstr "Переустановка AmneziaWG"
|
||||
msgid "Reinstalling Dawnline"
|
||||
msgstr "Переустановка Dawnline"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "RejectAfterTime must be at most 180 seconds."
|
||||
msgstr "RejectAfterTime: не больше 180 секунд."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc
|
||||
msgid "Release %s has no %s: it stays as it is"
|
||||
msgstr "В релизе %s нет %s: остаётся как есть"
|
||||
@@ -5529,8 +5760,13 @@ msgstr "Русский"
|
||||
msgid "Russian translation"
|
||||
msgstr "Русский перевод"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size."
|
||||
msgstr "S2 не может равняться S1 + 56: начальный и ответный пакеты рукопожатия будут одного размера."
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
@@ -5553,6 +5789,7 @@ msgid "Save to flash"
|
||||
msgstr "Запись во флеш-память"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
#: web/src/admin/pages/settings/defaults.ts
|
||||
@@ -5585,6 +5822,10 @@ msgstr "Отсканируйте в AmneziaVPN или любом приложе
|
||||
msgid "Screen sharing"
|
||||
msgstr "Общий экран"
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops."
|
||||
msgstr "В секундах. Пусто: как у сервера. Чем дольше, тем меньше расход батареи, но за некоторыми NAT связь тогда рвётся."
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Seen recently"
|
||||
msgstr "Недавно в сети"
|
||||
@@ -5767,6 +6008,10 @@ msgstr "Показать карту"
|
||||
msgid "Show progress"
|
||||
msgstr "Показать ход выполнения"
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Show the new configuration"
|
||||
msgstr "Показать новую конфигурацию"
|
||||
|
||||
#: web/src/admin/pages/settings/map.ts
|
||||
msgid "Show where people connect from on the Overview and person pages, at city level."
|
||||
msgstr "Показывать в «Обзоре» и на страницах людей, откуда они подключаются, - с точностью до города."
|
||||
@@ -5812,6 +6057,10 @@ msgstr "Пакеты-сигнатуры"
|
||||
msgid "Signatures"
|
||||
msgstr "Сигнатуры"
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."
|
||||
msgstr "Медленнее: каждый пакет проходит через роутер дважды. На двухъядерном роутере скорость ниже до трети, а на пределе теряются пакеты."
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"
|
||||
@@ -6009,6 +6258,15 @@ msgstr "Это то же самое устройство"
|
||||
msgid "The %s build, %s."
|
||||
msgstr "Сборка %s, версия %s."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr "Обновление AmneziaWG установлено и заработает после перезагрузки."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The AmneziaWG update waits for a reboot"
|
||||
msgstr "Обновление AmneziaWG ждёт перезагрузки"
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address."
|
||||
msgstr "Провайдер делит один адрес между многими абонентами: устройства смогут подключиться, только если он выдаст вам публичный адрес или IPv6. Спросите у провайдера или используйте имя DDNS, которое указывает на IPv6-адрес."
|
||||
@@ -6065,10 +6323,26 @@ msgstr "По умолчанию lan: устройства получат име
|
||||
msgid "The device is disconnected immediately and its configuration stops working."
|
||||
msgstr "Устройство сразу отключится, а его конфигурация перестанет работать."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The devices in AmneziaWG could not be checked"
|
||||
msgstr "Не удалось проверить устройства в AmneziaWG"
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "The device’s address at home."
|
||||
msgstr "Адрес устройства в домашней сети."
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected, except %s: your home network."
|
||||
msgstr "Локальная сеть устройства остаётся доступной при подключении, кроме %s: это ваша домашняя сеть."
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected."
|
||||
msgstr "Локальная сеть устройства остаётся доступной при подключении."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The device’s network may be blocking the connection."
|
||||
msgstr "Возможно, сеть устройства блокирует подключение."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "The firewall lets it through"
|
||||
msgstr "Межсетевой экран пропускает трафик"
|
||||
@@ -6077,6 +6351,10 @@ msgstr "Межсетевой экран пропускает трафик"
|
||||
msgid "The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware."
|
||||
msgstr "Прошивка сменилась (ядро %s → %s): сборки AmneziaWG, установленной для прежней, больше нет. Установите сборку для этой прошивки."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "The header protection key is not a key."
|
||||
msgstr "Ключ защиты заголовков некорректен."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "The id may use lowercase letters, digits and underscores."
|
||||
msgstr "В идентификаторе можно использовать строчные латинские буквы, цифры и подчёркивания."
|
||||
@@ -6138,8 +6416,8 @@ msgid "The new version did not answer in LuCI or its agent did not start. Try ag
|
||||
msgstr "Новая версия не ответила в LuCI, или её агент не запустился. Попробуйте ещё раз в «Компонентах» или установите её через install.sh, чтобы увидеть причину."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update"
|
||||
msgstr "Старый модуль ядра AmneziaWG всё ещё загружен (возможно, его использует другой интерфейс AmneziaWG): перезагрузите роутер, чтобы завершить обновление"
|
||||
msgid "The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr "Старый модуль ядра остаётся загруженным (возможно, его использует другой интерфейс AmneziaWG): обновление AmneziaWG установлено и заработает после перезагрузки."
|
||||
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
msgid "The old link stops working right away."
|
||||
@@ -6201,6 +6479,10 @@ msgstr "Роутер один раз отправляет сервису каж
|
||||
msgid "The router stopped answering. The job may still finish: reopen Components in a minute."
|
||||
msgstr "Роутер перестал отвечать. Задача ещё может завершиться: откройте «Компоненты» снова через минуту."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The same configuration connects from two places in turn. Give the other device its own."
|
||||
msgstr "Одна и та же конфигурация подключается по очереди из двух мест. Дайте второму устройству собственную."
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "The server is turned off"
|
||||
msgstr "Сервер выключен"
|
||||
@@ -6225,6 +6507,10 @@ msgstr "Перевод установлен."
|
||||
msgid "The translation is removed."
|
||||
msgstr "Перевод удалён."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The tunnel could not be read, so its devices could not be checked."
|
||||
msgstr "Туннель не удалось прочитать, поэтому его устройства не проверены."
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The tunnel needs %s. Install the build made for this firmware, then create the server."
|
||||
msgstr "Для туннеля нужно: %s. Установите сборку для этой прошивки, затем создайте сервер."
|
||||
@@ -6295,6 +6581,10 @@ msgstr "Это устройство создало ключи в браузер
|
||||
msgid "This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below."
|
||||
msgstr "На устройстве устаревшая конфигурация: после настройки изменились сети или DNS. Импортируйте её заново с помощью QR-кода, ключа или файла ниже."
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "This device is using an outdated configuration."
|
||||
msgstr "На этом устройстве устаревшая конфигурация."
|
||||
|
||||
#: web/src/admin/pages/person/devices.ts
|
||||
msgid "This device made its own keys in the browser; its configuration only exists there."
|
||||
msgstr "Это устройство создало ключи в браузере, поэтому его конфигурация есть только там."
|
||||
@@ -6541,6 +6831,10 @@ msgstr "UDP-порт: от 1 до 65535."
|
||||
msgid "UDP port: %s"
|
||||
msgstr "UDP-порт: %s"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Unable to complete the handshake"
|
||||
msgstr "Не удаётся завершить рукопожатие"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc
|
||||
msgid "Unexpected entry in backup: %s"
|
||||
msgstr "Неожиданная запись в резервной копии: %s"
|
||||
@@ -6669,6 +6963,10 @@ msgstr[0] "Максимум %s символ (сейчас %s)."
|
||||
msgstr[1] "Максимум %s символа (сейчас %s)."
|
||||
msgstr[2] "Максимум %s символов (сейчас %s)."
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Up to %s characters."
|
||||
msgstr "Не больше %s символов."
|
||||
|
||||
#: web/src/admin/pages/components/index.ts
|
||||
msgid "Up to date"
|
||||
msgstr "Актуально"
|
||||
@@ -7002,6 +7300,10 @@ msgstr "Почему соединение проходит или нет"
|
||||
msgid "Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."
|
||||
msgstr "Внутри круга: семья видит семью, гости - гостей. Каждый видит свои устройства. Люди только с интернетом - никогда."
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||
msgid "Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline."
|
||||
msgstr "Без kmod-nft-offload каждый пакет на этом пути дважды проходит через межсетевой экран. Установите его и перезапустите Dawnline."
|
||||
|
||||
#: web/src/admin/updater/operation.ts
|
||||
msgid "Working…"
|
||||
msgstr "Выполняется…"
|
||||
@@ -7216,6 +7518,10 @@ msgstr ": новую сборку нужно включить вручную в
|
||||
msgid "access"
|
||||
msgstr "доступ"
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "add its interface %s to their source interfaces yourself"
|
||||
msgstr "сами добавите его интерфейс %s в их источники трафика"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "address %s"
|
||||
msgstr "адрес %s"
|
||||
@@ -7252,6 +7558,10 @@ msgstr "другая программа на этом роутере"
|
||||
msgid "answers again"
|
||||
msgstr "снова отвечает"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not install %s %s (installed: %s)"
|
||||
msgstr "apk не установил %s %s (установлено: %s)"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not reinstall the version that is already installed"
|
||||
msgstr "apk не переустановил уже установленную версию"
|
||||
@@ -7280,6 +7590,14 @@ msgstr "отсутствуют"
|
||||
msgid "as soon as found"
|
||||
msgstr "сразу при обнаружении"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "as the server"
|
||||
msgstr "как у сервера"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "automatic"
|
||||
msgstr "автоматически"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
msgid "automatic update failed"
|
||||
msgstr ": автоматическое обновление не удалось"
|
||||
@@ -7500,10 +7818,6 @@ msgstr ": ошибка (%s)"
|
||||
msgid "from the portal"
|
||||
msgstr "через портал"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "h1-h4 must be distinct"
|
||||
msgstr "h1-h4 должны быть разными"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "has an invalid interface name \"%s\""
|
||||
msgstr ": недопустимое имя интерфейса «%s»"
|
||||
@@ -7552,6 +7866,14 @@ msgstr ": установлена сборка %s · %s"
|
||||
msgid "interface %s"
|
||||
msgstr "интерфейс %s"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s has Dawnline's settings again"
|
||||
msgstr ": у интерфейса %s снова настройки Dawnline"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s was changed outside Dawnline"
|
||||
msgstr ": интерфейс %s изменён не через Dawnline"
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "internet"
|
||||
msgstr "интернет"
|
||||
@@ -7560,6 +7882,10 @@ msgstr "интернет"
|
||||
msgid "is kept down"
|
||||
msgstr ": остановлен"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise has values AmneziaWG cannot take"
|
||||
msgstr ": остановлен, в маскировке есть значения, которые AmneziaWG не примет"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise needs AmneziaWG %s (installed: %s)"
|
||||
msgstr ": остановлен, для маскировки нужен AmneziaWG %s (установлен %s)"
|
||||
@@ -7620,6 +7946,10 @@ msgstr "кбит/с"
|
||||
msgid "keep access"
|
||||
msgstr "сохранить доступ"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "keep-alive"
|
||||
msgstr "keep-alive"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "kept in memory only (lost on reboot)"
|
||||
msgstr "только в памяти (пропадают при перезагрузке)"
|
||||
@@ -7640,6 +7970,10 @@ msgstr ": модуль ядра не загружен"
|
||||
msgid "last 15 min"
|
||||
msgstr "за 15 мин"
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "last 2 min"
|
||||
msgstr "за 2 мин"
|
||||
|
||||
#: web/src/admin/pages/person/header.ts
|
||||
msgid "last seen %s"
|
||||
msgstr "в сети %s"
|
||||
@@ -7927,6 +8261,10 @@ msgstr ": правила Dawnline изменены или удалены"
|
||||
msgid "runs again"
|
||||
msgstr "снова работает"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||
msgid "runs without its fast path"
|
||||
msgstr "работает без ускорения"
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "saved to flash every 10 minutes"
|
||||
msgstr "записываются во флеш-память каждые 10 минут"
|
||||
@@ -7955,7 +8293,17 @@ msgstr "сервер «%s»"
|
||||
msgid "services"
|
||||
msgstr "сервисы"
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgctxt "key"
|
||||
msgid "set"
|
||||
msgstr "задан"
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "set when it was added"
|
||||
msgstr "выбрано при добавлении"
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "setting it up again"
|
||||
msgstr "настраиваем заново"
|
||||
|
||||
|
||||
@@ -95,6 +95,18 @@ msgstr ""
|
||||
msgid "%s - not repaired again (%d repairs didn't help)"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record."
|
||||
msgid_plural "%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router."
|
||||
msgid_plural "%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you)."
|
||||
msgid_plural "%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."
|
||||
@@ -148,6 +160,10 @@ msgstr ""
|
||||
msgid "%s and %s are not in one circle"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s and %s overlap: each packet type needs values of its own."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "%s applied"
|
||||
msgstr ""
|
||||
@@ -420,6 +436,10 @@ msgstr ""
|
||||
msgid "%s has Internet only: only DNS and the portal on the router."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has a tag that is not closed with >."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s has an invalid interface name \"%s\"."
|
||||
msgstr ""
|
||||
@@ -523,6 +543,10 @@ msgstr ""
|
||||
msgid "%s is kept down."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise has values AmneziaWG cannot take. %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s is kept down: its disguise needs AmneziaWG %s (installed: %s)."
|
||||
msgstr ""
|
||||
@@ -541,6 +565,10 @@ msgstr[1] ""
|
||||
msgid "%s is not a bridge, so Dawnline cannot join the LAN as a device."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is not a common home subnet: the networks people connect from rarely use the same addresses."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/updates.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_pkgs.uc
|
||||
msgid "%s is not a package Dawnline manages"
|
||||
@@ -574,6 +602,10 @@ msgstr ""
|
||||
msgid "%s is on the internet"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "%s is part of %s; choose %s instead."
|
||||
msgstr ""
|
||||
@@ -629,6 +661,10 @@ msgstr[1] ""
|
||||
msgid "%s left"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s may not contain # or a line break."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/shared/format.ts
|
||||
msgid "%s min ago"
|
||||
msgstr ""
|
||||
@@ -648,7 +684,31 @@ msgid "%s moves to %s with OpenWrt %s."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or range"
|
||||
msgid "%s must be a number or a range like 10-100, up to 65535."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 100-200, up to 4294967295."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a number or a range like 5-15, from 1 to 65535."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be a whole number from 0 to 65535."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be at least 12 with header protection."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be from %d to %d."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s must be on or off."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
@@ -805,6 +865,10 @@ msgstr[1] ""
|
||||
msgid "%s resumed"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "%s s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/logs.ts
|
||||
msgid "%s since %s"
|
||||
msgstr ""
|
||||
@@ -882,6 +946,10 @@ msgid_plural "%s years"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · interface settings"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "%s · restored"
|
||||
msgstr ""
|
||||
@@ -898,6 +966,16 @@ msgstr ""
|
||||
msgid "%s → %s (this router)."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgid_plural "%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."
|
||||
msgstr ""
|
||||
@@ -935,6 +1013,10 @@ msgstr[1] ""
|
||||
msgid "%s: %s of 4"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "%s: the device's own network handles it."
|
||||
msgstr ""
|
||||
@@ -1597,6 +1679,10 @@ msgstr ""
|
||||
msgid "As soon as found"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "As the server: %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/updates.ts
|
||||
msgid "At a set time"
|
||||
msgstr ""
|
||||
@@ -1646,6 +1732,10 @@ msgstr ""
|
||||
msgid "Automatic update: system packages"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Automatic: %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "B"
|
||||
@@ -1753,7 +1843,7 @@ msgid "Blocked"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Blocked portal sign-ins (tunnels and services are in the service log)"
|
||||
msgid "Blocked portal sign-ins and devices that can’t connect properly (tunnels and services are in the service log)"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
@@ -1840,6 +1930,7 @@ msgid "Certificates (ACME)"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/limits.ts
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
@@ -1851,6 +1942,14 @@ msgstr ""
|
||||
msgid "Change limit"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the MTU"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Change the keep-alive"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Change the tunnel network"
|
||||
msgstr ""
|
||||
@@ -1859,6 +1958,10 @@ msgstr ""
|
||||
msgid "Changed network"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "Changed: %s."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "Changing it marks devices “Update config” until they import again"
|
||||
msgstr ""
|
||||
@@ -1952,6 +2055,10 @@ msgstr ""
|
||||
msgid "Choose a device on at least one side."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Choose a disguise on the Server page: it replaces the values set by hand."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/common.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
|
||||
msgid "Choose a free port between 1 and 65535 (not 22, 53, 80 or 443)."
|
||||
@@ -2046,6 +2153,10 @@ msgstr ""
|
||||
msgid "Collecting… 1 point a minute"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Collecting… 1 point a second"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "Colour"
|
||||
msgstr ""
|
||||
@@ -2101,6 +2212,10 @@ msgstr ""
|
||||
msgid "Connection"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connection keeps dropping"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/agent
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Connections"
|
||||
@@ -2175,6 +2290,10 @@ msgstr ""
|
||||
msgid "Couldn't read the devices at home."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Couldn't read the live speed: %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/store.uc
|
||||
msgid "Couldn't save /etc/config/dawnline: %s. Is the flash full?"
|
||||
msgstr ""
|
||||
@@ -2400,6 +2519,7 @@ msgstr ""
|
||||
|
||||
#: web/src/admin/logs.ts
|
||||
#: web/src/admin/map.ts
|
||||
#: web/src/shared/format.ts
|
||||
msgid "Device"
|
||||
msgstr ""
|
||||
|
||||
@@ -2415,6 +2535,18 @@ msgstr ""
|
||||
msgid "Device %s connected from %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s connects normally again"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s has a connection problem"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: MTU %d is not between 1280 and 1500."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: address %s is also used by device %s of %s."
|
||||
msgstr ""
|
||||
@@ -2435,6 +2567,10 @@ msgstr ""
|
||||
msgid "Device %s of %s: address (none) is not a plain IPv4 address."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: keep-alive %d is not between 0 and 600 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the preshared key is not a key."
|
||||
msgstr ""
|
||||
@@ -2447,6 +2583,10 @@ msgstr ""
|
||||
msgid "Device %s of %s: the public key is not a key."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Device %s of %s: the public key is the server's own."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/render.ts
|
||||
msgid "Device %s went offline"
|
||||
msgstr ""
|
||||
@@ -2715,6 +2855,10 @@ msgstr ""
|
||||
msgid "Empty = the portal’s address."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Empty: automatic. Lower it when big pages hang on this device."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Enable"
|
||||
msgstr ""
|
||||
@@ -2752,7 +2896,7 @@ msgid "Enter a circle name: up to 32 characters, without < > \" or \\."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "Enter a device name (up to 48 characters)."
|
||||
msgid "Enter a device name: up to %d letters, digits, spaces and - _ ."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
@@ -2975,6 +3119,14 @@ msgstr ""
|
||||
msgid "From"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 0 to 600 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "From 1280 to 1500."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "From the rules on this server"
|
||||
msgstr ""
|
||||
@@ -3060,6 +3212,10 @@ msgstr ""
|
||||
msgid "Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Handshake complete, but no data"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/diagnostics/index.ts
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Health"
|
||||
@@ -3137,6 +3293,10 @@ msgstr ""
|
||||
msgid "Home network + Internet"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "Home network addresses"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/pickers.ts
|
||||
msgid "Home networks %s reaches. Networks added to the server later stay out."
|
||||
msgstr ""
|
||||
@@ -3193,10 +3353,18 @@ msgstr ""
|
||||
msgid "How the portal listens (80 and 443 stay free)"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "I1-I5 together must be at most 2000 characters, not %d."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Idle right now"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "If the router’s DNS hands out proxy addresses, those sites won’t open without it."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/backups.ts
|
||||
msgid "Import"
|
||||
msgstr ""
|
||||
@@ -3281,6 +3449,10 @@ msgstr ""
|
||||
msgid "Install it in Dawnline → Components."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pkgs.ts
|
||||
msgid "Install the home-like link?"
|
||||
msgstr ""
|
||||
@@ -3464,6 +3636,10 @@ msgstr ""
|
||||
msgid "Invite card for %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "It connects, but the connection breaks every few minutes: the network may be cutting it."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "It is in the tunnel network %s."
|
||||
msgstr ""
|
||||
@@ -3492,6 +3668,10 @@ msgstr ""
|
||||
msgid "Its configuration sends it to the router"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "Jmin must not be larger than Jmax."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Junk packets"
|
||||
msgstr ""
|
||||
@@ -3529,13 +3709,19 @@ msgid "Keep the previous version"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "Keep-alive must be 0-600 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "Keep-alive of %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "Keeping AmneziaWG %s for rollback"
|
||||
msgstr ""
|
||||
@@ -3582,6 +3768,12 @@ msgstr ""
|
||||
msgid "Key generation failed."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "LAN Bypass"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "Last 30 days"
|
||||
msgstr ""
|
||||
@@ -3616,6 +3808,10 @@ msgstr ""
|
||||
msgid "Leave out https:// - just the name."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Letters, digits, spaces and - _ . only."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/components/packages.ts
|
||||
msgid "Let’s Encrypt certificate for the portal"
|
||||
msgstr ""
|
||||
@@ -3781,6 +3977,7 @@ msgstr ""
|
||||
msgid "MTU is now automatic"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/servers.uc
|
||||
msgid "MTU must be 1280-1500."
|
||||
msgstr ""
|
||||
@@ -3789,6 +3986,10 @@ msgstr ""
|
||||
msgid "MTU must be 1280–1500, or empty for automatic."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "MTU of %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Made by the router: browsers warn until a certificate covers the address."
|
||||
msgstr ""
|
||||
@@ -4273,6 +4474,7 @@ msgid "Nobody is connected"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/defaults.ts
|
||||
#: web/src/admin/ui/controls.ts
|
||||
msgid "None"
|
||||
msgstr ""
|
||||
|
||||
@@ -4423,6 +4625,7 @@ msgstr ""
|
||||
msgid "OK"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/disguise.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
@@ -4435,7 +4638,7 @@ msgid "Off: NAT may close the tunnel when idle, and “Connected” lags."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router."
|
||||
msgid "Off: internet traffic goes straight to the WAN, the fastest way. DNS still goes through this router. Proxies and filters here handle the tunnel only if you %s."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
@@ -4468,6 +4671,7 @@ msgstr ""
|
||||
msgid "Older →"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/components/hero.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "On"
|
||||
@@ -4481,6 +4685,14 @@ msgstr ""
|
||||
msgid "On one of the networks %s reaches."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "On two devices at once"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "On, except %s (home)"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page."
|
||||
msgstr ""
|
||||
@@ -4510,10 +4722,18 @@ msgstr ""
|
||||
msgid "Only home devices reach people's devices."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Only letters, digits, - _ ."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "Only people with home access reach other devices."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can change how a device connects."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc
|
||||
msgid "Only the admin can turn devices off."
|
||||
msgstr ""
|
||||
@@ -4671,6 +4891,10 @@ msgstr ""
|
||||
msgid "Parameters copied"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgid "Parameters copied. The header protection key is in each device’s file."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/portal.ts
|
||||
msgid "Paths on the router. Leave both empty to pick a certificate automatically."
|
||||
msgstr ""
|
||||
@@ -5151,6 +5375,10 @@ msgstr ""
|
||||
msgid "Reinstalling Dawnline"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "RejectAfterTime must be at most 180 seconds."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_app.uc
|
||||
msgid "Release %s has no %s: it stays as it is"
|
||||
msgstr ""
|
||||
@@ -5470,8 +5698,13 @@ msgstr ""
|
||||
msgid "Russian translation"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "S2 must not be S1 + 56: the handshake initiation and response would have the same size."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/device.ts
|
||||
#: web/src/admin/interfaces.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
@@ -5494,6 +5727,7 @@ msgid "Save to flash"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
#: web/src/admin/device-link.ts
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
#: web/src/admin/pages/settings/defaults.ts
|
||||
@@ -5526,6 +5760,10 @@ msgstr ""
|
||||
msgid "Screen sharing"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "Seconds. Empty: as the server. Longer saves battery; behind some NATs it then drops."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "Seen recently"
|
||||
msgstr ""
|
||||
@@ -5708,6 +5946,10 @@ msgstr ""
|
||||
msgid "Show progress"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "Show the new configuration"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/settings/map.ts
|
||||
msgid "Show where people connect from on the Overview and person pages, at city level."
|
||||
msgstr ""
|
||||
@@ -5753,6 +5995,10 @@ msgstr ""
|
||||
msgid "Signatures"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "Slower: every packet crosses the router twice. On a dual-core router expect up to a third less speed, and lost packets at full load."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"
|
||||
@@ -5949,6 +6195,15 @@ msgstr ""
|
||||
msgid "The %s build, %s."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The AmneziaWG update waits for a reboot"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address."
|
||||
msgstr ""
|
||||
@@ -6005,10 +6260,26 @@ msgstr ""
|
||||
msgid "The device is disconnected immediately and its configuration stops working."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The devices in AmneziaWG could not be checked"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/netcheck.ts
|
||||
msgid "The device’s address at home."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected, except %s: your home network."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device.ts
|
||||
msgid "The device’s local network stays reachable while connected."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The device’s network may be blocking the connection."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc
|
||||
msgid "The firewall lets it through"
|
||||
msgstr ""
|
||||
@@ -6017,6 +6288,10 @@ msgstr ""
|
||||
msgid "The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "The header protection key is not a key."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
|
||||
msgid "The id may use lowercase letters, digits and underscores."
|
||||
msgstr ""
|
||||
@@ -6078,7 +6353,7 @@ msgid "The new version did not answer in LuCI or its agent did not start. Try ag
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/upd_awg.uc
|
||||
msgid "The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update"
|
||||
msgid "The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/dialogs.ts
|
||||
@@ -6141,6 +6416,10 @@ msgstr ""
|
||||
msgid "The router stopped answering. The job may still finish: reopen Components in a minute."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "The same configuration connects from two places in turn. Give the other device its own."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/overview.ts
|
||||
msgid "The server is turned off"
|
||||
msgstr ""
|
||||
@@ -6165,6 +6444,10 @@ msgstr ""
|
||||
msgid "The translation is removed."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc
|
||||
msgid "The tunnel could not be read, so its devices could not be checked."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/server.ts
|
||||
msgid "The tunnel needs %s. Install the build made for this firmware, then create the server."
|
||||
msgstr ""
|
||||
@@ -6233,6 +6516,10 @@ msgstr ""
|
||||
msgid "This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "This device is using an outdated configuration."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/devices.ts
|
||||
msgid "This device made its own keys in the browser; its configuration only exists there."
|
||||
msgstr ""
|
||||
@@ -6478,6 +6765,10 @@ msgstr ""
|
||||
msgid "UDP port: %s"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "Unable to complete the handshake"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc
|
||||
msgid "Unexpected entry in backup: %s"
|
||||
msgstr ""
|
||||
@@ -6605,6 +6896,10 @@ msgid_plural "Up to %s characters (%s now)."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
|
||||
#: web/src/shared/name-guard.ts
|
||||
msgid "Up to %s characters."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/components/index.ts
|
||||
msgid "Up to date"
|
||||
msgstr ""
|
||||
@@ -6937,6 +7232,10 @@ msgstr ""
|
||||
msgid "Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never."
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||
msgid "Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline."
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/updater/operation.ts
|
||||
msgid "Working…"
|
||||
msgstr ""
|
||||
@@ -7151,6 +7450,10 @@ msgstr ""
|
||||
msgid "access"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/interfaces.ts
|
||||
msgid "add its interface %s to their source interfaces yourself"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "address %s"
|
||||
msgstr ""
|
||||
@@ -7187,6 +7490,10 @@ msgstr ""
|
||||
msgid "answers again"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not install %s %s (installed: %s)"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/pkg.uc
|
||||
msgid "apk did not reinstall the version that is already installed"
|
||||
msgstr ""
|
||||
@@ -7215,6 +7522,14 @@ msgstr ""
|
||||
msgid "as soon as found"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "as the server"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "automatic"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/libexec/dawnline/updater
|
||||
msgid "automatic update failed"
|
||||
msgstr ""
|
||||
@@ -7434,10 +7749,6 @@ msgstr ""
|
||||
msgid "from the portal"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "h1-h4 must be distinct"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "has an invalid interface name \"%s\""
|
||||
msgstr ""
|
||||
@@ -7486,6 +7797,14 @@ msgstr ""
|
||||
msgid "interface %s"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s has Dawnline's settings again"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "interface %s was changed outside Dawnline"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/access.ts
|
||||
msgid "internet"
|
||||
msgstr ""
|
||||
@@ -7494,6 +7813,10 @@ msgstr ""
|
||||
msgid "is kept down"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise has values AmneziaWG cannot take"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
msgid "is kept down: its disguise needs AmneziaWG %s (installed: %s)"
|
||||
msgstr ""
|
||||
@@ -7554,6 +7877,10 @@ msgstr ""
|
||||
msgid "keep access"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "keep-alive"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "kept in memory only (lost on reboot)"
|
||||
msgstr ""
|
||||
@@ -7574,6 +7901,10 @@ msgstr ""
|
||||
msgid "last 15 min"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/widgets/tiles.ts
|
||||
msgid "last 2 min"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/pages/person/header.ts
|
||||
msgid "last seen %s"
|
||||
msgstr ""
|
||||
@@ -7860,6 +8191,10 @@ msgstr ""
|
||||
msgid "runs again"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc
|
||||
msgid "runs without its fast path"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/events/model.ts
|
||||
msgid "saved to flash every 10 minutes"
|
||||
msgstr ""
|
||||
@@ -7888,7 +8223,17 @@ msgstr ""
|
||||
msgid "services"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/cores/awg.ts
|
||||
msgctxt "key"
|
||||
msgid "set"
|
||||
msgstr ""
|
||||
|
||||
#: web/src/admin/device-link.ts
|
||||
msgid "set when it was added"
|
||||
msgstr ""
|
||||
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
|
||||
#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/watchdog.uc
|
||||
msgid "setting it up again"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
// Dawnline agent (procd instance). Every second its watcher reads the tunnels
|
||||
// and, the moment a device connects, its session expires or it roams, logs
|
||||
// it, folds the counters, locates the new address and moves the revision the
|
||||
// admin UI polls (presence.json, see dawnline.live). Every minute it:
|
||||
// admin UI polls (presence.json, see dawnline.live). The same read tells when
|
||||
// a device's link fails in a named way (link.json, dawnline.link), what it does
|
||||
// right now for the portal's set-up sheet (setup.json) and the live meter's
|
||||
// last two minutes, written out while someone looks (meter.json, dawnline.meter).
|
||||
// Every minute it:
|
||||
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
|
||||
// * saves the activity log to flash as often as Settings says (or never)
|
||||
// * keeps the "like a home device" path and the Home-only resolver up
|
||||
@@ -26,6 +30,9 @@ import * as net from 'dawnline.net';
|
||||
import * as store from 'dawnline.store';
|
||||
import * as upd from 'dawnline.updates';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import * as link from 'dawnline.link';
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { L_ } from 'dawnline.i18n';
|
||||
|
||||
const TICK = 60 * 1000;
|
||||
@@ -55,6 +62,12 @@ let last_states = null;
|
||||
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
|
||||
// swallow connects that happened in between.
|
||||
let presence = read_json(live.PRESENCE, {});
|
||||
// What a link showed comes from the watcher's memory, which starts empty: a
|
||||
// state shows again once it held (link.HOLD), a set-up state with the next
|
||||
// read that tells it. The meter's points start again too, written at the next look.
|
||||
write_json(live.LINK, {}, 0o600);
|
||||
write_json(live.SETUP, {}, 0o600);
|
||||
meter.stop();
|
||||
let last_online = presence.online ?? {};
|
||||
let last_endpoint = presence.endpoint ?? {};
|
||||
let rev = +(presence.rev ?? 0);
|
||||
@@ -123,6 +136,8 @@ function record_rate(m) {
|
||||
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
|
||||
}
|
||||
let last_sync = 0;
|
||||
// Per server, how the agent's last sync of its devices went (dawnline.awg.sync_peers).
|
||||
let last_peers = {};
|
||||
let conf_mtime = null;
|
||||
let cert_mtime = null;
|
||||
|
||||
@@ -166,22 +181,104 @@ function named(e) {
|
||||
/* ---------- the watcher ---------- */
|
||||
|
||||
// Per device: its latest real handshake, kept when apply re-adds the peer
|
||||
// (its counters and handshake restart from zero, or it is briefly missing).
|
||||
let last_hs = {};
|
||||
// The model, read again only when the config file changes (the watcher runs every second).
|
||||
let wm = null, wm_sig = null;
|
||||
// (its counters and handshake restart from zero, or it is briefly missing),
|
||||
// and the public key it was seen with: new keys (Reconnect, New keys) end
|
||||
// the old session, whatever its handshake said.
|
||||
let last_hs = {}, last_key = {};
|
||||
// The model, read again only when the config file changes (the watcher runs
|
||||
// every second), the tunnels it reads (live.tunnel_ifnames: a regex per
|
||||
// server, compiled each time it runs, so not every second), each device's
|
||||
// online window (live.online_windows: its keep-alive's, from the model) and
|
||||
// the largest keepalive its server's disguise makes (link.keepalive_sizes).
|
||||
let wm = null, wm_sig = null, wm_ifnames = [], wm_windows = {}, wm_ka = {};
|
||||
// netifd deletes and adds a tunnel's link each time it sets it up (a new
|
||||
// ifindex): the devices come back only with the sync its hotplug starts, and
|
||||
// then with no handshake until each one makes a new one. For this long after
|
||||
// the link changed, a device missing from it keeps what was known of it,
|
||||
// rather than a burst of disconnects and connects for everyone online.
|
||||
const RESTART_GRACE = 45;
|
||||
// Per tunnel: the link last seen (null while it is down), and until when its grace lasts.
|
||||
let links = {}, grace = {};
|
||||
|
||||
/** A file's mtime and inode ('-' when it is missing): what the cached model depends on. */
|
||||
function file_sig(path) {
|
||||
let st = stat(path);
|
||||
return st ? `${st.mtime}/${st.inode}` : '-';
|
||||
}
|
||||
|
||||
function watch_model() {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
let st = stat(CONFIG_FILE);
|
||||
let sig = st ? `${st.mtime}/${st.inode}` : null;
|
||||
// Which servers are kept down (core.BLOCKED, written by apply) is in the
|
||||
// model too: their interface names may be someone else's tunnels.
|
||||
let sig = `${file_sig(CONFIG_FILE)} ${file_sig(core.BLOCKED)}`;
|
||||
if (wm == null || sig != wm_sig) {
|
||||
wm = core.load();
|
||||
wm_sig = sig;
|
||||
wm_ifnames = live.tunnel_ifnames(wm);
|
||||
wm_windows = live.online_windows(wm);
|
||||
wm_ka = link.keepalive_sizes(wm);
|
||||
}
|
||||
return wm;
|
||||
}
|
||||
|
||||
// Per device: how its link behaves (dawnline.link: a few recent events and
|
||||
// what is shown), and whether what is shown (link.json) or the set-up states
|
||||
// (setup.json) changed since they were written.
|
||||
let link_hist = {}, link_dirty = false, setup_dirty = false;
|
||||
|
||||
/**
|
||||
* A device's read into its link history: its set-up state follows at once
|
||||
* (link.setup, a few compares unless something happened); it is classified
|
||||
* again when something happened or link.CHECK_EVERY passed (its spans age).
|
||||
* Returns the change in what is shown (link.settle: { from, to }), or null.
|
||||
*/
|
||||
function watch_link(id, dev, peer, now, on) {
|
||||
let h = link_hist[id] ??= link.fresh(now);
|
||||
let moved = false;
|
||||
if (peer)
|
||||
moved = link.observe(h, peer, now, wm_ka[id] ?? link.KEEPALIVE);
|
||||
else
|
||||
link.gone(h);
|
||||
if (link.setup(h, now, on, moved))
|
||||
setup_dirty = true;
|
||||
if (!moved && now - h.checked < link.CHECK_EVERY)
|
||||
return null;
|
||||
h.checked = now;
|
||||
link.prune(h, now);
|
||||
h.raw = link.classify(h, now, on);
|
||||
let change = link.settle(h, h.raw, now, on);
|
||||
if (change)
|
||||
link_dirty = true;
|
||||
return change;
|
||||
}
|
||||
|
||||
// The live meter: the last sample and the last two minutes of points
|
||||
// ([ ts, JSON ], newest last, meter.keep), kept whether anyone looks or not so
|
||||
// that a look gets them at once; whether meter.json is out for a look now.
|
||||
let meter_prev = null, meter_ring = [], meter_out = false;
|
||||
|
||||
/**
|
||||
* A meter point a second from this read, kept; meter.json written while
|
||||
* someone looks (meter.wanted): all the points the first second of a look,
|
||||
* then with each new one. Once nobody does, the file goes; the points stay.
|
||||
*/
|
||||
function watch_meter(m, d, now) {
|
||||
let s = meter.sample(m, d, now);
|
||||
let p = meter_prev ? meter.point(meter_prev, s) : null;
|
||||
meter_prev = s;
|
||||
if (p)
|
||||
meter.keep(meter_ring, p);
|
||||
if (!meter.wanted(now)) {
|
||||
if (meter_out)
|
||||
meter.stop();
|
||||
meter_out = false;
|
||||
return;
|
||||
}
|
||||
if (p || !meter_out)
|
||||
meter.save(meter_ring);
|
||||
meter_out = true;
|
||||
}
|
||||
|
||||
/** Move the revisions (all, and these people's) and save who is online. */
|
||||
function save_presence(people) {
|
||||
rev++;
|
||||
@@ -303,43 +400,89 @@ function place_of(ip) {
|
||||
|
||||
/*
|
||||
* One look at the tunnels. Connects (a new handshake from a device that was
|
||||
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
|
||||
* a phone asleep looks the same as one switched off, so silence alone is not
|
||||
* enough) and roaming (a new address) are acted on at
|
||||
* once: the log, the counters and the map, then the revision the UI polls.
|
||||
* Only from a complete read: a failed one says nothing about anyone.
|
||||
* away), disconnects (its session expired: no handshake within its online
|
||||
* window, live.online_window; a phone asleep looks the same as one switched
|
||||
* off, so silence alone is not enough) and roaming (a new address) are acted
|
||||
* on at once: the log, the counters and the map, then the revision the UI polls.
|
||||
* Only Dawnline's own tunnels are read, each on its own (one process with a
|
||||
* single server): a tunnel that could not be read says nothing about its
|
||||
* devices, which stay as they were.
|
||||
*/
|
||||
function watch() {
|
||||
let d = awg.dump();
|
||||
if (!d.ok)
|
||||
return;
|
||||
let m = watch_model();
|
||||
let d = awg.dump(wm_ifnames);
|
||||
let now = time();
|
||||
let events = [], people = {}, ips = [];
|
||||
for (let ifn, r in d.reads) {
|
||||
if (r == 'error')
|
||||
continue;
|
||||
let ix = d.ifaces[ifn]?.ifindex;
|
||||
if (ifn in links && links[ifn] != ix)
|
||||
grace[ifn] = now + RESTART_GRACE;
|
||||
links[ifn] = ix;
|
||||
}
|
||||
for (let ifn in keys(links))
|
||||
if (!(ifn in d.reads)) {
|
||||
delete links[ifn];
|
||||
delete grace[ifn];
|
||||
}
|
||||
let events = [], people = {}, ips = [], failing = [];
|
||||
for (let id, dev in m.devices) {
|
||||
let ifn = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.reads[ifn] == 'error')
|
||||
continue;
|
||||
let peer = d.peers[dev.public_key];
|
||||
let ep = '';
|
||||
// New keys: offline until they shake hands, and a new link history. The
|
||||
// old one's set-up session (its no data, or its data flowing) and its
|
||||
// answers would otherwise be taken for the new configuration's.
|
||||
if (last_key[id] != dev.public_key) {
|
||||
if (last_key[id] != null) {
|
||||
last_hs[id] = 0;
|
||||
let h = link_hist[id];
|
||||
if (h?.state != null) {
|
||||
link_dirty = true;
|
||||
people[dev.person] = true;
|
||||
}
|
||||
if (h?.setup != null)
|
||||
setup_dirty = true;
|
||||
delete link_hist[id];
|
||||
}
|
||||
last_key[id] = dev.public_key;
|
||||
}
|
||||
if (peer) {
|
||||
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
|
||||
ep = live.endpoint_ip(peer.endpoint);
|
||||
}
|
||||
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
|
||||
// again only with a new handshake, not the one remembered from before.
|
||||
else
|
||||
// again only with a new handshake, not the one remembered from before. Unless its
|
||||
// tunnel was just set up again and the sync has not brought it back yet.
|
||||
else if (!(grace[ifn] > now))
|
||||
last_hs[id] = 0;
|
||||
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
|
||||
let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW);
|
||||
let was = last_online[id];
|
||||
// What is shown changed: the person's pages read it again (link.json), also
|
||||
// when it cleared without an event (the device stopped trying, or was paused).
|
||||
let change = watch_link(id, dev, peer, now, on);
|
||||
if (change) {
|
||||
people[dev.person] = true;
|
||||
let le = link.event_for(change, dev, on);
|
||||
if (le)
|
||||
push(failing, le);
|
||||
}
|
||||
// One configuration on two devices: its address goes back and forth all
|
||||
// the time, which is no roaming (nor a reason to move the revision).
|
||||
let flapping = link_hist[id].raw == 'shared' || link_hist[id].state == 'shared';
|
||||
if (on && !was) {
|
||||
push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
|
||||
push(ips, ep);
|
||||
}
|
||||
else if (!on && was)
|
||||
push(events, { type: 'disconnect', person: dev.person, device: id });
|
||||
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) {
|
||||
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id] && !flapping) {
|
||||
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
|
||||
push(ips, ep);
|
||||
}
|
||||
if (on != !!was || (ep && ep != last_endpoint[id]))
|
||||
if (on != !!was || (ep && ep != last_endpoint[id] && !flapping))
|
||||
people[dev.person] = true;
|
||||
last_online[id] = on;
|
||||
if (ep)
|
||||
@@ -350,7 +493,29 @@ function watch() {
|
||||
delete last_online[id];
|
||||
delete last_endpoint[id];
|
||||
delete last_hs[id];
|
||||
delete last_key[id];
|
||||
}
|
||||
for (let id in keys(link_hist))
|
||||
if (!m.devices[id]) {
|
||||
if (link_hist[id].state != null)
|
||||
link_dirty = true;
|
||||
if (link_hist[id].setup != null)
|
||||
setup_dirty = true;
|
||||
delete link_hist[id];
|
||||
}
|
||||
if (link_dirty) {
|
||||
write_json(live.LINK, link.shown(link_hist), 0o600);
|
||||
link_dirty = false;
|
||||
}
|
||||
// The portal's set-up sheet polls for it: no revision moves with it.
|
||||
if (setup_dirty) {
|
||||
write_json(live.SETUP, link.setups(link_hist), 0o600);
|
||||
setup_dirty = false;
|
||||
}
|
||||
// Merged per device for an hour: a link that keeps failing and coming back is one line.
|
||||
for (let e in failing)
|
||||
live.add_event_merged(e, 3600);
|
||||
watch_meter(m, d, now);
|
||||
if (!length(keys(people)))
|
||||
return;
|
||||
save_presence(keys(people));
|
||||
@@ -515,8 +680,9 @@ function check_usage_reset(m) {
|
||||
* Push devices and access rules when people's states changed, the config
|
||||
* file was written (by anyone: rpcd, the portal, the CLI, a restore), 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.
|
||||
* device reach everything, so the sync unloads them until it is back), a
|
||||
* running tunnel holds other devices than it should (check_peers), or every
|
||||
* RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
|
||||
*/
|
||||
function sync_runtime(t) {
|
||||
// uci commits replace the file: a new inode even within the same second.
|
||||
@@ -525,13 +691,32 @@ function sync_runtime(t) {
|
||||
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
|
||||
(conf_mtime != null && mt != conf_mtime);
|
||||
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
|
||||
apply.sync(t.m, usage);
|
||||
last_peers = apply.sync(t.m, usage).peers ?? {};
|
||||
last_sync = time();
|
||||
}
|
||||
conf_mtime = mt;
|
||||
last_states = t.states;
|
||||
}
|
||||
|
||||
/*
|
||||
* A running tunnel without all of its devices, or with ones it should not
|
||||
* have (set up again before its hotplug sync ran, an `awg set` by hand): the
|
||||
* sync runs on this tick, not up to RESYNC_EVERY later. By the same choice
|
||||
* of devices the sync makes (and Health compares); only where the agent's
|
||||
* last sync took: a server that refuses its devices has said so in the
|
||||
* service log and keeps the slower pace.
|
||||
*/
|
||||
function check_peers(t) {
|
||||
for (let id, srv in t.m.servers) {
|
||||
let last = last_peers[id] ?? 'ok';
|
||||
if (t.dmp?.reads?.[srv.ifname] != 'read' || (last != 'ok' && last != 'down'))
|
||||
continue;
|
||||
let diff = awg.peer_diff(awg.tunnel_devices(t.m, id, t.states), t.dmp, srv.ifname);
|
||||
if (diff.missing || diff.extra)
|
||||
last_sync = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The router's network changed under us: re-derive everything. Only a change
|
||||
* seen on two ticks in a row (a bridge recreated or an interface restarting
|
||||
@@ -568,7 +753,8 @@ const STEPS = [
|
||||
} },
|
||||
{ who: L_('Traffic'), run: (t) => {
|
||||
t.reset = check_usage_reset(t.m);
|
||||
live.collect(t.m, usage, live.dump(t.m));
|
||||
t.dmp = live.dump(t.m);
|
||||
live.collect(t.m, usage, t.dmp);
|
||||
} },
|
||||
{ who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) },
|
||||
{ who: L_('People'), run: (t) => {
|
||||
@@ -577,8 +763,10 @@ const STEPS = [
|
||||
check_expiry(t.m, t.events);
|
||||
} },
|
||||
{ who: L_('Access rules'), run: (t) => {
|
||||
if (t.states)
|
||||
sync_runtime(t);
|
||||
if (!t.states)
|
||||
return;
|
||||
check_peers(t);
|
||||
sync_runtime(t);
|
||||
} },
|
||||
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
|
||||
{ who: L_('Activity'), run: (t) => {
|
||||
@@ -624,7 +812,7 @@ function tick() {
|
||||
}
|
||||
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
|
||||
usage = live.load_usage();
|
||||
let t = { m: null, pol: null, reset: false, events: [] };
|
||||
let t = { m: null, pol: null, reset: false, events: [], dmp: null };
|
||||
for (let i, s in STEPS)
|
||||
if (i == 0 || t.m)
|
||||
step(i, s, () => s.run(t));
|
||||
@@ -652,6 +840,8 @@ function shutdown() {
|
||||
live.persist_events();
|
||||
geo.flush();
|
||||
slog_trim(true);
|
||||
// The live meter's file goes with it: a stopped agent's points are no speed now.
|
||||
meter.stop();
|
||||
// A clean stop: the next start is not a crash.
|
||||
unlink(watchdog.BEAT);
|
||||
}
|
||||
@@ -686,6 +876,9 @@ else if (live.uptime() < 600)
|
||||
slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
|
||||
else
|
||||
slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline');
|
||||
// A module Dawnline did not install has no record of its kernel: without one
|
||||
// Health cannot tell a firmware upgrade from a missing module.
|
||||
builds.adopt();
|
||||
|
||||
uloop.init();
|
||||
|
||||
|
||||
@@ -24,6 +24,25 @@ import * as pkgs from 'dawnline.upd_pkgs';
|
||||
import * as i18n from 'dawnline.i18n';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
|
||||
const USAGE = `Usage:
|
||||
updater check [app|amneziawg|packages]
|
||||
updater install app | app@<tag> | app:reinstall | app:rollback
|
||||
updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
|
||||
updater install pkgs:<name,…>
|
||||
updater auto
|
||||
`;
|
||||
|
||||
// No command, one it doesn't know, or an install of nothing: the usage and exit, before anything is read or
|
||||
// written (no job for Components, no history, nothing in the service log). Asked for help: the same, on stdout.
|
||||
if (index([ '-h', '--help', 'help' ], ARGV[0]) >= 0) {
|
||||
print(USAGE);
|
||||
exit(0);
|
||||
}
|
||||
if (index([ 'check', 'install', 'auto' ], ARGV[0]) < 0 || (ARGV[0] == 'install' && !length(ARGV[1] ?? ''))) {
|
||||
warn(USAGE);
|
||||
exit(2);
|
||||
}
|
||||
|
||||
// The phases and errors of a job LuCI started are in the admin's language (rpc/updates.uc hands it over).
|
||||
i18n.use(getenv('DAWNLINE_LANG'));
|
||||
|
||||
@@ -313,7 +332,7 @@ function main() {
|
||||
else if (job.action == 'auto')
|
||||
auto();
|
||||
else
|
||||
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
|
||||
die(USAGE);
|
||||
job.state = 'done';
|
||||
phase(_('Finished'));
|
||||
}
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
Geist and Geist Mono are licensed under the SIL Open Font License, Version 1.1.
|
||||
Copyright (c) 2023 Vercel, in collaboration with basement.studio.
|
||||
https://github.com/vercel/geist-font/blob/main/OFL.txt
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><style>.t{fill:#0a0a0a}.g{fill:#fff}@media (prefers-color-scheme:dark){.t{fill:#fff}.g{fill:#0a0a0a}}</style><rect class="t" width="64" height="64" rx="16"/><path class="g" d="M14 38a18 18 0 0 1 36 0z"/><rect class="g" x="12" y="43" width="40" height="4" rx="2" opacity=".5"/></svg>
|
||||
|
Before Width: | Height: | Size: 343 B |
@@ -1 +0,0 @@
|
||||
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
|
||||
@@ -1,6 +0,0 @@
|
||||
"use strict";(()=>{var li=Object.create;var tr=Object.defineProperty;var ci=Object.getOwnPropertyDescriptor;var di=Object.getOwnPropertyNames;var ui=Object.getPrototypeOf,pi=Object.prototype.hasOwnProperty;var fi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var hi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of di(t))!pi.call(e,o)&&o!==n&&tr(e,o,{get:()=>t[o],enumerable:!(r=ci(t,o))||r.enumerable});return e};var mi=(e,t,n)=>(n=e!=null?li(ui(e)):{},hi(t||!e||!e.__esModule?tr(n,"default",{value:e,enumerable:!0}):n,e));var Ur=fi((zr,Kr)=>{"use strict";var Wr=(function(){var e=function(d,v){var a=236,h=17,p=d,A=n[v],u=null,l=0,E=null,x=[],C={},I=function(w,k){l=p*4+17,u=(function(y){for(var L=new Array(y),S=0;S<y;S+=1){L[S]=new Array(y);for(var H=0;H<y;H+=1)L[S][H]=null}return L})(l),G(0,0),G(l-7,0),G(0,l-7),re(),J(),ue(w,k),p>=7&&le(w),E==null&&(E=ie(p,A,x)),Y(E,k)},G=function(w,k){for(var y=-1;y<=7;y+=1)if(!(w+y<=-1||l<=w+y))for(var L=-1;L<=7;L+=1)k+L<=-1||l<=k+L||(0<=y&&y<=6&&(L==0||L==6)||0<=L&&L<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=L&&L<=4?u[w+y][k+L]=!0:u[w+y][k+L]=!1)},V=function(){for(var w=0,k=0,y=0;y<8;y+=1){I(!0,y);var L=o.getLostPoint(C);(y==0||w>L)&&(w=L,k=y)}return k},J=function(){for(var w=8;w<l-8;w+=1)u[w][6]==null&&(u[w][6]=w%2==0);for(var k=8;k<l-8;k+=1)u[6][k]==null&&(u[6][k]=k%2==0)},re=function(){for(var w=o.getPatternPosition(p),k=0;k<w.length;k+=1)for(var y=0;y<w.length;y+=1){var L=w[k],S=w[y];if(u[L][S]==null)for(var H=-2;H<=2;H+=1)for(var K=-2;K<=2;K+=1)H==-2||H==2||K==-2||K==2||H==0&&K==0?u[L+H][S+K]=!0:u[L+H][S+K]=!1}},le=function(w){for(var k=o.getBCHTypeNumber(p),y=0;y<18;y+=1){var L=!w&&(k>>y&1)==1;u[Math.floor(y/3)][y%3+l-8-3]=L}for(var y=0;y<18;y+=1){var L=!w&&(k>>y&1)==1;u[y%3+l-8-3][Math.floor(y/3)]=L}},ue=function(w,k){for(var y=A<<3|k,L=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var H=!w&&(L>>S&1)==1;S<6?u[S][8]=H:S<8?u[S+1][8]=H:u[l-15+S][8]=H}for(var S=0;S<15;S+=1){var H=!w&&(L>>S&1)==1;S<8?u[8][l-S-1]=H:S<9?u[8][15-S-1+1]=H:u[8][15-S-1]=H}u[l-8][8]=!w},Y=function(w,k){for(var y=-1,L=l-1,S=7,H=0,K=o.getMaskFunction(k),W=l-1;W>0;W-=2)for(W==6&&(W-=1);;){for(var X=0;X<2;X+=1)if(u[L][W-X]==null){var se=!1;H<w.length&&(se=(w[H]>>>S&1)==1);var U=K(L,W-X);U&&(se=!se),u[L][W-X]=se,S-=1,S==-1&&(H+=1,S=7)}if(L+=y,L<0||l<=L){L-=y,y=-y;break}}},ee=function(w,k){for(var y=0,L=0,S=0,H=new Array(k.length),K=new Array(k.length),W=0;W<k.length;W+=1){var X=k[W].dataCount,se=k[W].totalCount-X;L=Math.max(L,X),S=Math.max(S,se),H[W]=new Array(X);for(var U=0;U<H[W].length;U+=1)H[W][U]=255&w.getBuffer()[U+y];y+=X;var ye=o.getErrorCorrectPolynomial(se),be=c(H[W],ye.getLength()-1),Xn=be.mod(ye);K[W]=new Array(ye.getLength()-1);for(var U=0;U<K[W].length;U+=1){var Zn=U+Xn.getLength()-K[W].length;K[W][U]=Zn>=0?Xn.getAt(Zn):0}}for(var er=0,U=0;U<k.length;U+=1)er+=k[U].totalCount;for(var bn=new Array(er),Nt=0,U=0;U<L;U+=1)for(var W=0;W<k.length;W+=1)U<H[W].length&&(bn[Nt]=H[W][U],Nt+=1);for(var U=0;U<S;U+=1)for(var W=0;W<k.length;W+=1)U<K[W].length&&(bn[Nt]=K[W][U],Nt+=1);return bn},ie=function(w,k,y){for(var L=m.getRSBlocks(w,k),S=g(),H=0;H<y.length;H+=1){var K=y[H];S.put(K.getMode(),4),S.put(K.getLength(),o.getLengthInBits(K.getMode(),w)),K.write(S)}for(var W=0,H=0;H<L.length;H+=1)W+=L[H].dataCount;if(S.getLengthInBits()>W*8)throw"code length overflow. ("+S.getLengthInBits()+">"+W*8+")";for(S.getLengthInBits()+4<=W*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=W*8||(S.put(a,8),S.getLengthInBits()>=W*8));)S.put(h,8);return ee(S,L)};C.addData=function(w,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=f(w);break;case"Alphanumeric":y=T(w);break;case"Byte":y=M(w);break;case"Kanji":y=b(w);break;default:throw"mode:"+k}x.push(y),E=null},C.isDark=function(w,k){if(w<0||l<=w||k<0||l<=k)throw w+","+k;return u[w][k]},C.getModuleCount=function(){return l},C.make=function(){if(p<1){for(var w=1;w<40;w++){for(var k=m.getRSBlocks(w,A),y=g(),L=0;L<x.length;L++){var S=x[L];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),w)),S.write(y)}for(var H=0,L=0;L<k.length;L++)H+=k[L].dataCount;if(y.getLengthInBits()<=H*8)break}p=w}I(!1,V())},C.createTableTag=function(w,k){w=w||2,k=typeof k=="undefined"?w*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var L=0;L<C.getModuleCount();L+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+w+"px;",y+=" height: "+w+"px;",y+=" background-color: ",y+=C.isDark(L,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(w,k,y,L){var S={};typeof arguments[0]=="object"&&(S=arguments[0],w=S.cellSize,k=S.margin,y=S.alt,L=S.title),w=w||2,k=typeof k=="undefined"?w*4:k,y=typeof y=="string"?{text:y}:y|Line truncated
|
||||
`}return y%2&&w>0?be.substring(0,be.length-y-1)+Array(y+1).join("▀"):be.substring(0,be.length-1)};return C.createASCII=function(w,k){if(w=w||1,w<2)return Bt(k);w-=1,k=typeof k=="undefined"?w*2:k;var y=C.getModuleCount()*w+k*2,L=k,S=y-k,H,K,W,X,se=Array(w+1).join("██"),U=Array(w+1).join(" "),ye="",be="";for(H=0;H<y;H+=1){for(W=Math.floor((H-L)/w),be="",K=0;K<y;K+=1)X=1,L<=K&&K<S&&L<=H&&H<S&&C.isDark(W,Math.floor((K-L)/w))&&(X=0),be+=X?se:U;for(W=0;W<w;W+=1)ye+=be+`
|
||||
`}return ye.substring(0,ye.length-1)},C.renderTo2dContext=function(w,k){k=k||2;for(var y=C.getModuleCount(),L=0;L<y;L++)for(var S=0;S<y;S++)w.fillStyle=C.isDark(L,S)?"black":"white",w.fillRect(L*k,S*k,k,k)},C};e.stringToBytesFuncs={default:function(d){for(var v=[],a=0;a<d.length;a+=1){var h=d.charCodeAt(a);v.push(h&255)}return v}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(d,v){var a=(function(){for(var p=D(d),A=function(){var J=p.read();if(J==-1)throw"eof";return J},u=0,l={};;){var E=p.read();if(E==-1)break;var x=A(),C=A(),I=A(),G=String.fromCharCode(E<<8|x),V=C<<8|I;l[G]=V,u+=1}if(u!=v)throw u+" != "+v;return l})(),h=63;return function(p){for(var A=[],u=0;u<p.length;u+=1){var l=p.charCodeAt(u);if(l<128)A.push(l);else{var E=a[p.charAt(u)];typeof E=="number"?(E&255)==E?A.push(E):(A.push(E>>>8),A.push(E&255)):A.push(h)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,a=7973,h=21522,p={},A=function(u){for(var l=0;u!=0;)l+=1,u>>>=1;return l};return p.getBCHTypeInfo=function(u){for(var l=u<<10;A(l)-A(v)>=0;)l^=v<<A(l)-A(v);return(u<<10|l)^h},p.getBCHTypeNumber=function(u){for(var l=u<<12;A(l)-A(a)>=0;)l^=a<<A(l)-A(a);return u<<12|l},p.getPatternPosition=function(u){return d[u-1]},p.getMaskFunction=function(u){switch(u){case r.PATTERN000:return function(l,E){return(l+E)%2==0};case r.PATTERN001:return function(l,E){return l%2==0};case r.PATTERN010:return function(l,E){return E%3==0};case r.PATTERN011:return function(l,E){return(l+E)%3==0};case r.PATTERN100:return function(l,E){return(Math.floor(l/2)+Math.floor(E/3))%2==0};case r.PATTERN101:return function(l,E){return l*E%2+l*E%3==0};case r.PATTERN110:return function(l,E){return(l*E%2+l*E%3)%2==0};case r.PATTERN111:return function(l,E){return(l*E%3+(l+E)%2)%2==0};default:throw"bad maskPattern:"+u}},p.getErrorCorrectPolynomial=function(u){for(var l=c([1],0),E=0;E<u;E+=1)l=l.multiply(c([1,s.gexp(E)],0));return l},p.getLengthInBits=function(u,l){if(1<=l&&l<10)switch(u){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+u}else if(l<27)switch(u){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+u}else if(l<41)switch(u){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+u}else throw"type:"+l},p.getLostPoint=function(u){for(var l=u.getModuleCount(),E=0,x=0;x<l;x+=1)for(var C=0;C<l;C+=1){for(var I=0,G=u.isDark(x,C),V=-1;V<=1;V+=1)if(!(x+V<0||l<=x+V))for(var J=-1;J<=1;J+=1)C+J<0||l<=C+J||V==0&&J==0||G==u.isDark(x+V,C+J)&&(I+=1);I>5&&(E+=3+I-5)}for(var x=0;x<l-1;x+=1)for(var C=0;C<l-1;C+=1){var re=0;u.isDark(x,C)&&(re+=1),u.isDark(x+1,C)&&(re+=1),u.isDark(x,C+1)&&(re+=1),u.isDark(x+1,C+1)&&(re+=1),(re==0||re==4)&&(E+=3)}for(var x=0;x<l;x+=1)for(var C=0;C<l-6;C+=1)u.isDark(x,C)&&!u.isDark(x,C+1)&&u.isDark(x,C+2)&&u.isDark(x,C+3)&&u.isDark(x,C+4)&&!u.isDark(x,C+5)&&u.isDark(x,C+6)&&(E+=40);for(var C=0;C<l;C+=1)for(var x=0;x<l-6;x+=1)u.isDark(x,C)&&!u.isDark(x+1,C)&&u.isDark(x+2,C)&&u.isDark(x+3,C)&&u.isDark(x+4,C)&&!u.isDark(x+5,C)&&u.isDark(x+6,C)&&(E+=40);for(var le=0,C=0;C<l;C+=1)for(var x=0;x<l;x+=1)u.isDark(x,C)&&(le+=1);var ue=Math.abs(100*le/l/l-50)/5;return E+=ue*10,E},p})(),s=(function(){for(var d=new Array(256),v=new Array(256),a=0;a<8;a+=1)d[a]=1<<a;for(var a=8;a<256;a+=1)d[a]=d[a-4]^d[a-5]^d[a-6]^d[a-8];for(var a=0;a<255;a+=1)v[d[a]]=a;var h={};return h.glog=function(p){if(p<1)throw"glog("+p+")";return v[p]},h.gexp=function(p){for(;p<0;)p+=255;for(;p>=256;)p-=255;return d[p]},h})();function c(d,v){if(typeof d.length=="undefined")throw d.length+"/"+v;var a=(function(){for(var p=0;p<d.length&&d[p]==0;)p+=1;for(var A=new Array(d.length-p+v),u=0;u<d.length-p;u+=1)A[u]=d[u+p];return A})(),h={};return h.getAt=function(p){return a[p]},h.getLength=function(){return a.length},h.multiply=function(p){for(var A=new Array(h.getLength()+p.getLength()-1),u=0;u<h.getLength();u+=1)for(var l=0;l<p.getLength();l+=1)A[u+l]^=s.gexp(s.glog(h.getAt(u))+s.glog(p.getAt(l)));return c(A,0)},h.mod=function(
Line truncated
|
||||
`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},m={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(c),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(m.dns1=n.dns[0]),n.dns[1]&&(m.dns2=n.dns[1]),m}function Zi(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function es(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let n=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),r=new Uint8Array(await new t.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,e.length,!1),o.set(r,4),o}catch{return null}}async function Kn(e,t,n=!0){let r=new TextEncoder().encode(JSON.stringify(Xi(e,t))),o=n?await es(r):null;return`vpn://${Zi(o!=null?o:r)}`}var Eo=e=>e.replace(/^vpn:\/\//,"");var To=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function je(e,t={}){let n=i("div",{class:`acc${t.inset?" inset":""}`}),r=e.map((f,T)=>{var P;let M=f.body.filter(d=>!!d),b=!M.length,O=[f.icon,i("span",{class:"acc-title"},i("span",{class:"t"},f.title),(P=f.tag)!=null?P:null),f.val?i("span",{class:`acc-val${f.valHide?" hide-open":""}`},f.val):null],B=T===t.open&&!b,D=b?i("div",{class:"acc-head"},...O):i("button",{type:"button",class:"acc-head","aria-expanded":String(B),onclick:()=>g(R)},...O,z("chevron","i acc-chev")),R=i("div",{class:`acc-row${b?" still":""}${B?" open":""}`},D,i("div",{class:"acc-body"},...M));return n.appendChild(R),R}),o=f=>f.querySelector(".acc-body"),s=()=>r.forEach((f,T)=>{let M=f.classList.contains("open");f.classList.toggle("rt",T===0||M||r[T-1].classList.contains("open")),f.classList.toggle("rb",T===r.length-1||M||r[T+1].classList.contains("open"))}),c=f=>{let T=getComputedStyle(f),M={};for(let b of To)M[b]=b==="height"?`${f.getBoundingClientRect().height}px`:T[b];return M},m=()=>r.forEach(f=>{var T;return(T=f.querySelector("button.acc-head"))==null?void 0:T.setAttribute("aria-expanded",String(f.classList.contains("open")))});function g(f){var B;let T=r.map(c);r.forEach(D=>D.getAnimations().forEach(R=>R.cancel())),r.forEach(D=>o(D).getAnimations().forEach(R=>R.cancel()));let M=!f.classList.contains("open"),b=r.filter(D=>D.classList.contains("open")&&(D===f||M));r.forEach(D=>{D.classList.remove("closing"),D!==f&&D.classList.remove("open")}),f.classList.toggle("open",M),s();let O=yt();r.forEach((D,R)=>{let P=c(D);To.some(d=>T[R][d]!==P[d])&&(b.includes(D)&&D.classList.add("closing"),$(D,[T[R],P],{duration:Ae.duration,easing:Ae.easing}).onfinish=()=>D.classList.remove("closing"))}),b.forEach(D=>$(o(D),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:Z,fill:"forwards"})),M&&$(o(f),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),bt(O),m(),(B=t.onToggle)==null||B.call(t,r.indexOf(f),M,!1)}return s(),{el:n,openIndex:()=>r.findIndex(f=>f.classList.contains("open")),setOpen(f){r.forEach((T,M)=>T.classList.toggle("open",M===f&&!T.classList.contains("still"))),s(),m(),r.forEach((T,M)=>{var b;return(b=t.onToggle)==null?void 0:b.call(t,M,T.classList.contains("open"),!0)})}}}function Lo(e,t,n){let r=i("span",{class:"seg-pill"}),o=i("div",{class:"seg appseg",role:"tablist"},r),s=e.map(b=>{let O=i("button",{type:"button",class:"seg-b",role:"tab","aria-label":b.label,title:b.label,onclick:()=>M(b.value)},z(b.icon),i("span",{class:"seg-l"},b.label));return O.dataset.v=b.value,o.appendChild(O),O}),c=b=>b.querySelector(".seg-l"),m=()=>s.forEach(b=>{let O=b.dataset.v===t;b.classList.toggle("on",O),b.setAttribute("aria-selected",String(O))}),g=()=>{let b=s.find(O=>O.dataset.v===t);return b&&b.offsetWidth?[b.offsetLeft,o.clientWidth-b.offsetLeft-b.offsetWidth]:null},f=()=>{let b=g();b&&(r.style.left=`${b[0]}px`,r.style.right=`${b[1]}px`)},T=0;function M(b){if(b===t)return;let O=s.findIndex(C=>C.dataset.v===t),B=s.findIndex(C=>C.dataset.v===b),D=getComputedStyle(r),R=parseFloat(D.left)||0,P=parseFloat(D.right)||0,d=s.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),v=c(s[O]),a=v.getBoundingClientRect().width;[...s,...s.map(c)].forEach(C=>C.getAnimations().forEach(I=>I.cancel())),t=b,m(),s.forEach((C,I)=>{let G=I===B?1:0;d[I]!==G&&$(C,[{flexGrow:d[I]},{flexGrow:G}],{duration:q.duration,easing:q.easing})}),$(v,[{opacity:1,maxWidth:`${a}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),$(c(s[B]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:j,fill:"backwards"});let h=B>O,p=Se()?q:hr,A=performance.now(),u=Math.m
Line truncated
|
||||
`).flatMap((f,T)=>T?[`
|
||||
`,So(f,t)]:[So(f,t)]));r();let o=!!Ze(e.filename,e.conf),s=i("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,s.replaceChildren(z(t?"x":"key"),i("span",{},t?_("Hide key"):_("Show key"))),r(),n.querySelectorAll(".mask, .k").forEach(f=>$(f,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:j}))}},z("key"),i("span",{},_("Show key"))),c=i("button",{type:"button",class:"btn soft sm",onclick:f=>he(e.conf,_("Configuration copied"),f.currentTarget)},z("copy"),i("span",{class:"lbl"},_("Copy"))),m=i("div",{class:"filecard"},i("div",{class:"fc-row"},i("span",{class:"filecard-ic"},".conf"),i("span",{class:"t"},i("span",{class:"mono"},e.filename),i("span",{},_("For computers and routers")))),i("button",{type:"button",class:"btn accent sm block",onclick:()=>Tt(e.filename,e.conf)},z(o?"open":"download"),i("span",{},o?_("Share file"):_("Download")))),g=je([{icon:Q("file"),title:_("Configuration"),body:[i("div",{class:"confbar"},s,c),n]}],{inset:!0});return i("div",{class:"step-box"},m,g.el)}function Io(e){let t=i("span",{class:"osm-p"},ce[e]),n=ao(Ct(e,"ios"),Ct(e,"android"));return{el:i("span",{class:"scanline"},i("span",{},...Ke(_("In %s:"),t)),n.el),set(r){te(t,ce[r],void 0,{whole:!0}),n.set(Ct(r,"ios"),Ct(r,"android"))}}}function Go(e){let t=i("span",{class:"tt"}),n=i("span",{class:"tt-m"}),r=i("span",{class:"hp-tip","aria-hidden":"true"},t,n),o=i("button",{type:"button",class:"hp-b",onclick:()=>Tt(e().file,e().text)},z("download")),s=i("button",{type:"button",class:"hp-b"},z("copy")),c=i("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},o,s,r),m=null,g=0,f=0,T=a=>{var h;return a===s&&s.classList.contains("done")?_("Copied"):(h=a.getAttribute("aria-label"))!=null?h:""},M=(a,h)=>{n.textContent=h;let p=n.offsetWidth+20;return Math.min(a.offsetLeft+a.offsetWidth/2,c.offsetWidth+46-p/2)},b=a=>`translateX(${a}px) translateX(-50%)`,O=a=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(p=>p.cancel()),r.style.transform=b(a),$(r,[{transform:h},{transform:b(a)}],{duration:q.duration,easing:q.easing})},B=a=>te(t,a),D=a=>{if(clearTimeout(g),m===a&&r.classList.contains("on"))return;if(m=a,r.classList.contains("on")){let p=T(a);return O(M(a,p)),B(p)}let h=()=>{let p=T(a);Ne(t,p);let A=M(a,p);r.getAnimations().forEach(u=>u.cancel()),r.style.transform=b(A),r.classList.add("on"),$(r,[{opacity:0,transform:`${b(A)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:b(A),filter:"blur(0px)"}],{duration:220,easing:j})};performance.now()<f?h():g=window.setTimeout(h,420)},R=()=>{clearTimeout(g),m=null,r.classList.contains("on")&&(f=performance.now()+500,r.classList.remove("on"),$(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let a of[o,s])a.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&D(a)}),a.addEventListener("focus",()=>{a.matches(":focus-visible")&&D(a)}),a.addEventListener("blur",R);c.addEventListener("pointerleave",R);let P=a=>{let h=z(a);s.querySelector("svg").replaceWith(h),$(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:xe.duration,easing:xe.easing})},d=()=>{if(m!==s||!r.classList.contains("on"))return;let a=T(s);O(M(s,a)),B(a)},v=0;return s.addEventListener("click",()=>{let a=e();he(a.text,a.msg),clearTimeout(v),s.classList.contains("done")||(s.classList.add("done"),P("check"),d()),v=window.setTimeout(()=>{s.classList.remove("done"),P("copy"),d()},1600)}),{el:c,sync(){let a=e().app;o.setAttribute("aria-label",N(_("Download %s config"),a)),s.setAttribute("aria-label",N(_("Copy %s config"),a))}}}function zo(e){let t=i("b",{},_("Waiting for the connection")),n=i("span",{class:"ws",hidden:!0}),r=i("div",{class:"way",role:"status","aria-live":"polite"},i("div",{class:"way-row"},i("span",{class:"way-end"},z(e.kind)),i("span",{class:"way-track"},i("span",{class:"way-glow"},i("i")),i("span",{class:"way-fill"})),i("span",{class:"way-end home"},z("server"))),i("div",{class:"way-text"},i("span",{class:"t"},t,n)));return{el:r,connected(){r.classList.add("done"),te(t,N(_("%s connected"),e.name))},gaveUp(){r.classList.add("stopped"),te(t,_("No connection yet")),n.textContent=_("Close this and open it again to keep checking."),n.hidden=!1,$(t.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:j})}}}function Ko(e,t=4){window.setTimeout(async()=>{var n;try{let r=await fe("state");ke(r),At()||Ee(),!((n=r.person.devices.find(o=>o.id===e))!=null&&n.online)&&t>1&&Ko(e,t-1)}catch{}},1500)}function Uo(e,t,n){let r=ct(),o=0,s=0,c=!1,m=Date.now(),g=async()=>{if(o=0,!c){if(Date.now()-m>6e5){c=!0,n();return}if(document.hidden)return f();try{let M=await fe("state");ke(M);let b=M.person.devices.find(O=>O.id===e.id);if(b&&b.handshake>r){c=!0,t(),b.online||Ko(e.id);return}}catch(M){if(jt(M)){c=!0;return}}s++,f()}},f=()=>{!c&&!o&&(o=window.setTimeout(g,s<6?5e3:s<12?15e3:3e4))},T=()=>{!document.hidden&&!c&&!o&&g(
Line truncated
|
||||
@@ -9,7 +9,7 @@ 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', 'HTTP_ACCEPT_LANGUAGE',
|
||||
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING',
|
||||
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
|
||||
'HTTP_CF_CONNECTING_IP' ])
|
||||
env[k] = getenv(k);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
"luci.dawnline": [
|
||||
"rev",
|
||||
"status",
|
||||
"meter",
|
||||
"setup_defaults",
|
||||
"health",
|
||||
"service_log",
|
||||
|
||||
@@ -115,9 +115,9 @@ function peer_of(dmp, d) {
|
||||
return dmp.peers[d.public_key];
|
||||
}
|
||||
|
||||
/** What the device sends to the router: its configuration's AllowedIPs. */
|
||||
/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */
|
||||
function routed(m, srv, p, d) {
|
||||
return awg.allowed_ips(m, srv, p);
|
||||
return awg.allowed_ips(m, srv, p, d);
|
||||
}
|
||||
|
||||
/** The home network (interface) of a server that holds an address. */
|
||||
@@ -204,6 +204,12 @@ function from_device(m, d, t, states, dmp, snap) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
// A device that keeps its own local network out of the tunnel (lan_bypass;
|
||||
// Home only is the same either way) sends a private address there, router
|
||||
// or home address alike: it never reaches this router's rules.
|
||||
if (d.lan_bypass && p.access != 'lan' && !in_nets(t.ip, allowed))
|
||||
return stop(steps, via(t.ip));
|
||||
|
||||
// The router itself.
|
||||
if (index(router_addrs(snap), t.ip) >= 0) {
|
||||
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
|
||||
@@ -301,17 +307,20 @@ function to_device(m, ip, d, states, dmp, snap) {
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */
|
||||
export function check(m, from, to) {
|
||||
/**
|
||||
* `from` and `to`: a device id, or an IPv4 address (optionally :port).
|
||||
* `ctx` = { states, dmp, snap } (a test's own); read from the router when not
|
||||
* given. Returns { ok, steps: [{ ok, title, detail }] }.
|
||||
*/
|
||||
export function check(m, from, to, ctx) {
|
||||
let a = parse_target(m, from), b = parse_target(m, to);
|
||||
if (!a)
|
||||
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
|
||||
if (!b)
|
||||
die(sprintf(_('"%s" is not a device or an IPv4 address.'), to));
|
||||
let usage = core.load_usage();
|
||||
let states = view.states(m, usage);
|
||||
let dmp = live.dump(m);
|
||||
let snap = net.snapshot(true);
|
||||
let states = ctx?.states ?? view.states(m, core.load_usage());
|
||||
let dmp = ctx?.dmp ?? live.dump(m);
|
||||
let snap = ctx?.snap ?? net.snapshot(true);
|
||||
let steps;
|
||||
if (a.dev)
|
||||
steps = from_device(m, a.dev, b, states, dmp, snap);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
|
||||
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
|
||||
// tunnel, its peers (`awg syncconf`, no restart), live counters, the words for
|
||||
// why a tunnel is kept down (blocked_text) and what the watchdog and Health
|
||||
// check about it. Plain WireGuard is AmneziaWG with the disguise off.
|
||||
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation) and the values
|
||||
// AmneziaWG refuses, client configurations (.conf, AmneziaVPN key), the
|
||||
// netifd options of a server's tunnel, its peers (`awg syncconf`, no
|
||||
// restart), live counters, the words for why a tunnel is kept down
|
||||
// (blocked_text) and what the watchdog and Health check about it. Plain
|
||||
// WireGuard is AmneziaWG with the disguise off.
|
||||
|
||||
import { readfile, stat, unlink } from 'fs';
|
||||
import {
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import { ipv6_groups } from 'dawnline.schema';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import { _, L_ } from 'dawnline.i18n';
|
||||
@@ -28,6 +30,9 @@ export const OBF_CONF = {
|
||||
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
|
||||
/** The packages AmneziaWG comes in (the Components tab installs them). */
|
||||
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
|
||||
// A module constant, compiled once (a literal is compiled each time it runs):
|
||||
// dump() checks it on every line of each tunnel's `awg show <ifname> dump`, every second.
|
||||
const DIGITS = /^[0-9]+$/;
|
||||
|
||||
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
|
||||
function proto_handler() {
|
||||
@@ -135,7 +140,9 @@ function rand_h(used) {
|
||||
}
|
||||
}
|
||||
|
||||
// caps() answers from here while the tool, the protocol script and the module file are the same.
|
||||
// caps() answers from here while the tool, the protocol script, the module
|
||||
// file, the install record and the loaded module are the same (tmpfs: a
|
||||
// reboot starts over).
|
||||
const CAPS = `${RUN_DIR}/awg-caps.json`;
|
||||
|
||||
/**
|
||||
@@ -143,15 +150,20 @@ const CAPS = `${RUN_DIR}/awg-caps.json`;
|
||||
* 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):
|
||||
* configure header protection that the kernel silently lacks). While an
|
||||
* update waits for a reboot (its old module stayed loaded) the kernel runs
|
||||
* the generation from before it, as the install recorded it:
|
||||
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
|
||||
* v3 — header protection, trailers, padding, timing (AWG 3.1)
|
||||
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
|
||||
* mismatch — the two differ
|
||||
* pending — an installed module waits for a reboot (dawnline.awg_builds)
|
||||
*/
|
||||
export function caps() {
|
||||
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 core = builds.module_core();
|
||||
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}` +
|
||||
`/${stat(builds.RECORD)?.mtime ?? 0}/${core ?? 0}`;
|
||||
let cached = read_json(CAPS, null);
|
||||
if (cached?.key == key && cached.caps)
|
||||
return cached.caps;
|
||||
@@ -160,12 +172,15 @@ export function caps() {
|
||||
let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
|
||||
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
|
||||
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
|
||||
// A module installed by hand has no package: then the tools are believed.
|
||||
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
|
||||
// A module installed by hand has no package, so no generation (also when
|
||||
// a pending update replaces it): then the tools are believed.
|
||||
let rec = read_json(builds.RECORD, null), boot = builds.boot_id();
|
||||
let kmod = builds.running_gen(rec, boot, core, 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,
|
||||
pending: builds.pending(rec, boot, core),
|
||||
};
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(CAPS, { key, caps: out }, 0o644);
|
||||
@@ -238,18 +253,24 @@ function dns_answer() {
|
||||
* offers Balanced or Maximum instead.
|
||||
*/
|
||||
export function obf_preset(name) {
|
||||
if (name == 'max')
|
||||
if (name == 'max') {
|
||||
// 32 random bytes, as `awg genkey` makes them (no process). Without
|
||||
// one the server would come up with weak or no header protection.
|
||||
let hpk = genpsk();
|
||||
if (!valid_key(hpk))
|
||||
die(_('Key generation failed (no random data).'));
|
||||
return {
|
||||
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
|
||||
s1: '12', s2: '12', s3: '12', s4: '12',
|
||||
h1: '1', h2: '2', h3: '3', h4: '4',
|
||||
i1: dns_query(), i2: dns_answer(),
|
||||
header_protection_key: sh_out('awg genkey'),
|
||||
header_protection_key: hpk,
|
||||
content_padding_addition: '10-100',
|
||||
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
|
||||
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
|
||||
random_trailers: 'on', disable_cookies: 'on',
|
||||
};
|
||||
}
|
||||
if (name == 'off')
|
||||
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
|
||||
let o = {};
|
||||
@@ -275,38 +296,222 @@ export function obf_preset(name) {
|
||||
return o;
|
||||
};
|
||||
|
||||
/* ---------- disguise values AmneziaWG refuses ---------- */
|
||||
|
||||
export function obf_errors(o) {
|
||||
// Checked with ltrim, not regexes: this module loads with every portal request.
|
||||
const DEC = '0123456789', HEX = '0123456789abcdefABCDEF';
|
||||
|
||||
/** A whole number in digits up to `top`, or null (no spaces: callers trim where the tools drop them). */
|
||||
function uint(v, top) {
|
||||
let s = `${v}`;
|
||||
if (s == '' || length(s) > 10 || ltrim(s, DEC) != '')
|
||||
return null;
|
||||
return +s <= top ? +s : null;
|
||||
}
|
||||
|
||||
/** A number or a range as AmneziaWG writes them ("5", "5-15"), each end up to `top`: [ lo, hi ], or null. */
|
||||
function uint_range(v, top) {
|
||||
let p = split(trim(`${v}`), '-');
|
||||
let lo = length(p) <= 2 ? uint(p[0], top) : null;
|
||||
let hi = length(p) == 2 ? uint(p[1], top) : lo;
|
||||
return lo != null && hi != null && lo <= hi ? [ lo, hi ] : null;
|
||||
}
|
||||
|
||||
/** Value `k` of disguise values `o` is set. */
|
||||
function given(o, k) {
|
||||
return o[k] != null && o[k] != '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Packet types H1-H4: a number or a range each, apart from the others (the
|
||||
* kernel refuses an overlap). One not given keeps WireGuard's own type, 1-4.
|
||||
*/
|
||||
function headers_unsafe(o, errs) {
|
||||
let hs = [];
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
let r = given(o, `h${i}`) ? uint_range(o[`h${i}`], 4294967295) : [ i, i ];
|
||||
if (!r)
|
||||
push(errs, sprintf(_('%s must be a number or a range like 100-200, up to 4294967295.'), OBF_CONF[`h${i}`]));
|
||||
push(hs, r);
|
||||
}
|
||||
for (let i = 0; i < 4; i++)
|
||||
for (let j = i + 1; j < 4; j++)
|
||||
if (hs[i] && hs[j] && hs[i][0] <= hs[j][1] && hs[j][0] <= hs[i][1])
|
||||
push(errs, sprintf(_('%s and %s overlap: each packet type needs values of its own.'), OBF_CONF[`h${i + 1}`], OBF_CONF[`h${j + 1}`]));
|
||||
}
|
||||
|
||||
/**
|
||||
* One tag of a signature packet as both the kernel and amneziawg-go read it:
|
||||
* <b 0x..> fixed bytes (an even number of hex digits), <r N>, <rc N>, <rd N>
|
||||
* (N random bytes, letters, digits; a negative N writes past the packet in
|
||||
* the kernel, kmod #267) or <t> (the time). <c> is the kernel's alone and
|
||||
* <d>, <ds>, <dz> amneziawg-go's: devices on the other refuse them.
|
||||
*/
|
||||
function itag_ok(tag) {
|
||||
if (tag == 't')
|
||||
return true;
|
||||
let sp = index(tag, ' ');
|
||||
if (sp < 0)
|
||||
return false;
|
||||
let key = substr(tag, 0, sp), val = substr(tag, sp + 1);
|
||||
if (key == 'b')
|
||||
return length(val) > 2 && length(val) % 2 == 0 && substr(val, 0, 2) == '0x' && ltrim(substr(val, 2), HEX) == '';
|
||||
if (key == 'r' || key == 'rc' || key == 'rd')
|
||||
return (uint(val, 1000) ?? 0) >= 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** What is wrong with signature packet `name` (I1-I5) holding `s`, as a sentence; null when nothing. */
|
||||
function itag_error(name, s) {
|
||||
// In a .conf file `#` starts a comment and a line break ends the line: the rest would be lost.
|
||||
if (index(s, '#') >= 0 || index(s, '\n') >= 0 || index(s, '\r') >= 0)
|
||||
return sprintf(_('%s may not contain # or a line break.'), name);
|
||||
// Text between tags is skipped by both parsers.
|
||||
for (let a = index(s, '<'); a >= 0; a = index(s, '<')) {
|
||||
let b = index(substr(s, a), '>');
|
||||
if (b < 0)
|
||||
return sprintf(_('%s has a tag that is not closed with >.'), name);
|
||||
let tag = substr(s, a + 1, b - 1);
|
||||
if (!itag_ok(tag))
|
||||
return sprintf(_('%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.'),
|
||||
name, length(tag) > 24 ? `${substr(tag, 0, 24)}…` : tag);
|
||||
s = substr(s, a + b + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Signature packets I1-I5: their tags, and all of them in one device's configuration (one QR code). */
|
||||
function itags_unsafe(o, errs) {
|
||||
let total = 0;
|
||||
for (let k in [ 'i1', 'i2', 'i3', 'i4', 'i5' ]) {
|
||||
if (!given(o, k))
|
||||
continue;
|
||||
total += length(`${o[k]}`);
|
||||
let e = itag_error(OBF_CONF[k], `${o[k]}`);
|
||||
if (e)
|
||||
push(errs, e);
|
||||
}
|
||||
if (total > 2000)
|
||||
push(errs, sprintf(_('I1-I5 together must be at most 2000 characters, not %d.'), total));
|
||||
}
|
||||
|
||||
/**
|
||||
* What in disguise values `o` AmneziaWG would refuse, crash on or break
|
||||
* devices with: what an import, a restore or a hand edit in uci must never
|
||||
* hand to the kernel (dawnline.backup, dawnline.netifd). Only those rules,
|
||||
* none of Dawnline's own bounds (obf_errors): a backup the kernel takes stays
|
||||
* usable. Sentences in the reader's language; [] when the values are safe.
|
||||
*/
|
||||
export function obf_unsafe(o) {
|
||||
o ??= {};
|
||||
let errs = [];
|
||||
for (let k, r in OBF_SPEC) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1])
|
||||
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
|
||||
let num = (k) => given(o, k) ? uint(trim(`${o[k]}`), 65535) : 0;
|
||||
// 16-bit numbers for the tools; Jmin above Jmax sizes junk past its buffer (kmod #225).
|
||||
for (let k in [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4' ])
|
||||
if (num(k) == null)
|
||||
push(errs, sprintf(_('%s must be a whole number from 0 to 65535.'), OBF_CONF[k]));
|
||||
if (given(o, 'jmin') && given(o, 'jmax') && num('jmin') != null && num('jmax') != null && num('jmin') > num('jmax'))
|
||||
push(errs, _('Jmin must not be larger than Jmax.'));
|
||||
headers_unsafe(o, errs);
|
||||
// Header protection: a 32-byte key, and every padding at least the 12 bytes of its nonce (the kernel checks).
|
||||
if (given(o, 'header_protection_key')) {
|
||||
if (!valid_key(o.header_protection_key))
|
||||
push(errs, _('The header protection key is not a key.'));
|
||||
for (let k in [ 's1', 's2', 's3', 's4' ])
|
||||
if (num(k) != null && num(k) < 12)
|
||||
push(errs, sprintf(_('%s must be at least 12 with header protection.'), OBF_CONF[k]));
|
||||
}
|
||||
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
|
||||
push(errs, 'jmin > jmax');
|
||||
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
|
||||
push(errs, 's1 + 56 = s2');
|
||||
let hs = {};
|
||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
|
||||
let v = o[k];
|
||||
if (v == null || v == '')
|
||||
continue;
|
||||
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
|
||||
push(errs, sprintf(_('%s must be a number or range'), k));
|
||||
else if (hs[v])
|
||||
push(errs, _('h1-h4 must be distinct'));
|
||||
hs[v] = true;
|
||||
// 3.1 timers and counts: 0 alone is the kernel's default; a 0 in a range
|
||||
// would fire at once. Keys are dropped after 180 seconds whatever is set.
|
||||
for (let k in [ 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts' ]) {
|
||||
let r = given(o, k) ? uint_range(o[k], 65535) : [ 0, 0 ];
|
||||
if (!r || (r[0] == 0 && r[1] > 0))
|
||||
push(errs, sprintf(_('%s must be a number or a range like 5-15, from 1 to 65535.'), OBF_CONF[k]));
|
||||
else if (k == 'reject_after_time' && r[1] > 180)
|
||||
push(errs, _('RejectAfterTime must be at most 180 seconds.'));
|
||||
}
|
||||
if (given(o, 'content_padding_addition') && !uint_range(o.content_padding_addition, 65535))
|
||||
push(errs, sprintf(_('%s must be a number or a range like 10-100, up to 65535.'), OBF_CONF.content_padding_addition));
|
||||
// What both netifd and the .conf parser read as a switch.
|
||||
for (let k in [ 'random_trailers', 'disable_cookies' ])
|
||||
if (given(o, k) && index([ 'on', 'off', '1', '0' ], `${o[k]}`) < 0)
|
||||
push(errs, sprintf(_('%s must be on or off.'), OBF_CONF[k]));
|
||||
itags_unsafe(o, errs);
|
||||
return errs;
|
||||
};
|
||||
|
||||
/**
|
||||
* What is wrong with the disguise values of a server Dawnline sets up: what
|
||||
* AmneziaWG refuses (obf_unsafe), and Dawnline's own bounds on top (junk that
|
||||
* stays under the path MTU, a handshake initiation and response that never
|
||||
* share a size). Its presets pass it. Sentences in the reader's language; []
|
||||
* when the values are fine.
|
||||
*/
|
||||
export function obf_errors(o) {
|
||||
o ??= {};
|
||||
let errs = obf_unsafe(o);
|
||||
for (let k, r in OBF_SPEC) {
|
||||
let n = given(o, k) ? uint(trim(`${o[k]}`), 65535) : null;
|
||||
if (n != null && (n < r[0] || n > r[1]))
|
||||
push(errs, sprintf(_('%s must be from %d to %d.'), OBF_CONF[k], r[0], r[1]));
|
||||
}
|
||||
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
|
||||
push(errs, _('S2 must not be S1 + 56: the handshake initiation and response would have the same size.'));
|
||||
return errs;
|
||||
};
|
||||
|
||||
/**
|
||||
* Disguise values `o` as anyone who may read the status sees them: all but
|
||||
* the header protection key, a secret every device of the server shares
|
||||
* (with it and the server's public key, captured traffic can be unmasked).
|
||||
* Devices get it in their own configuration (client_config).
|
||||
*/
|
||||
export function obf_public(o) {
|
||||
let out = { ...(o ?? {}) };
|
||||
delete out.header_protection_key;
|
||||
return out;
|
||||
};
|
||||
|
||||
export function allowed_ips(m, srv, p) {
|
||||
if (p.access == 'lan') {
|
||||
/*
|
||||
* Everything but a device's own local network, for a device whose local
|
||||
* network stays outside the tunnel (lan_bypass): every IPv4 address outside
|
||||
* the private ranges the access table drops for internet people anyway
|
||||
* (dawnline.nft PRIVATE4: 10/8, 172.16/12, 192.168/16, 100.64/10,
|
||||
* 169.254/16, 224/3), and every IPv6 address outside fc00::/7, fe80::/10
|
||||
* and ff00::/8. Fixed lists (tests/ucode/awg.test.uc proves each is exactly
|
||||
* that complement); what of the private ranges goes through the tunnel after
|
||||
* all (DNS, home) is added to them.
|
||||
*/
|
||||
export const BYPASS4 = [
|
||||
'0.0.0.0/5', '8.0.0.0/7', '11.0.0.0/8', '12.0.0.0/6', '16.0.0.0/4', '32.0.0.0/3', '64.0.0.0/3', '96.0.0.0/6',
|
||||
'100.0.0.0/10', '100.128.0.0/9', '101.0.0.0/8', '102.0.0.0/7', '104.0.0.0/5', '112.0.0.0/4', '128.0.0.0/3', '160.0.0.0/5',
|
||||
'168.0.0.0/8', '169.0.0.0/9', '169.128.0.0/10', '169.192.0.0/11', '169.224.0.0/12', '169.240.0.0/13', '169.248.0.0/14',
|
||||
'169.252.0.0/15', '169.255.0.0/16', '170.0.0.0/7', '172.0.0.0/12', '172.32.0.0/11', '172.64.0.0/10', '172.128.0.0/9',
|
||||
'173.0.0.0/8', '174.0.0.0/7', '176.0.0.0/4', '192.0.0.0/9', '192.128.0.0/11', '192.160.0.0/13', '192.169.0.0/16',
|
||||
'192.170.0.0/15', '192.172.0.0/14', '192.176.0.0/12', '192.192.0.0/10', '193.0.0.0/8', '194.0.0.0/7', '196.0.0.0/6',
|
||||
'200.0.0.0/5', '208.0.0.0/4',
|
||||
];
|
||||
export const BYPASS6 = [ '::/1', '8000::/2', 'c000::/3', 'e000::/4', 'f000::/5', 'f800::/6', 'fe00::/9', 'fec0::/10' ];
|
||||
|
||||
/** An IPv6 address BYPASS6 leaves out: in fc00::/7, fe80::/10 or ff00::/8 (the first 16 bits decide). False for anything else. */
|
||||
function private6(a) {
|
||||
let g = ipv6_groups(a)?.[0];
|
||||
return g != null && ((g & 0xfe00) == 0xfc00 || (g & 0xffc0) == 0xfe80 || (g & 0xff00) == 0xff00);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a device sends into the tunnel (its AllowedIPs; the server's peer
|
||||
* line stays its address/32). Home only: the person's home networks, the
|
||||
* tunnel network or the router's address, and the DNS. Internet: everything,
|
||||
* or with `dev.lan_bypass` everything but the device's own local network
|
||||
* (BYPASS4, BYPASS6), every DNS server it is given (IPv4 and IPv6) and for
|
||||
* home access what Home only gets. Without `dev`, as for a device without
|
||||
* lan_bypass.
|
||||
*/
|
||||
export function allowed_ips(m, srv, p, dev) {
|
||||
if (p.access != 'lan' && !dev?.lan_bypass)
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
let home = () => {
|
||||
let nets = core.person_home(srv, p).nets;
|
||||
// With devices reaching each other, the whole tunnel network (the router's
|
||||
// address is in it); otherwise only the router's own address.
|
||||
@@ -315,13 +520,27 @@ export function allowed_ips(m, srv, p) {
|
||||
push(nets, srv.subnet);
|
||||
else if (a)
|
||||
push(nets, `${a}/32`);
|
||||
return nets;
|
||||
};
|
||||
let dns = core.client_dns(m, srv, p);
|
||||
if (p.access == 'lan') {
|
||||
// The resolver address must be reachable through the tunnel too (not the fallback).
|
||||
let dns = core.client_dns(m, srv, p)[0];
|
||||
if (dns)
|
||||
push(nets, `${dns}/32`);
|
||||
let nets = home();
|
||||
if (dns[0])
|
||||
push(nets, `${dns[0]}/32`);
|
||||
return net.collapse(nets);
|
||||
}
|
||||
return [ '0.0.0.0/0', '::/0' ];
|
||||
// Every DNS server stays in the tunnel: a private one left out would be
|
||||
// asked on whatever network the device is on (a public one is in the rest).
|
||||
let nets = [ ...BYPASS4 ], nets6 = [];
|
||||
for (let a in dns)
|
||||
if (ip2int(a) != null)
|
||||
push(nets, `${a}/32`);
|
||||
else if (private6(a))
|
||||
push(nets6, `${a}/128`);
|
||||
if (p.access == 'both')
|
||||
push(nets, ...home());
|
||||
return [ ...net.collapse(nets), ...BYPASS6, ...uniq(nets6) ];
|
||||
};
|
||||
|
||||
|
||||
@@ -369,14 +588,56 @@ function client_obf(srv, dev) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* The keep-alive `dev` gets (its own or the server's, core.device_keepalive)
|
||||
* as [ lo, hi ] seconds; null when it is off (0). With 3.1 (header
|
||||
* protection: its apps take ranges) jittered over ten seconds like the other
|
||||
* timers, since a fixed beat would be the one regular thing left. The online
|
||||
* window follows its upper end (dawnline.live).
|
||||
*/
|
||||
export function keepalive_range(srv, dev) {
|
||||
let k = core.device_keepalive(srv, dev);
|
||||
if (!(k > 0))
|
||||
return null;
|
||||
return srv.obf?.header_protection_key ? [ k, k + 10 ] : [ k, k ];
|
||||
};
|
||||
|
||||
/**
|
||||
* The longest an idle device goes between two handshakes, in seconds; null
|
||||
* when its keep-alive is off (an idle device then sends nothing at all). Its
|
||||
* keep-alive packets are what it sends, and the first one after its key's
|
||||
* rekey time (RekeyAfterTime, WireGuard's 120 s; past 180 s the key is
|
||||
* refused anyway) starts a handshake (kmod send.c keep_key_fresh): up to one
|
||||
* keep-alive past that time, or each keep-alive once they are further apart.
|
||||
*/
|
||||
export function idle_handshake(srv, dev) {
|
||||
let ka = keepalive_range(srv, dev);
|
||||
if (!ka)
|
||||
return null;
|
||||
let rekey = min(uint_range(srv.obf?.rekey_after_time ?? '', 65535)?.[1] || 120, 180);
|
||||
return ka[0] > rekey ? ka[1] : rekey + ka[1];
|
||||
};
|
||||
|
||||
/**
|
||||
* keepalive_range() as the apps write it ("25-35", "25"); null when off. The
|
||||
* .conf and the AmneziaVPN key carry the same text (AmneziaVPN hands it on as
|
||||
* written, ranges included).
|
||||
*/
|
||||
function keepalive_text(srv, dev) {
|
||||
let r = keepalive_range(srv, dev);
|
||||
if (!r)
|
||||
return null;
|
||||
return r[0] == r[1] ? `${r[0]}` : `${r[0]}-${r[1]}`;
|
||||
}
|
||||
|
||||
export function client_config(m, dev) {
|
||||
let p = m.people[dev.person];
|
||||
let srv = p ? m.servers[p.server] : null;
|
||||
if (!srv)
|
||||
return null;
|
||||
let host = core.endpoint_host(m, srv);
|
||||
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
|
||||
let allowed = allowed_ips(m, srv, p);
|
||||
let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host;
|
||||
let allowed = allowed_ips(m, srv, p, dev);
|
||||
let dns = core.client_dns(m, srv, p);
|
||||
let mtu = core.device_mtu(srv, dev);
|
||||
let lines = [ '[Interface]' ];
|
||||
@@ -398,10 +659,9 @@ export function client_config(m, dev) {
|
||||
push(lines, `PresharedKey = ${dev.preshared_key}`);
|
||||
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
|
||||
push(lines, `Endpoint = ${ep}:${srv.port}`);
|
||||
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
|
||||
// other timers; a fixed beat would be the one regular thing left.
|
||||
if (srv.keepalive > 0)
|
||||
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`);
|
||||
let keepalive = keepalive_text(srv, dev);
|
||||
if (keepalive)
|
||||
push(lines, `PersistentKeepalive = ${keepalive}`);
|
||||
return {
|
||||
name: dev.name,
|
||||
person: p.name,
|
||||
@@ -421,7 +681,7 @@ export function client_config(m, dev) {
|
||||
client_pub_key: dev.public_key,
|
||||
psk_key: dev.preshared_key,
|
||||
server_pub_key: srv.public_key,
|
||||
persistent_keep_alive: `${srv.keepalive}`,
|
||||
persistent_keep_alive: keepalive ?? '0',
|
||||
obfuscation: obf,
|
||||
},
|
||||
};
|
||||
@@ -445,12 +705,63 @@ export function netifd_options(srv) {
|
||||
};
|
||||
for (let k in core.OBF_KEYS)
|
||||
o[`awg_${k}`] = srv.obf[k];
|
||||
// DisableCookies is the devices' alone (their .conf and key keep it): on
|
||||
// the server it would turn off WireGuard's own defence against a flood of
|
||||
// handshakes (cookie replies and a per-address limit, only ever under
|
||||
// load), and anyone who held a configuration could keep both cores busy.
|
||||
// Null takes it off an interface that had it.
|
||||
o.awg_disable_cookies = null;
|
||||
return o;
|
||||
};
|
||||
|
||||
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
|
||||
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
|
||||
|
||||
/**
|
||||
* The devices sync_peers() loads into server `sid`'s tunnel, in the model's
|
||||
* order (an empty list when none). Pure: the model and the people's states
|
||||
* (apply.states_for). Health and the agent compare a running tunnel with it.
|
||||
*/
|
||||
export function tunnel_devices(m, sid, states) {
|
||||
let out = [];
|
||||
let own = m.servers?.[sid]?.public_key;
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
// One malformed line makes syncconf refuse the whole server: such a device
|
||||
// stays out (Health's Data check names it), and so does one with the
|
||||
// server's own key, which the kernel silently ignores (it would look
|
||||
// missing for ever). Over the data limit or outside the allowed hours the
|
||||
// tunnel stays: the access table blocks everything but the portal, which
|
||||
// says why (a silent handshake failure would look like a broken VPN).
|
||||
if (p && p.server == sid && !d.disabled && index(SOFT_STATES, states[p.id]) >= 0 && valid_key(d.public_key) && ip2int(d.address) != null &&
|
||||
(!own || d.public_key != own))
|
||||
push(out, d);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* How the peers dump() read on `ifname` differ from the devices that belong
|
||||
* there (tunnel_devices): { loaded, missing, extra }, counted by key, not by
|
||||
* number (a stale peer standing in for a missing one would make the numbers
|
||||
* match). Pure.
|
||||
*/
|
||||
export function peer_diff(devs, dmp, ifname) {
|
||||
let want = {};
|
||||
for (let d in devs)
|
||||
want[d.public_key] = true;
|
||||
let loaded = 0, extra = 0, found = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == ifname) {
|
||||
loaded++;
|
||||
if (want[k])
|
||||
found++;
|
||||
else
|
||||
extra++;
|
||||
}
|
||||
return { loaded, missing: length(keys(want)) - found, extra };
|
||||
};
|
||||
|
||||
/** Push the peer list of every server to the kernel without restarting it. */
|
||||
export function sync_peers(m, states) {
|
||||
ensure_dir(RUN_DIR);
|
||||
@@ -464,15 +775,7 @@ export function sync_peers(m, states) {
|
||||
continue;
|
||||
}
|
||||
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
// One malformed line makes syncconf refuse the whole server: such a device
|
||||
// stays out (Health's Data check names it). Over the data limit or
|
||||
// outside the allowed hours the tunnel stays: the access table blocks
|
||||
// everything but the portal, which says why (a silent handshake failure
|
||||
// would look like a broken VPN).
|
||||
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
|
||||
continue;
|
||||
for (let d in tunnel_devices(m, id, states)) {
|
||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||
if (d.preshared_key)
|
||||
push(lines, `PresharedKey = ${d.preshared_key}`);
|
||||
@@ -489,38 +792,83 @@ export function sync_peers(m, states) {
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
|
||||
* Lines are told apart by their shape, not their length (each AmneziaWG
|
||||
* generation adds fields to the interface line): an interface line carries
|
||||
* its private and public key and a port, a peer line the peer's key, a
|
||||
* preshared key or "(none)" and an endpoint. The tool fails when any one
|
||||
* interface can't be read, but still prints the others: with `wanted` (the
|
||||
* ifnames that matter) `ok` means those were all read, so another tunnel's
|
||||
* trouble is not ours.
|
||||
/** The interface's index while it exists (a new one each time netifd sets the tunnel up), else null. */
|
||||
function ifindex(ifname) {
|
||||
let s = trim(readfile(`/sys/class/net/${ifname}/ifindex`) ?? '');
|
||||
return s != '' ? +s : null;
|
||||
}
|
||||
|
||||
/*
|
||||
* One interface's `awg show <ifname> dump` into `out` (see dump()). Lines are
|
||||
* told apart by their shape, not their length (each AmneziaWG generation adds
|
||||
* fields to the interface line): an interface line carries its private and
|
||||
* public key and a port, a peer line the peer's key, a preshared key or
|
||||
* "(none)" and an endpoint. Unlike `show all`, the lines have no ifname.
|
||||
*/
|
||||
export function dump(wanted) {
|
||||
let r = sh('awg show all dump');
|
||||
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) < 5 || !valid_key(f[1]))
|
||||
continue;
|
||||
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
|
||||
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
|
||||
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
|
||||
let ep = f[3] == '(none)' ? '' : f[3];
|
||||
out.peers[f[1]] = {
|
||||
ifname: f[0],
|
||||
endpoint: ep,
|
||||
handshake: +f[5],
|
||||
rx: +f[6],
|
||||
tx: +f[7],
|
||||
};
|
||||
}
|
||||
function read_iface(out, ifname) {
|
||||
// Read around the call: a link set up again in between gave counters of either one.
|
||||
let before = ifindex(ifname);
|
||||
// Not there (a tunnel netifd could not bring up, AmneziaWG gone after an
|
||||
// upgrade): no process to learn it. One that appears is read next time.
|
||||
if (before == null) {
|
||||
out.reads[ifname] = 'down';
|
||||
return;
|
||||
}
|
||||
if (!out.ok && type(wanted) == 'array')
|
||||
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
|
||||
let r = sh(`awg show ${q(ifname)} dump`);
|
||||
let ix = ifindex(ifname);
|
||||
let iface = null, peers = {};
|
||||
if (r.code == 0)
|
||||
for (let line in split(r.out, '\n')) {
|
||||
let f = split(line, '\t');
|
||||
if (length(f) < 4 || !valid_key(f[0]))
|
||||
continue;
|
||||
let key2 = valid_key(f[1]);
|
||||
if (key2 && match(f[2], DIGITS))
|
||||
iface = { public_key: f[1], port: +f[2], ifindex: ix };
|
||||
else if (length(f) >= 8 && (key2 || f[1] == '(none)'))
|
||||
peers[f[0]] = {
|
||||
ifname,
|
||||
endpoint: f[2] == '(none)' ? '' : f[2],
|
||||
handshake: +f[4],
|
||||
rx: +f[5],
|
||||
tx: +f[6],
|
||||
};
|
||||
}
|
||||
let read = iface != null;
|
||||
// Gone during the read: its peers and their counters are gone with it.
|
||||
if (ix == null) {
|
||||
out.reads[ifname] = 'down';
|
||||
return;
|
||||
}
|
||||
if (!read || ix != before) {
|
||||
out.reads[ifname] = 'error';
|
||||
out.ok = false;
|
||||
return;
|
||||
}
|
||||
out.reads[ifname] = 'read';
|
||||
out.ifaces[ifname] = iface;
|
||||
for (let k, p in peers)
|
||||
out.peers[k] = p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dawnline's own tunnels, one `awg show <ifname> dump` each for `ifnames`
|
||||
* (live.tunnel_ifnames): never `all`, so another AmneziaWG interface on the
|
||||
* router (a client tunnel with long I1-I5, say) neither slows the 1-second
|
||||
* watcher down nor has its keys read. Returns { ok, reads: { ifname: 'read' |
|
||||
* 'down' | 'error' }, ifaces: { ifname: { public_key, port, ifindex } },
|
||||
* peers: { pubkey: { ifname, endpoint, handshake, rx, tx } } }, with only
|
||||
* what was read in `ifaces` and `peers`:
|
||||
* down the interface does not exist (/sys/class/net has no such link;
|
||||
* no process is started for it): its peers and counters are gone
|
||||
* error it exists but could not be read (or was set up again during the
|
||||
* read): that says nothing about its peers
|
||||
* `ok` is false when any of them is 'error' (true for an empty list).
|
||||
*/
|
||||
export function dump(ifnames) {
|
||||
let out = { ok: true, reads: {}, ifaces: {}, peers: {} };
|
||||
for (let ifn in ifnames ?? [])
|
||||
read_iface(out, ifn);
|
||||
return out;
|
||||
};
|
||||
|
||||
@@ -540,6 +888,8 @@ export function server_state(srv) {
|
||||
* { code: 'ifname', ifname } the interface name is invalid
|
||||
* { code: 'taken', ifname } network.<ifname> exists and isn't Dawnline's
|
||||
* { code: 'disguise', need, installed } obf_unsupported()
|
||||
* { code: 'disguise_invalid' } obf_unsafe() finds values AmneziaWG refuses
|
||||
* (said again from the server's values when read)
|
||||
* Files written by older versions hold the English fragment ("has an invalid
|
||||
* interface name …"), shown as it is.
|
||||
*/
|
||||
@@ -555,9 +905,20 @@ export function blocked_note(r) {
|
||||
if (r.code == 'disguise')
|
||||
return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed)
|
||||
: sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need);
|
||||
if (r.code == 'disguise_invalid')
|
||||
return L_('is kept down: its disguise has values AmneziaWG cannot take');
|
||||
return L_('is kept down');
|
||||
};
|
||||
|
||||
/** What to do about a reason (blocked_note), for the service log's details. */
|
||||
export function blocked_fix(r) {
|
||||
if (r?.code == 'disguise')
|
||||
return L_('Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
|
||||
if (r?.code == 'disguise_invalid')
|
||||
return L_('Choose a disguise on the Server page: it replaces the values set by hand.');
|
||||
return L_('Choose another interface name in the server settings.');
|
||||
};
|
||||
|
||||
/**
|
||||
* Why the server's tunnel is kept down (`srv.blocked`), as a sentence with
|
||||
* its name in the reader's language: what the admin UI shows. Null when it
|
||||
@@ -577,6 +938,9 @@ export function blocked_text(srv) {
|
||||
return r.installed
|
||||
? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed)
|
||||
: sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need);
|
||||
// Which values, from the server's own (the reason is kept as a code).
|
||||
if (r.code == 'disguise_invalid')
|
||||
return trim(sprintf(_('%s is kept down: its disguise has values AmneziaWG cannot take. %s'), srv.name, join(' ', obf_unsafe(srv.obf))));
|
||||
return sprintf(_('%s is kept down.'), srv.name);
|
||||
};
|
||||
|
||||
@@ -633,7 +997,7 @@ export function probes(m, ctx) {
|
||||
push(out, {
|
||||
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
|
||||
problem: blocked_note(why), back: L_('AmneziaWG is running again'),
|
||||
detail: () => L_('Choose another interface name in the server settings.'),
|
||||
detail: () => blocked_fix(why),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -654,6 +1018,9 @@ export function probes(m, ctx) {
|
||||
/* ---------- issued configurations ---------- */
|
||||
|
||||
const ISSUED = `${DATA_DIR}/issued.json`;
|
||||
// The lines a fingerprint leaves out. A module constant, compiled once, not
|
||||
// for each line of each device's configuration.
|
||||
const DEVICE_OWN = /^(PrivateKey|Jc|Jmin|Jmax) /;
|
||||
|
||||
function fnv32(str) {
|
||||
let h = 2166136261;
|
||||
@@ -670,7 +1037,7 @@ function fnv32(str) {
|
||||
*/
|
||||
export function config_fingerprint(m, dev) {
|
||||
let c = dev ? client_config(m, dev) : null;
|
||||
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
|
||||
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, DEVICE_OWN)))) : null;
|
||||
};
|
||||
|
||||
/** Device id → fingerprint of the configuration last shown or downloaded. */
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
|
||||
// builds per OpenWrt release and target (the kernel module must match the
|
||||
// firmware). Used by the updater and the Components RPCs.
|
||||
// firmware), and the record of what was installed on which kernel and boot
|
||||
// (an update whose module could not be swapped starts with the next boot:
|
||||
// until then caps() and Health go by the module that still runs). Used by
|
||||
// the updater, the Components RPCs, dawnline.awg and Health. Installing
|
||||
// itself is dawnline.upd_awg.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { readfile, stat } from 'fs';
|
||||
import { connect } from 'ubus';
|
||||
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
@@ -36,19 +40,52 @@ export function firmware() {
|
||||
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
|
||||
export const RECORD = `${DATA_DIR}/awg.json`;
|
||||
|
||||
/** This boot (a new one loads the module on disk), or null when the kernel does not say. */
|
||||
export function boot_id() {
|
||||
return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The size in memory of the loaded kernel module, or null when none is
|
||||
* loaded. sysfs has no version for it, but builds differ in size: a module
|
||||
* reloaded by hand ends a wait for a reboot (pending()).
|
||||
*/
|
||||
export function module_core() {
|
||||
let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? ''));
|
||||
return n > 0 ? n : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remember which build was installed on which kernel. After a firmware
|
||||
* upgrade the module is gone (it was built for that kernel): Health can then
|
||||
* say so and offer the build for the new one (dawnline.health).
|
||||
* say so and offer the build for the new one (dawnline.health). `run` comes
|
||||
* from an install: prev_gen and prev_core, the module that ran before it
|
||||
* (module_now()), and reloaded, false while that one stays loaded until the
|
||||
* next boot. null for a module Dawnline did not install (adopt()).
|
||||
*/
|
||||
export function record(source, tag, packages) {
|
||||
export function record(source, tag, packages, run) {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
write_json(RECORD, {
|
||||
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
|
||||
source, tag, packages, installed: time(),
|
||||
source, tag, packages, installed: time(), boot: boot_id(),
|
||||
prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null,
|
||||
}, 0o600);
|
||||
};
|
||||
|
||||
/**
|
||||
* A record for a module Dawnline did not install (install.sh, by hand, or
|
||||
* before Dawnline kept records), so kernel_changed() notices the next
|
||||
* firmware upgrade: the kernel it is for, source null, `installed` the time
|
||||
* Dawnline first saw it. Only when there is no record and the module is
|
||||
* loaded or on disk for the running kernel. The agent calls it when it starts.
|
||||
*/
|
||||
export function adopt() {
|
||||
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
|
||||
if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`))))
|
||||
return;
|
||||
record(null, null, null, null);
|
||||
};
|
||||
|
||||
/**
|
||||
* The firmware the recorded AmneziaWG build was for, when it is not this one
|
||||
* (and the module is gone): { was, now, tag, source }, else null.
|
||||
@@ -88,6 +125,42 @@ export function gen(version) {
|
||||
return '2.0';
|
||||
};
|
||||
|
||||
/**
|
||||
* An installed update that waits for a reboot: the install could not swap
|
||||
* the kernel module (the old one stayed loaded), this is still the boot it
|
||||
* ran in, and the module loaded is still the one from before it (core:
|
||||
* module_core() now). Pure: rec is the record or null.
|
||||
*/
|
||||
export function pending(rec, boot, core) {
|
||||
return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core;
|
||||
};
|
||||
|
||||
/**
|
||||
* The AmneziaWG generation of the kernel module that runs: the one from
|
||||
* before the install while it waits for a reboot (pending(); null when that
|
||||
* module had no package), else the installed package's version (gen()).
|
||||
* Pure, with the record, this boot and module_core() passed in.
|
||||
*/
|
||||
export function running_gen(rec, boot, core, version) {
|
||||
return pending(rec, boot, core) ? rec.prev_gen : gen(version);
|
||||
};
|
||||
|
||||
/**
|
||||
* The kernel module loaded now, taken before an install changes packages:
|
||||
* { core, gen, pending }. core is null when none is loaded; gen is what it
|
||||
* runs (running_gen(), from `version`, the kmod-amneziawg package installed
|
||||
* now); pending, an earlier update that still waits for a reboot.
|
||||
*/
|
||||
export function module_now(version) {
|
||||
let rec = read_json(RECORD, null), boot = boot_id(), core = module_core();
|
||||
return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) };
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */
|
||||
export function waits_for_reboot() {
|
||||
return pending(read_json(RECORD, null), boot_id(), module_core());
|
||||
};
|
||||
|
||||
/** The installed AmneziaWG packages: { name: version | null }. */
|
||||
export function installed() {
|
||||
let r = {};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Dawnline — backups (tar.gz of the config and its data files), restoring
|
||||
// them, and the JSON export / import. Whatever comes back in is checked first:
|
||||
// only Dawnline's own regular files, and servers that cannot take over one of
|
||||
// the router's own interfaces or networks.
|
||||
// the router's own interfaces or networks, or hand the kernel disguise values
|
||||
// AmneziaWG refuses.
|
||||
|
||||
import { readfile, stat, unlink, lsdir, rename } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
|
||||
} from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as live from 'dawnline.live';
|
||||
import * as apply from 'dawnline.apply';
|
||||
import * as net from 'dawnline.net';
|
||||
@@ -39,9 +41,10 @@ const MAX_UNPACKED = 16 * 1024 * 1024;
|
||||
/**
|
||||
* What is wrong with a configuration about to replace the current one
|
||||
* (cursor `c` holds it): each server must have a valid, unique interface
|
||||
* name that is not one of the router's own interfaces, a free subnet and a
|
||||
* unique port, and the people and devices must be consistent
|
||||
* (core.model_errors). [] when it can be used.
|
||||
* name that is not one of the router's own interfaces, a free subnet, a
|
||||
* unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the
|
||||
* people and devices must be consistent (core.model_errors). [] when it can
|
||||
* be used.
|
||||
*/
|
||||
export function config_errors(c) {
|
||||
let m = core.load(c);
|
||||
@@ -52,7 +55,7 @@ export function config_errors(c) {
|
||||
let internal = values(net.INTERNAL);
|
||||
let ifnames = {}, ports = {}, subnets = [];
|
||||
for (let id, srv in m.servers) {
|
||||
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
|
||||
for (let e in [ ...core.server_errors(m, srv, [ ...foreign, ...subnets ]), ...awg.obf_unsafe(srv.obf) ])
|
||||
push(errs, sprintf(_('Server %s: %s'), srv.name, e));
|
||||
if (ifnames[srv.ifname])
|
||||
push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import {
|
||||
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||
valid_name, valid_device_name, DEVICE_NAME_MAX, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
||||
} from 'dawnline.util';
|
||||
import { _, N_ } from 'dawnline.i18n';
|
||||
@@ -199,6 +199,13 @@ export function load(c) {
|
||||
created: toint(r.created, 0),
|
||||
created_by: r.created_by ?? 'admin',
|
||||
disabled: bool(r.disabled, false),
|
||||
// The device's own link values (admin only): 0 / null = the server's
|
||||
// (device_mtu, device_keepalive). Out of range is kept as read, so
|
||||
// model_errors can name it; the configuration then uses the server's.
|
||||
mtu: toint(r.mtu, 0),
|
||||
keepalive: r.keepalive == null || r.keepalive == '' ? null : toint(r.keepalive, null),
|
||||
// Its own local network stays outside the tunnel (awg.allowed_ips).
|
||||
lan_bypass: bool(r.lan_bypass, false),
|
||||
};
|
||||
m.devices[id] = d;
|
||||
if (m.people[d.person])
|
||||
@@ -367,18 +374,40 @@ export function alloc_address(m, srv) {
|
||||
*/
|
||||
const AUTO_MTU = 1380;
|
||||
const MOBILE_MTU = 1280;
|
||||
/** What an MTU set by hand may be (the server's and a device's alike). */
|
||||
export const MTU_RANGE = [ 1280, 1500 ];
|
||||
/** What a keep-alive set by hand may be, in seconds (0 = off). */
|
||||
export const KEEPALIVE_RANGE = [ 0, 600 ];
|
||||
|
||||
function in_range(n, r) {
|
||||
return type(n) == 'int' && n >= r[0] && n <= r[1];
|
||||
}
|
||||
|
||||
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
|
||||
export function tunnel_mtu(srv) {
|
||||
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
|
||||
};
|
||||
|
||||
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
|
||||
/**
|
||||
* The MTU a device's configuration carries: the device's own when the admin
|
||||
* set one, else the tunnel's, at most 1280 for phones and tablets.
|
||||
*/
|
||||
export function device_mtu(srv, dev) {
|
||||
if (in_range(dev.mtu, MTU_RANGE))
|
||||
return dev.mtu;
|
||||
let mtu = tunnel_mtu(srv);
|
||||
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
|
||||
};
|
||||
|
||||
/**
|
||||
* The keep-alive a device's configuration carries, in seconds (0 = off): the
|
||||
* device's own when the admin set one, else the server's. Both ends never
|
||||
* have to agree on it (the server's peers carry none), so it is the device's.
|
||||
*/
|
||||
export function device_keepalive(srv, dev) {
|
||||
return in_range(dev?.keepalive, KEEPALIVE_RANGE) ? dev.keepalive : srv.keepalive;
|
||||
};
|
||||
|
||||
export function endpoint_host(m, srv) {
|
||||
return srv.endpoint || m.settings.portal_host || '';
|
||||
};
|
||||
@@ -635,7 +664,7 @@ export function update_person(c, m, id, a) {
|
||||
c.delete(CONFIG, id, 'home_net');
|
||||
}
|
||||
if (type(a.home_nets) == 'array') {
|
||||
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
|
||||
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), valid_iface));
|
||||
if (length(nets))
|
||||
c.set(CONFIG, id, 'home_net', nets);
|
||||
else
|
||||
@@ -649,6 +678,8 @@ export function update_person(c, m, id, a) {
|
||||
* Add a device for a person. `opts.keys` = { private_key?, public_key,
|
||||
* preshared_key } from dawnline.awg (or a public key the browser generated).
|
||||
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
|
||||
* `opts.lan_bypass` true keeps the device's own local network outside the
|
||||
* tunnel (awg.allowed_ips).
|
||||
*/
|
||||
export function create_device(c, m, person_id, name, kind, opts) {
|
||||
opts ??= {};
|
||||
@@ -659,8 +690,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
if (!srv)
|
||||
fail(_('The person has no server.'));
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail(_('Enter a device name (up to 48 characters).'));
|
||||
if (!valid_device_name(name))
|
||||
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
|
||||
if (index(KINDS, kind) < 0)
|
||||
kind = 'other';
|
||||
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
|
||||
@@ -677,10 +708,15 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
for (let o, d in m.devices)
|
||||
if (d.public_key == k.public_key)
|
||||
fail(_('This key is already in use.'));
|
||||
// A server's own key (it is in every configuration): the kernel would silently ignore such a peer.
|
||||
for (let sid, s in m.servers)
|
||||
if (s.public_key == k.public_key)
|
||||
fail(_('This key is already in use.'));
|
||||
|
||||
let id = `d_${rand_hex(4)}`;
|
||||
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
|
||||
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
|
||||
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false,
|
||||
mtu: 0, keepalive: null, lan_bypass: opts.lan_bypass === true };
|
||||
c.set(CONFIG, id, 'device');
|
||||
c.set(CONFIG, id, 'person', person_id);
|
||||
c.set(CONFIG, id, 'name', name);
|
||||
@@ -691,6 +727,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
|
||||
c.set(CONFIG, id, f, dev[f]);
|
||||
c.set(CONFIG, id, 'created', `${dev.created}`);
|
||||
c.set(CONFIG, id, 'created_by', dev.created_by);
|
||||
if (dev.lan_bypass)
|
||||
c.set(CONFIG, id, 'lan_bypass', '1');
|
||||
|
||||
// Keep the in-memory model consistent for callers that continue.
|
||||
m.devices[id] = dev;
|
||||
@@ -703,8 +741,8 @@ export function rename_device(c, m, id, name) {
|
||||
if (!d)
|
||||
fail(_('Unknown device.'));
|
||||
name = trim(name ?? '');
|
||||
if (!valid_name(name))
|
||||
fail(_('Enter a device name (up to 48 characters).'));
|
||||
if (!valid_device_name(name))
|
||||
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
|
||||
for (let o in m.people[d.person]?.devices ?? [])
|
||||
if (o != id && lc(m.devices[o].name) == lc(name))
|
||||
fail(sprintf(_('"%s" already exists.'), name));
|
||||
@@ -712,6 +750,45 @@ export function rename_device(c, m, id, name) {
|
||||
d.name = name;
|
||||
};
|
||||
|
||||
/**
|
||||
* The admin's link settings of a device: `a` = { mtu?, keepalive?,
|
||||
* lan_bypass? }, only keys present change; '' takes a number back to the
|
||||
* server's (0 is a keep-alive of its own: off). Each is in the device's
|
||||
* configuration alone (the server's peers carry neither), so a change asks
|
||||
* that device to import again and touches nothing on the router. Returns the
|
||||
* names of the options that changed.
|
||||
*/
|
||||
export function set_device_link(c, m, id, a) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
fail(_('Unknown device.'));
|
||||
let changed = [];
|
||||
let put = (k, v, was) => {
|
||||
if (v == was)
|
||||
return;
|
||||
if (v == null)
|
||||
c.delete(CONFIG, id, k);
|
||||
else
|
||||
c.set(CONFIG, id, k, `${v}`);
|
||||
push(changed, k);
|
||||
};
|
||||
let number = (v, r, msg) => {
|
||||
let s = trim(`${v}`);
|
||||
if (s == '')
|
||||
return null;
|
||||
if (!match(s, /^[0-9]{1,4}$/) || +s < r[0] || +s > r[1])
|
||||
fail(msg);
|
||||
return +s;
|
||||
};
|
||||
if (a.mtu != null)
|
||||
put('mtu', number(a.mtu, MTU_RANGE, _('MTU must be 1280-1500.')), d.mtu || null);
|
||||
if (a.keepalive != null)
|
||||
put('keepalive', number(a.keepalive, KEEPALIVE_RANGE, _('Keep-alive must be 0-600 seconds.')), d.keepalive);
|
||||
if (a.lan_bypass != null)
|
||||
put('lan_bypass', a.lan_bypass === true ? 1 : null, d.lan_bypass ? 1 : null);
|
||||
return changed;
|
||||
};
|
||||
|
||||
export function delete_device(c, m, id) {
|
||||
let d = m.devices[id];
|
||||
if (!d)
|
||||
@@ -781,10 +858,12 @@ export function server_errors(m, srv, others_subnets) {
|
||||
* 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).
|
||||
* server), malformed keys, an MTU or keep-alive of their own out of range,
|
||||
* 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), and a configuration takes the server's value
|
||||
* for a link value out of range (device_mtu, device_keepalive).
|
||||
*/
|
||||
export function model_errors(m) {
|
||||
let errs = [];
|
||||
@@ -816,6 +895,11 @@ export function model_errors(m) {
|
||||
say(_('Device %s of %s: the private key is not a key.'));
|
||||
if (d.preshared_key != '' && !valid_key(d.preshared_key))
|
||||
say(_('Device %s of %s: the preshared key is not a key.'));
|
||||
// Its own link values (0 / null: the server's); one out of range is never used.
|
||||
if (d.mtu && !in_range(d.mtu, MTU_RANGE))
|
||||
say(_('Device %s of %s: MTU %d is not between 1280 and 1500.'), d.mtu);
|
||||
if (d.keepalive != null && !in_range(d.keepalive, KEEPALIVE_RANGE))
|
||||
say(_('Device %s of %s: keep-alive %d is not between 0 and 600 seconds.'), d.keepalive);
|
||||
let n = ip2int(d.address);
|
||||
if (n == null) {
|
||||
if (d.address)
|
||||
@@ -825,6 +909,9 @@ export function model_errors(m) {
|
||||
continue;
|
||||
}
|
||||
let srv = m.servers[p.server];
|
||||
// AmneziaWG ignores a peer with the interface's own key (dawnline.awg tunnel_devices leaves it out).
|
||||
if (srv?.public_key && d.public_key == srv.public_key)
|
||||
say(_("Device %s of %s: the public key is the server's own."));
|
||||
let t = srv ? parse_cidr(srv.subnet) : null;
|
||||
if (t && (n < t.first || n > t.last))
|
||||
say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
|
||||
@@ -895,7 +982,7 @@ export function wan_forwards(zone, proto) {
|
||||
c.load('firewall');
|
||||
let out = [];
|
||||
c.foreach('firewall', 'redirect', (r) => {
|
||||
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
|
||||
if (substr(r['.name'], 0, 9) == 'dawnline_' || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
|
||||
return;
|
||||
// fw4's default is "tcp udp".
|
||||
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
|
||||
|
||||
@@ -39,11 +39,15 @@ function own(m, id, opts) {
|
||||
return d;
|
||||
}
|
||||
|
||||
/** New device with fresh keys (or the browser's public key): { id, config }. */
|
||||
/**
|
||||
* New device with fresh keys (or the browser's public key): { id, config }.
|
||||
* `opts.lan_bypass` true keeps its own local network outside the tunnel.
|
||||
*/
|
||||
export function add(person, name, kind, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
|
||||
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind,
|
||||
{ by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true }));
|
||||
let s = apply.sync();
|
||||
let m = core.load();
|
||||
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
|
||||
@@ -52,14 +56,21 @@ export function add(person, name, kind, opts) {
|
||||
};
|
||||
|
||||
/**
|
||||
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
|
||||
* the admin turns devices off. Returns the runtime sync.
|
||||
* Rename and/or turn a device off or on, or change how it connects (`ch` =
|
||||
* { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see
|
||||
* core.set_device_link); only the admin turns devices off or changes the
|
||||
* rest. Returns the runtime sync ({} after a change of the link values alone:
|
||||
* they are in the device's configuration, nothing on the router changes).
|
||||
*/
|
||||
export function update(id, ch, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
if (ch.disabled != null && by != 'admin')
|
||||
die(_('Only the admin can turn devices off.'));
|
||||
let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null;
|
||||
if (link && by != 'admin')
|
||||
die(_('Only the admin can change how a device connects.'));
|
||||
let linked = [];
|
||||
let d0 = store.transact((c, m) => {
|
||||
let d = own(m, id, opts);
|
||||
let was = { ...d };
|
||||
@@ -71,18 +82,28 @@ export function update(id, ch, opts) {
|
||||
else
|
||||
c.delete(core.CONFIG, id, 'disabled');
|
||||
}
|
||||
if (link)
|
||||
linked = core.set_device_link(c, m, id, ch);
|
||||
return was;
|
||||
});
|
||||
let r = apply.sync();
|
||||
let r = ch.name != null || ch.disabled != null ? apply.sync() : {};
|
||||
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
|
||||
else if (ch.name != null && ch.name != d0.name)
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
|
||||
// The option names, as person_changed lists a person's.
|
||||
if (length(linked))
|
||||
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: join(', ', linked), by });
|
||||
return r;
|
||||
};
|
||||
|
||||
/** New keys for a device: returns its new configuration. */
|
||||
export function rotate(id, opts) {
|
||||
/*
|
||||
* New keys for a device: returns its new configuration, marked as issued (it
|
||||
* goes to the set-up sheet; the device then waits for it as "Not set up yet",
|
||||
* not as "settings changed"). Only through reconnect: new keys always mean
|
||||
* setting the device up again.
|
||||
*/
|
||||
function rotate(id, opts) {
|
||||
opts ??= {};
|
||||
let by = opts.by ?? 'admin';
|
||||
store.transact((c, m) => {
|
||||
@@ -104,14 +125,15 @@ export function rotate(id, opts) {
|
||||
if (s?.warning)
|
||||
cfg.warning = s.warning;
|
||||
return cfg;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a device up from scratch (a new phone, the app reinstalled, settings
|
||||
* the admin changed): new keys, so the configuration it holds stops working
|
||||
* with the sync, and it counts as not set up until it connects with the new
|
||||
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
|
||||
* it. Returns the new configuration, as rotate.
|
||||
* the admin changed; the portal's Reconnect and the admin's New keys): new
|
||||
* keys, so the configuration it holds stops working with the sync, and it
|
||||
* counts as not set up until it connects with the new one. The usage keeps
|
||||
* the old keys' last handshake: awg.handshake_since hides it. Returns the new
|
||||
* configuration (with `warning` when the sync did not fully take).
|
||||
*/
|
||||
export function reconnect(id, opts) {
|
||||
opts ??= {};
|
||||
|
||||
@@ -126,7 +126,7 @@ export function sync(m, dry) {
|
||||
|
||||
let stale = [];
|
||||
c.foreach('firewall', null, (s) => {
|
||||
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
|
||||
if (substr(s['.name'], 0, 9) == 'dawnline_' && !want[s['.name']])
|
||||
push(stale, s['.name']);
|
||||
});
|
||||
for (let s in stale) {
|
||||
@@ -170,6 +170,9 @@ export function drift(m) {
|
||||
};
|
||||
|
||||
const MARK_ALL = 0xffffffff;
|
||||
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff". A module
|
||||
// constant, compiled once, not for each rule.
|
||||
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/;
|
||||
|
||||
function hx(n) {
|
||||
return sprintf('0x%x', n);
|
||||
@@ -184,8 +187,7 @@ export function proxy_diverts() {
|
||||
let out = [], seen = {};
|
||||
for (let fam in [ '-4', '-6' ])
|
||||
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
|
||||
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff".
|
||||
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
|
||||
let mm = match(line, MARK_RULE);
|
||||
if (!mm || +mm[1] >= 32766)
|
||||
continue;
|
||||
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
|
||||
|
||||
@@ -45,19 +45,27 @@ export function needs() {
|
||||
};
|
||||
};
|
||||
|
||||
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
|
||||
// A module constant, compiled once: a literal in the loop would be compiled
|
||||
// again for every socket (0.12 ms each on the WR3000P, some 90 sockets a call).
|
||||
const UDP_UNCONNECTED = /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /;
|
||||
|
||||
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
|
||||
export function udp_bound() {
|
||||
let out = {};
|
||||
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
|
||||
for (let line in split(readfile(f) ?? '', '\n')) {
|
||||
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
|
||||
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
|
||||
let m = match(line, UDP_UNCONNECTED);
|
||||
if (m)
|
||||
out[hex(m[1])] = true;
|
||||
}
|
||||
return map(keys(out), (k) => +k);
|
||||
};
|
||||
|
||||
// netstat's columns and the port of "0.0.0.0:53" / ":::53". Module constants,
|
||||
// compiled once, not for each socket.
|
||||
const BLANKS = /[ \t]+/, PORT_SUFFIX = /:([0-9]+)$/;
|
||||
|
||||
/**
|
||||
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
|
||||
* Kernel sockets (a tunnel's) have no name.
|
||||
@@ -65,10 +73,10 @@ export function udp_bound() {
|
||||
function port_programs(proto) {
|
||||
let out = {};
|
||||
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
|
||||
let f = split(trim(line), /[ \t]+/);
|
||||
let f = split(trim(line), BLANKS);
|
||||
if (f[0] != proto && f[0] != `${proto}6`)
|
||||
continue;
|
||||
let m = match(f[3] ?? '', /:([0-9]+)$/);
|
||||
let m = match(f[3] ?? '', PORT_SUFFIX);
|
||||
let owner = split(f[length(f) - 1], '/');
|
||||
if (!m || !owner[1] || out[m[1]])
|
||||
continue;
|
||||
@@ -215,23 +223,138 @@ export function wan_kind(wan) {
|
||||
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
|
||||
};
|
||||
|
||||
const HEX = '0123456789abcdef';
|
||||
|
||||
// An IPv6 address as its 32 hex digits, so two spellings of one address
|
||||
// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints
|
||||
// it); null when it is none. No regex: the router's addresses and a name's
|
||||
// AAAA records go through it on every look.
|
||||
function ip6_full(s) {
|
||||
if (type(s) != 'string')
|
||||
return null;
|
||||
let halves = split(lc(s), '::');
|
||||
if (length(halves) > 2)
|
||||
return null;
|
||||
let head = halves[0] != '' ? split(halves[0], ':') : [];
|
||||
let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : [];
|
||||
let gap = 8 - length(head) - length(tail);
|
||||
if (length(halves) == 2 ? gap < 1 : gap != 0)
|
||||
return null;
|
||||
let groups = [ ...head ];
|
||||
for (let i = 0; i < gap; i++)
|
||||
push(groups, '0');
|
||||
push(groups, ...tail);
|
||||
let out = '';
|
||||
for (let g in groups) {
|
||||
if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '')
|
||||
return null;
|
||||
out += substr(`0000${g}`, length(g));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The router's public IPv6 addresses in `ip -6 -j addr show scope global`
|
||||
* output (`links`), on any interface: a DDNS client may publish the LAN's
|
||||
* address from the delegated prefix, which reaches the router too. Unique
|
||||
* local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6
|
||||
* from the ISP) and failed duplicates do not count: nothing reaches them from
|
||||
* outside. [] when there is none.
|
||||
*/
|
||||
export function own_ipv6(links) {
|
||||
let out = [];
|
||||
for (let l in (type(links) == 'array' ? links : []))
|
||||
for (let a in l?.addr_info ?? []) {
|
||||
let k = ip6_full(a?.local);
|
||||
if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd')
|
||||
push(out, a.local);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell.
|
||||
function router_ipv6() {
|
||||
let out = sh_out('ip -6 -j addr show scope global');
|
||||
if (out == null)
|
||||
return null;
|
||||
try {
|
||||
let links = json(out || '[]');
|
||||
return type(links) == 'array' ? own_ipv6(links) : null;
|
||||
}
|
||||
catch (e) {
|
||||
// No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// What the facts are made from, read on the router.
|
||||
function endpoint_reads(srv, host) {
|
||||
let ips = host ? lookup.resolve(host) : [];
|
||||
// The router's IPv6 only when the name has some to compare with.
|
||||
return {
|
||||
ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'),
|
||||
router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a public address points at, for Health and the "as you type" check on
|
||||
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
|
||||
* here (an IPv4 of it is this router's WAN), v6_only }.
|
||||
* here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's
|
||||
* public IPv6 addresses, own_ipv6; null when unknown, or not read because the
|
||||
* name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all
|
||||
* of them when the router has none; null while router6 is), here6 (it has
|
||||
* IPv6 addresses and each is one of the router's) }. `reads` (a test's)
|
||||
* stands for what is read on the router: { ips, wan, router6 }.
|
||||
*/
|
||||
export function endpoint_facts(srv, host) {
|
||||
let ips = host ? lookup.resolve(host) : [];
|
||||
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
|
||||
export function endpoint_facts(srv, host, reads) {
|
||||
let r = reads ?? endpoint_reads(srv, host);
|
||||
let ips = r.ips ?? [], wan = r.wan ?? null;
|
||||
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
|
||||
let own = r.router6 != null ? map(r.router6, ip6_full) : null;
|
||||
let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null;
|
||||
return {
|
||||
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
|
||||
host, ips, ips4, ips6, wan, kind: wan_kind(wan),
|
||||
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
|
||||
here: wan != null && index(ips4, wan) >= 0,
|
||||
v6_only: !length(ips4) && length(ips6) > 0,
|
||||
router6: r.router6 ?? null, foreign6,
|
||||
here6: foreign6 != null && length(ips6) > 0 && !length(foreign6),
|
||||
};
|
||||
};
|
||||
|
||||
/*
|
||||
* The name's IPv6 addresses that do not reach this router from outside, in
|
||||
* words, or null (each is a public one of the router, or those are unknown).
|
||||
* A name with IPv4 too: devices that prefer IPv6 take these and fail, the
|
||||
* others connect.
|
||||
*/
|
||||
function aaaa_words(f) {
|
||||
let bad = f.foreign6 ?? [], n = length(bad);
|
||||
if (!n)
|
||||
return null;
|
||||
if (!length(f.router6))
|
||||
return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.',
|
||||
'%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'),
|
||||
f.host, join(', ', bad));
|
||||
return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'),
|
||||
f.host, join(', ', bad));
|
||||
}
|
||||
|
||||
// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise.
|
||||
function v6_only_unreached(f) {
|
||||
let n = length(f.foreign6 ?? []);
|
||||
if (!n || n < length(f.ips6))
|
||||
return null;
|
||||
if (!length(f.router6))
|
||||
return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'),
|
||||
f.host, join(', ', f.ips6));
|
||||
return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.',
|
||||
'%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'),
|
||||
f.host, join(', ', f.ips6));
|
||||
}
|
||||
|
||||
/**
|
||||
* The facts in words, in the language of the call: { status: ok|warn|error, text }
|
||||
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
|
||||
@@ -244,18 +367,28 @@ export function endpoint_words(f, proto_note) {
|
||||
if (f.cloudflare)
|
||||
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
|
||||
f.host, join(', ', f.ips), proto_note) };
|
||||
if (f.v6_only)
|
||||
let v6 = aaaa_words(f);
|
||||
if (f.v6_only) {
|
||||
let none = v6_only_unreached(f);
|
||||
if (none != null || v6 != null)
|
||||
return { status: 'warn', text: none ?? v6 };
|
||||
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
|
||||
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
|
||||
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
|
||||
}
|
||||
let v4 = null;
|
||||
if (f.kind == 'cgnat' || f.kind == 'private')
|
||||
return { status: 'warn', text: f.kind == 'cgnat'
|
||||
v4 = f.kind == 'cgnat'
|
||||
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
|
||||
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note) };
|
||||
if (f.wan && !f.here)
|
||||
return { status: 'warn', text: sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan) };
|
||||
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note);
|
||||
else if (f.wan && !f.here)
|
||||
v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan);
|
||||
// Two separate facts, each a sentence of its own: the IPv4 one first.
|
||||
if (v4 != null || v6 != null)
|
||||
return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) };
|
||||
// Without the router's WAN address only the facts: names and addresses, no words.
|
||||
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, f.wan) : `${f.host} → ${join(', ', f.ips)}` };
|
||||
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ]))
|
||||
: `${f.host} → ${join(', ', f.ips)}` };
|
||||
};
|
||||
|
||||
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
|
||||
@@ -264,6 +397,9 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
|
||||
return check(id, title, w.status, w.text, null, problem);
|
||||
}
|
||||
|
||||
// "1000: from all fwmark 0x1 lookup 100". A module constant, compiled once, not for each rule.
|
||||
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/;
|
||||
|
||||
/**
|
||||
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
|
||||
* Dawnline's (pref < 5205) whose table has a default route of its own sends
|
||||
@@ -273,7 +409,7 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
|
||||
function policy_routing() {
|
||||
let out = [];
|
||||
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
|
||||
let mm = match(line, MARK_RULE);
|
||||
if (!mm || +mm[1] >= 5205)
|
||||
continue;
|
||||
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
|
||||
@@ -321,9 +457,53 @@ function awg_check() {
|
||||
}
|
||||
if (!st.handler)
|
||||
return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
|
||||
// The install could not swap the loaded module: the old one runs until the next boot (dawnline.awg_builds).
|
||||
if (builds.waits_for_reboot())
|
||||
return check('awg', title, 'warn', _('The AmneziaWG update is installed and starts after a reboot.'), null,
|
||||
_('The AmneziaWG update waits for a reboot'));
|
||||
return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The /24s home routers come with out of the box. A home network on one of
|
||||
* them is very likely the same as the network a person connects from, and
|
||||
* home access then takes those addresses into the tunnel: their own printer or
|
||||
* TV is out of reach while connected, LAN Bypass or not.
|
||||
*/
|
||||
const COMMON_HOME = [
|
||||
'192.168.0.0/24', '192.168.1.0/24', '192.168.2.0/24', '192.168.3.0/24', '192.168.8.0/24', '192.168.10.0/24',
|
||||
'192.168.31.0/24', '192.168.50.0/24', '192.168.88.0/24', '192.168.100.0/24', '192.168.178.0/24',
|
||||
'10.0.0.0/24', '10.1.1.0/24',
|
||||
];
|
||||
|
||||
/** The home networks in `nets` that overlap a common out-of-the-box subnet. */
|
||||
export function common_home(nets) {
|
||||
return filter(nets ?? [], (n) => {
|
||||
let a = parse_cidr(n);
|
||||
return a && length(filter(COMMON_HOME, (c) => cidr_overlaps(a, parse_cidr(c))));
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the server's home networks are on a common subnet, while anyone on
|
||||
* it has home access (otherwise nothing of home goes into the tunnel). A
|
||||
* warning on Health only: advice, not a fault, so no notice elsewhere.
|
||||
*/
|
||||
function home_check(m, id, srv, label) {
|
||||
let reach = filter(values(m.people), (p) => p.server == id && (p.access == 'lan' || p.access == 'both'));
|
||||
let nets = net.server_net(srv).nets;
|
||||
if (!length(reach) || !length(nets))
|
||||
return null;
|
||||
let bad = common_home(nets);
|
||||
let c = check(`homenet_${id}`, _('Home network addresses') + label, length(bad) ? 'warn' : 'ok',
|
||||
length(bad)
|
||||
? sprintf(_('%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24.'), join(', ', bad))
|
||||
: sprintf(_('%s is not a common home subnet: the networks people connect from rarely use the same addresses.'), join(', ', nets)),
|
||||
null);
|
||||
c.problem = null;
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Checks of a server's AmneziaWG tunnel. */
|
||||
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
let out = [];
|
||||
@@ -339,26 +519,15 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
!st ? sprintf(_('%s does not exist.'), srv.ifname) :
|
||||
length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
|
||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
|
||||
if (up) {
|
||||
// By key, not by count: a stale peer standing in for a missing one would
|
||||
// make the numbers match.
|
||||
let states = apply.states_for(m, core.load_usage());
|
||||
let wanted = {}, expected = 0;
|
||||
for (let did, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
|
||||
wanted[d.public_key] = true;
|
||||
expected++;
|
||||
}
|
||||
}
|
||||
let loaded = {}, actual = 0;
|
||||
for (let k, p in dmp.peers)
|
||||
if (p.ifname == srv.ifname) {
|
||||
loaded[k] = true;
|
||||
actual++;
|
||||
}
|
||||
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
|
||||
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
|
||||
// The devices the sync loads, by the same choice the agent compares with every minute.
|
||||
if (up && dmp.reads[srv.ifname] == 'error')
|
||||
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn',
|
||||
_('The tunnel could not be read, so its devices could not be checked.'), null,
|
||||
_('The devices in AmneziaWG could not be checked') + label));
|
||||
else if (up) {
|
||||
let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage()));
|
||||
let diff = awg.peer_diff(devs, dmp, srv.ifname);
|
||||
let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded;
|
||||
let same = !missing && !extra;
|
||||
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
|
||||
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
|
||||
@@ -395,6 +564,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
||||
push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok',
|
||||
length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet),
|
||||
null, _('AmneziaWG subnet overlaps another network') + label));
|
||||
let home = home_check(m, id, srv, label);
|
||||
if (home)
|
||||
push(out, home);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
// Dawnline — how each device's link behaves, from the counters the agent's
|
||||
// watcher reads every second (dawnline.awg.dump): a device that knocks but
|
||||
// never finishes connecting, one whose configuration is in use on two devices,
|
||||
// one whose traffic the router drops, one whose connection keeps breaking.
|
||||
//
|
||||
// The agent keeps one history per device in memory (fresh(), observe(): a few
|
||||
// events of the last HISTORY seconds, not one entry per tick), classifies it
|
||||
// (classify(), pure) and shows a state only once it held HOLD seconds
|
||||
// (settle()). It writes what is shown to dawnline.live.LINK on a change; the
|
||||
// read side (live.dump's `link`, view.device_view) is dawnline.live's, so the
|
||||
// portal never loads this module. Who is online stays live.PRESENCE's.
|
||||
//
|
||||
// The same history tells the set-up sheet, at once and without HOLD, what a
|
||||
// device that is being set up does right now (setup_state(), setup()): it
|
||||
// knocks without finishing, data flows, or it connected but nothing it sends
|
||||
// comes through. The agent writes that to dawnline.live.SETUP on a change.
|
||||
//
|
||||
// What the counters mean (kmod 3.1, receive.c and send.c):
|
||||
// * an accepted handshake initiation adds exactly INITIATION bytes to the
|
||||
// peer's rx: the S1 prefix and any trailer are cut off and the header
|
||||
// protection is undone in place before update_rx_stats(skb->len). The
|
||||
// router answers it; its own handshake time moves only when the first
|
||||
// packet under the new keys arrives.
|
||||
// * a keepalive adds KEEPALIVE plus its content padding; a handshake
|
||||
// response (the router initiated) RESPONSE; data 32 + its padded length.
|
||||
// Plain data is a multiple of 16, so 148, 296 and 444 never are data.
|
||||
// * a data packet the router then drops (its source is not the device's
|
||||
// address: an old configuration after renumbering; this is what moves
|
||||
// the interface's rx_frame_errors) adds nothing to rx, but the router
|
||||
// still answers it with a keepalive within KeepaliveTimeout (about 10 s).
|
||||
|
||||
/** Seconds of events kept per device. */
|
||||
export const HISTORY = 600;
|
||||
/** A state is shown once it held this long (a flapping mobile link passes). */
|
||||
export const HOLD = 180;
|
||||
/** A device is classified at least this often when nothing happened (its spans age). */
|
||||
export const CHECK_EVERY = 15;
|
||||
|
||||
/** Bytes an accepted initiation adds to rx (sizeof(struct message_handshake_initiation)). */
|
||||
export const INITIATION = 148;
|
||||
/** Bytes a handshake response adds to rx (the router initiated). */
|
||||
export const RESPONSE = 92;
|
||||
/** Bytes an empty data packet adds to rx, before content padding. */
|
||||
export const KEEPALIVE = 32;
|
||||
// Random trailers without content padding: a keepalive grows up to a full packet.
|
||||
const TRAILER_MAX = 1500;
|
||||
// Initiations a device sends at most in one second (retries are 5 s apart).
|
||||
const KNOCKS_PER_TICK = 3;
|
||||
|
||||
/** trying: at least TRY_KNOCKS accepted initiations within TRY_SPAN seconds while not online. */
|
||||
export const TRY_SPAN = 120;
|
||||
export const TRY_KNOCKS = 3;
|
||||
/*
|
||||
* Churning: at least CHURN_COUNT handshakes within CHURN_SPAN seconds, with
|
||||
* CHURN_COUNT - 1 of the gaps under CHURN_GAP seconds. A device that is
|
||||
* there renews its keys every 100-120 s (RekeyAfterTime), more only when
|
||||
* its packets get nothing back (KeepaliveTimeout + RekeyTimeout, ~15 s).
|
||||
*/
|
||||
export const CHURN_SPAN = 300;
|
||||
export const CHURN_COUNT = 4;
|
||||
export const CHURN_GAP = 45;
|
||||
/** shared: while churning, the endpoint (ip:port) went back to an earlier one this often. */
|
||||
export const SHARE_RETURNS = 2;
|
||||
/*
|
||||
* dropped: online with a handshake within DROP_HS seconds, nothing but
|
||||
* handshakes and keepalives received for DROP_SPAN seconds, and the router
|
||||
* sent something at least DROP_ANSWERS times in that span with nothing
|
||||
* coming in (its keepalives answering packets it dropped), under DROP_TX
|
||||
* bytes in all (a real download is far more).
|
||||
*/
|
||||
export const DROP_SPAN = 180;
|
||||
export const DROP_HS = 240;
|
||||
export const DROP_ANSWERS = 6;
|
||||
export const DROP_TX = 65536;
|
||||
|
||||
/** Every state classify() can give. */
|
||||
export const STATES = [ 'trying', 'shared', 'dropped', 'unstable' ];
|
||||
|
||||
/*
|
||||
* The set-up sheet's trying: at least SETUP_KNOCKS accepted initiations
|
||||
* within SETUP_SPAN seconds, none of them followed by a handshake. A device
|
||||
* retries every 5 s, so it shows with the second (5-6 s in) and goes about
|
||||
* 15 s after the last.
|
||||
*/
|
||||
export const SETUP_SPAN = 20;
|
||||
export const SETUP_KNOCKS = 2;
|
||||
/*
|
||||
* nodata: online for SETUP_QUIET seconds since the handshake its session
|
||||
* began with, nothing but handshakes and keepalives in since, and the router
|
||||
* answered at least once with nothing coming in (a keepalive for data it
|
||||
* dropped, about 10 s after it: an old address in the configuration). An
|
||||
* idle device gets no answers, so it never shows.
|
||||
*/
|
||||
export const SETUP_QUIET = 15;
|
||||
|
||||
// Per list, the newest entries kept (a device whose endpoint flips every second).
|
||||
const KEEP = 64;
|
||||
|
||||
function keep(list, entry) {
|
||||
push(list, entry);
|
||||
if (length(list) > KEEP)
|
||||
shift(list);
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty history for a device first seen at `now`. Fields: rx, tx
|
||||
* (the counters last read, null before the first read), hs (the newest
|
||||
* handshake), ep (the endpoint), data (when rx last carried data), hsev
|
||||
* (handshake times), epev ([ ts, ip:port, the one before ] endpoint
|
||||
* changes), knocks (times
|
||||
* of accepted initiations), ans ([ ts, bytes ] the router sent with nothing
|
||||
* received), state/since (what is shown), pend (a state waiting for HOLD),
|
||||
* raw (the last classification), checked (when it was made); for the set-up
|
||||
* sheet (setup()): on (online at the last read), sess (the handshake its
|
||||
* online stretch began with, 0 while away), setup ({ state, since } or null)
|
||||
* and due (when setup_state() may change with time alone, 0 for never).
|
||||
*/
|
||||
export function fresh(now) {
|
||||
return {
|
||||
start: now, rx: null, tx: null, hs: 0, ep: null, data: 0,
|
||||
hsev: [], epev: [], knocks: [], ans: [],
|
||||
state: null, since: 0, pend: null, raw: null, checked: 0,
|
||||
on: false, sess: 0, setup: null, due: 0,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* The largest rx a keepalive adds for a server's disguise: KEEPALIVE plus
|
||||
* the top of its ContentPaddingAddition, or a full packet with random
|
||||
* trailers and no content padding (the apps get the server's values).
|
||||
*/
|
||||
export function keepalive_max(srv) {
|
||||
let o = srv?.obf ?? {};
|
||||
let cpa = split(`${o.content_padding_addition ?? ''}`, '-');
|
||||
let hi = +(cpa[length(cpa) - 1]);
|
||||
if (o.content_padding_addition != null && o.content_padding_addition != '' && hi > 0)
|
||||
return KEEPALIVE + hi;
|
||||
if (o.random_trailers == 'on' || o.random_trailers == '1')
|
||||
return KEEPALIVE + TRAILER_MAX;
|
||||
return KEEPALIVE;
|
||||
};
|
||||
|
||||
/** keepalive_max() for each device's server: { device id: bytes }. */
|
||||
export function keepalive_sizes(m) {
|
||||
let out = {};
|
||||
for (let id, d in m.devices)
|
||||
out[id] = keepalive_max(m.servers[m.people[d.person]?.server]);
|
||||
return out;
|
||||
};
|
||||
|
||||
/** An rx increment made of accepted initiations only. */
|
||||
export function knock(drx) {
|
||||
return drx > 0 && drx % INITIATION == 0 && drx <= KNOCKS_PER_TICK * INITIATION;
|
||||
};
|
||||
|
||||
/**
|
||||
* An rx increment that carried no data: nothing, or one keepalive of up to
|
||||
* `ka` bytes (keepalive_max); in the second a handshake completed (`shook`)
|
||||
* also the handshake messages that came with it. Outside that second a
|
||||
* handshake message is never counted in: with a padded keepalive their
|
||||
* sums would cover every small packet (a DNS query, an ACK) up to some
|
||||
* 670 bytes, and a device with light traffic would look like one whose
|
||||
* data never comes through.
|
||||
*/
|
||||
export function bare(drx, ka, shook) {
|
||||
if (drx <= 0)
|
||||
return true;
|
||||
if (!shook)
|
||||
return drx >= KEEPALIVE && drx <= ka;
|
||||
if (drx > KNOCKS_PER_TICK * INITIATION + RESPONSE + ka)
|
||||
return false;
|
||||
for (let k = 0; k <= KNOCKS_PER_TICK; k++)
|
||||
for (let r = 0; r <= 1; r++) {
|
||||
let rest = drx - k * INITIATION - r * RESPONSE;
|
||||
if (rest == 0 || (rest >= KEEPALIVE && rest <= ka))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fold one read of the device's peer ({ endpoint, handshake, rx, tx } from
|
||||
* awg.dump) at `now` into its history `h`; `ka` is its keepalive_max().
|
||||
* Returns true when something worth classifying again happened (a
|
||||
* handshake, a new endpoint, a knock, an answer, data after a quiet span).
|
||||
* Counters that went down (the peer re-added, its tunnel set up again)
|
||||
* start a new baseline.
|
||||
*/
|
||||
export function observe(h, peer, now, ka) {
|
||||
let changed = false;
|
||||
let shook = peer.handshake > h.hs;
|
||||
if (shook) {
|
||||
keep(h.hsev, peer.handshake);
|
||||
h.hs = peer.handshake;
|
||||
changed = true;
|
||||
}
|
||||
if (peer.endpoint != h.ep) {
|
||||
if (h.ep != null && peer.endpoint != '') {
|
||||
keep(h.epev, [ now, peer.endpoint, h.ep ]);
|
||||
changed = true;
|
||||
}
|
||||
h.ep = peer.endpoint;
|
||||
}
|
||||
if (h.rx == null || peer.rx < h.rx || peer.tx < h.tx) {
|
||||
h.rx = peer.rx;
|
||||
h.tx = peer.tx;
|
||||
return changed;
|
||||
}
|
||||
let drx = peer.rx - h.rx, dtx = peer.tx - h.tx;
|
||||
h.rx = peer.rx;
|
||||
h.tx = peer.tx;
|
||||
if (drx > 0) {
|
||||
if (!shook && knock(drx)) {
|
||||
keep(h.knocks, now);
|
||||
changed = true;
|
||||
}
|
||||
else if (!bare(drx, ka, shook)) {
|
||||
if (now - h.data >= DROP_SPAN)
|
||||
changed = true;
|
||||
h.data = now;
|
||||
}
|
||||
}
|
||||
else if (dtx > 0) {
|
||||
keep(h.ans, [ now, dtx ]);
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/** The device's peer is not in its tunnel: the next read starts a new baseline. */
|
||||
export function gone(h) {
|
||||
h.rx = null;
|
||||
h.tx = null;
|
||||
};
|
||||
|
||||
/** Forget events older than HISTORY seconds. */
|
||||
export function prune(h, now) {
|
||||
let cut = now - HISTORY;
|
||||
h.hsev = filter(h.hsev, (t) => t > cut);
|
||||
h.knocks = filter(h.knocks, (t) => t > cut);
|
||||
h.epev = filter(h.epev, (e) => e[0] > cut);
|
||||
h.ans = filter(h.ans, (e) => e[0] > cut);
|
||||
};
|
||||
|
||||
/** Endpoint changes within the span that went back to an endpoint seen before in it (A → B → A → B: 2). */
|
||||
function returns(h, now) {
|
||||
let seen = null, n = 0;
|
||||
for (let e in h.epev)
|
||||
if (now - e[0] < CHURN_SPAN) {
|
||||
if (seen == null) {
|
||||
seen = {};
|
||||
seen[e[2]] = true;
|
||||
}
|
||||
if (seen[e[1]])
|
||||
n++;
|
||||
seen[e[1]] = true;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function churning(h, now) {
|
||||
let hs = filter(h.hsev, (t) => now - t < CHURN_SPAN);
|
||||
if (length(hs) < CHURN_COUNT)
|
||||
return false;
|
||||
let short = 0;
|
||||
for (let i = 1; i < length(hs); i++)
|
||||
if (hs[i] - hs[i - 1] < CHURN_GAP)
|
||||
short++;
|
||||
return short >= CHURN_COUNT - 1;
|
||||
}
|
||||
|
||||
function dropped(h, now) {
|
||||
if (now - h.start < DROP_SPAN || now - h.data < DROP_SPAN || !(h.hs > 0 && now - h.hs < DROP_HS))
|
||||
return false;
|
||||
let n = 0, bytes = 0;
|
||||
for (let a in h.ans)
|
||||
if (now - a[0] < DROP_SPAN) {
|
||||
n++;
|
||||
bytes += a[1];
|
||||
}
|
||||
return n >= DROP_ANSWERS && bytes < DROP_TX;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the history says about the device at `now` (`on`: it is online, as
|
||||
* the watcher decides it): null (nothing wrong, or nothing to tell), or
|
||||
* 'trying' not online, but its initiations reach the router and are
|
||||
* answered, and it never finishes connecting (the network
|
||||
* may block it, or its configuration is out of date: a
|
||||
* stale preshared key looks the same)
|
||||
* 'shared' connecting over and over from two or more alternating
|
||||
* endpoints (ip:port): one configuration on two devices
|
||||
* 'unstable' connecting over and over from one place: the connection
|
||||
* keeps breaking
|
||||
* 'dropped' connected, but nothing it sends gets through: the router
|
||||
* drops it (an old address in its configuration)
|
||||
*/
|
||||
export function classify(h, now, on) {
|
||||
if (!on) {
|
||||
let n = 0;
|
||||
for (let t in h.knocks)
|
||||
if (now - t < TRY_SPAN)
|
||||
n++;
|
||||
return n >= TRY_KNOCKS ? 'trying' : null;
|
||||
}
|
||||
if (churning(h, now))
|
||||
return returns(h, now) >= SHARE_RETURNS ? 'shared' : 'unstable';
|
||||
return dropped(h, now) ? 'dropped' : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turn a classification into what is shown (h.state, h.since): a state, or
|
||||
* a change of state, shows once classify() gave it for HOLD seconds (since
|
||||
* = when it began); nothing wrong shows at once when the device is online
|
||||
* (it works), else after HOLD as well. Returns the change, { from, to }
|
||||
* (either may be null), or null when what is shown stays.
|
||||
*/
|
||||
export function settle(h, raw, now, on) {
|
||||
if (raw == h.state) {
|
||||
h.pend = null;
|
||||
return null;
|
||||
}
|
||||
let since = now;
|
||||
if (raw != null || !on) {
|
||||
if (h.pend == null || h.pend.state != raw) {
|
||||
h.pend = { state: raw, since: now };
|
||||
return null;
|
||||
}
|
||||
if (now - h.pend.since < HOLD)
|
||||
return null;
|
||||
since = h.pend.since;
|
||||
}
|
||||
let from = h.state;
|
||||
h.state = raw;
|
||||
h.since = raw != null ? since : 0;
|
||||
h.pend = null;
|
||||
return { from, to: raw };
|
||||
};
|
||||
|
||||
/**
|
||||
* What the device's link does at `now` for the set-up sheet (pure; `on`: it
|
||||
* is online, as the watcher decides it): { state, due }. state is
|
||||
* 'trying' its initiations reach the router and are answered, and no
|
||||
* handshake follows (SETUP_KNOCKS within SETUP_SPAN): the
|
||||
* network blocks the answers, or the configuration is not this
|
||||
* device's any more
|
||||
* 'flowing' online, and data came in during this session (since h.sess)
|
||||
* 'nodata' online for SETUP_QUIET seconds, nothing but handshakes and
|
||||
* keepalives came in, and the router answered packets it
|
||||
* dropped: an old address in the configuration
|
||||
* null none of these (waiting, idle, or away)
|
||||
* due: when the state may change with time alone (a knock ages out, the
|
||||
* quiet span ends), 0 for never: anything else comes with a read.
|
||||
*/
|
||||
export function setup_state(h, now, on) {
|
||||
let n = 0;
|
||||
for (let i = length(h.knocks) - 1; i >= 0; i--) {
|
||||
let t = h.knocks[i];
|
||||
if (t <= h.hs || now - t >= SETUP_SPAN)
|
||||
break;
|
||||
if (++n == SETUP_KNOCKS)
|
||||
return { state: 'trying', due: t + SETUP_SPAN };
|
||||
}
|
||||
if (!on || !h.sess)
|
||||
return { state: null, due: 0 };
|
||||
if (h.data >= h.sess)
|
||||
return { state: 'flowing', due: 0 };
|
||||
if (now - h.sess < SETUP_QUIET)
|
||||
return { state: null, due: h.sess + SETUP_QUIET };
|
||||
let a = h.ans[length(h.ans) - 1];
|
||||
return { state: a != null && a[0] >= h.sess ? 'nodata' : null, due: 0 };
|
||||
};
|
||||
|
||||
/**
|
||||
* Bring h.setup to setup_state() after a read at `now` (`moved`: what
|
||||
* observe() returned). Most reads cost a few compares: the state is worked
|
||||
* out again only when something happened, the device came or went, data
|
||||
* came in while it is not 'flowing', or its `due` time came. Returns true
|
||||
* when h.setup changed ({ state, since: when it began } or null).
|
||||
*/
|
||||
export function setup(h, now, on, moved) {
|
||||
// A session begins with the handshake that brought the device online.
|
||||
if (!on)
|
||||
h.sess = 0;
|
||||
else if (!h.sess)
|
||||
h.sess = h.hs;
|
||||
let came = on != h.on;
|
||||
h.on = on;
|
||||
let cur = h.setup?.state;
|
||||
if (!moved && !came && !(h.due && now >= h.due) && !(h.data == now && cur != 'flowing'))
|
||||
return false;
|
||||
let s = setup_state(h, now, on);
|
||||
h.due = s.due;
|
||||
if (s.state == cur)
|
||||
return false;
|
||||
h.setup = s.state != null ? { state: s.state, since: now } : null;
|
||||
return true;
|
||||
};
|
||||
|
||||
/** setup() of every device: { device id: { state, since } }, devices with none left out. */
|
||||
export function setups(hist) {
|
||||
let out = {};
|
||||
for (let id, h in hist)
|
||||
if (h.setup != null)
|
||||
out[id] = h.setup;
|
||||
return out;
|
||||
};
|
||||
|
||||
/** What is shown for every device: { device id: { state, since } }, devices with nothing to show left out. */
|
||||
export function shown(hist) {
|
||||
let out = {};
|
||||
for (let id, h in hist)
|
||||
if (h.state != null)
|
||||
out[id] = { state: h.state, since: h.since };
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* The activity event for a change settle() made, or null: device_failing
|
||||
* (detail: the new state) when a state shows, device_recovered (detail:
|
||||
* the state it had) when it clears while the device is online. One that
|
||||
* clears while the device is away (it stopped trying, it was paused) logs
|
||||
* nothing: nobody saw it work.
|
||||
*/
|
||||
export function event_for(change, dev, on) {
|
||||
if (!change)
|
||||
return null;
|
||||
if (change.to != null)
|
||||
return { type: 'device_failing', person: dev.person, device: dev.id, detail: change.to };
|
||||
if (on && change.from != null)
|
||||
return { type: 'device_recovered', person: dev.person, device: dev.id, detail: change.from };
|
||||
return null;
|
||||
};
|
||||
@@ -11,11 +11,14 @@ import {
|
||||
iface_status as util_iface_status, RUN_DIR, DATA_DIR
|
||||
} from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as schema from 'dawnline.schema';
|
||||
|
||||
// Online while the WireGuard session lives: it is dropped 180 s after its
|
||||
// handshake, and a device that is there renews it every 2 min (a little slack
|
||||
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
|
||||
// The shortest window: a device whose keep-alive is longer gets more
|
||||
// (online_window), or it would flap between its handshakes.
|
||||
export const ONLINE_WINDOW = 190;
|
||||
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
|
||||
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
|
||||
@@ -31,6 +34,8 @@ export const CATEGORY = {
|
||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
|
||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||
// A device's link (dawnline.link): failing in a named way, and working again.
|
||||
device_failing: 'problems', device_recovered: 'problems',
|
||||
};
|
||||
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
||||
|
||||
@@ -95,24 +100,90 @@ export const PRESENCE = `${RUN_DIR}/presence.json`;
|
||||
const BEAT = `${RUN_DIR}/agent.beat`;
|
||||
const BEAT_STALE = 180;
|
||||
|
||||
/** The agent runs (its heartbeat is fresh): what its watcher wrote counts. */
|
||||
function agent_running() {
|
||||
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||
return beat > 0 && time() - beat <= BEAT_STALE;
|
||||
}
|
||||
|
||||
/** What the watcher sees, or null when the agent isn't running. */
|
||||
export function presence() {
|
||||
let beat = +(read_json(BEAT, 0) ?? 0);
|
||||
if (!beat || time() - beat > BEAT_STALE)
|
||||
return null;
|
||||
return read_json(PRESENCE, null);
|
||||
return agent_running() ? read_json(PRESENCE, null) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
|
||||
* handshake, rx, tx } }, presence }. See dawnline.awg.
|
||||
* Written by the agent's watcher when what it shows changes (dawnline.link):
|
||||
* { device id: { state: 'trying' | 'shared' | 'dropped' | 'unstable', since } },
|
||||
* only devices whose link fails in one of these ways (link.classify()).
|
||||
*/
|
||||
export function dump(m) {
|
||||
// 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();
|
||||
export const LINK = `${RUN_DIR}/link.json`;
|
||||
|
||||
/**
|
||||
* Written by the agent's watcher when it changes (dawnline.link.setup, at
|
||||
* once, without LINK's hold): what each device's link does right now, for the
|
||||
* set-up sheet: { device id: { state: 'trying' | 'flowing' | 'nodata', since } },
|
||||
* devices with none of these left out.
|
||||
*/
|
||||
export const SETUP = `${RUN_DIR}/setup.json`;
|
||||
|
||||
/**
|
||||
* The interfaces of the servers that run: enabled, with keys and an
|
||||
* interface that is Dawnline's (core.tunnels: never another tunnel that
|
||||
* took the name); with `sid`, only that server's. What dawnline.awg.dump()
|
||||
* reads; an empty list when none.
|
||||
*/
|
||||
export function tunnel_ifnames(m, sid) {
|
||||
let out = [];
|
||||
for (let id, srv in m.servers)
|
||||
if (srv.enabled && (sid == null || id == sid))
|
||||
for (let t in core.tunnels(srv))
|
||||
push(out, t.ifname);
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* How long after its last handshake a device still counts as online, in
|
||||
* seconds: ONLINE_WINDOW, or 30 s more than an idle device with its
|
||||
* keep-alive goes between handshakes (awg.idle_handshake) when that is
|
||||
* longer. A device that sends nothing renews its session only with its
|
||||
* keep-alive: with one of about 95-120 s, or over 160 s, the fixed window
|
||||
* would see it leave and come back between two handshakes. Keep-alive off:
|
||||
* ONLINE_WINDOW.
|
||||
*/
|
||||
export function online_window(srv, dev) {
|
||||
let h = srv ? awg.idle_handshake(srv, dev) : null;
|
||||
return h != null ? max(ONLINE_WINDOW, h + 30) : ONLINE_WINDOW;
|
||||
};
|
||||
|
||||
/** online_window() of every device (with `sid`, of that server's): { device id: seconds }. */
|
||||
export function online_windows(m, sid) {
|
||||
let out = {};
|
||||
for (let id, d in m.devices) {
|
||||
let s = m.people[d.person]?.server;
|
||||
if (sid == null || s == sid)
|
||||
out[id] = online_window(m.servers[s], d);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
* Dawnline's tunnels as dawnline.awg.dump() reads them (only those, each on
|
||||
* its own: { ok, reads, ifaces, peers: { public key: { ifname, endpoint,
|
||||
* handshake, rx, tx } } }), plus `presence`, the agent watcher's, `windows`,
|
||||
* each device's online_window() (online() without the agent), `link`, the
|
||||
* watcher's LINK ({} without the agent: its states would be stale), and
|
||||
* `setup`, its SETUP (null without the agent: nobody tells data from a bare
|
||||
* handshake then, view.device_view goes by the handshake). With `sid` only
|
||||
* that server's tunnel is read (one person's page needs no other: one `awg`
|
||||
* process, not one per server).
|
||||
*/
|
||||
export function dump(m, sid) {
|
||||
let d = awg.dump(tunnel_ifnames(m, sid));
|
||||
let up = agent_running();
|
||||
d.presence = up ? read_json(PRESENCE, null) : null;
|
||||
d.windows = online_windows(m, sid);
|
||||
d.link = up ? (read_json(LINK, null) ?? {}) : {};
|
||||
d.setup = up ? (read_json(SETUP, null) ?? {}) : null;
|
||||
return d;
|
||||
};
|
||||
|
||||
@@ -121,11 +192,15 @@ export function online(dmp, id, peer) {
|
||||
let p = dmp?.presence?.online;
|
||||
if (p)
|
||||
return !!(peer && p[id]);
|
||||
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
|
||||
return !!(peer && peer.handshake > 0 && time() - peer.handshake < (dmp?.windows?.[id] ?? ONLINE_WINDOW));
|
||||
};
|
||||
|
||||
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
|
||||
// the agent's watcher asks for every device, every second.
|
||||
const ENDPOINT = /^\[?([^\]]+)\]?:[0-9]+$/;
|
||||
|
||||
export function endpoint_ip(ep) {
|
||||
let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
|
||||
let m = match(ep ?? '', ENDPOINT);
|
||||
return m ? m[1] : ep;
|
||||
};
|
||||
|
||||
@@ -214,34 +289,36 @@ function offline(rec) {
|
||||
|
||||
/**
|
||||
* Fold the current kernel counters into `usage`. Counters restart from zero
|
||||
* when a peer is re-added or the interface restarts; a drop is treated as a
|
||||
* reset. Returns the per-device live view keyed by device id.
|
||||
* when a peer is re-added or its tunnel is set up again; a drop is treated
|
||||
* as a reset, and so is a new link (each record keeps the interface index
|
||||
* its counters were read on: new counters that already passed the old ones
|
||||
* would be counted short). Returns the per-device live view keyed by device id.
|
||||
*
|
||||
* A device missing from the dump had its counters reset only when its tunnel
|
||||
* was actually read: an interface the tool couldn't read says nothing, and
|
||||
* forgetting the last counters there would count them again on the next good
|
||||
* read. A failed read with nothing in it changes nothing at all.
|
||||
* was read or is down (dawnline.awg.dump's `reads`): one the tool couldn't
|
||||
* read says nothing, and forgetting the last counters there would count them
|
||||
* again on the next good read.
|
||||
*/
|
||||
export function collect(m, usage, d) {
|
||||
d ??= dump(m);
|
||||
let ts = time();
|
||||
let live = {};
|
||||
if (d.ok === false && !length(d.peers)) {
|
||||
for (let id in keys(m.devices))
|
||||
live[id] = offline(usage.devices[id]);
|
||||
return live;
|
||||
}
|
||||
for (let id, dev in m.devices) {
|
||||
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
|
||||
let peer = d.peers[dev.public_key];
|
||||
if (!peer) {
|
||||
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
|
||||
if (d.ok !== false || d.ifaces[ifname] != null)
|
||||
if (d.reads[ifname] != 'error')
|
||||
rec.raw = [ 0, 0 ];
|
||||
live[id] = offline(rec);
|
||||
continue;
|
||||
}
|
||||
let raw = rec.raw ?? [ 0, 0 ];
|
||||
let link = d.ifaces[peer.ifname]?.ifindex;
|
||||
if (link != null && rec.ifindex != null && link != rec.ifindex)
|
||||
raw = [ 0, 0 ];
|
||||
if (link != null)
|
||||
rec.ifindex = link;
|
||||
let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx;
|
||||
let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx;
|
||||
rec.raw = [ peer.rx, peer.tx ];
|
||||
@@ -262,7 +339,7 @@ export function collect(m, usage, d) {
|
||||
delete rec.ips[ips[i]];
|
||||
}
|
||||
live[id] = {
|
||||
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
|
||||
online: peer.handshake > 0 && ts - peer.handshake < online_window(m.servers[m.people[dev.person]?.server], dev),
|
||||
handshake: peer.handshake || rec.handshake || 0,
|
||||
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
|
||||
present: true,
|
||||
@@ -369,7 +446,10 @@ export function add_event(e) {
|
||||
add_events([ e ]);
|
||||
};
|
||||
|
||||
/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */
|
||||
/**
|
||||
* Like add_event, but folds into the previous event of the same kind, person
|
||||
* and device (when it has one) within `window` s.
|
||||
*/
|
||||
export function add_event_merged(e, window) {
|
||||
let pol = policy();
|
||||
if (index(pol.categories, category_of(e.type)) < 0)
|
||||
@@ -378,7 +458,7 @@ export function add_event_merged(e, window) {
|
||||
let ev = load_events();
|
||||
let last = ev[length(ev) - 1];
|
||||
let ts = time();
|
||||
if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) {
|
||||
if (last && last.type == e.type && last.person == e.person && last.device == e.device && ts - last.ts < (window ?? 120)) {
|
||||
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
|
||||
last.detail = join(', ', filter(parts, (x) => x != ''));
|
||||
last.ts = ts;
|
||||
|
||||
@@ -7,13 +7,24 @@
|
||||
// └── NAT to a LAN address ┘
|
||||
//
|
||||
// The netns is one more device on the LAN bridge with its own address (picked
|
||||
// from the LAN subnet above the DHCP pool). Replies come back the same way.
|
||||
// from the LAN subnet above the DHCP pool) and its own MAC (hashed from the
|
||||
// bridge's), the same each time it is created: the router's neighbour table
|
||||
// knows the address by that MAC, so a netns created again keeps its address
|
||||
// instead of seeing it held by another device. Replies come back the same way.
|
||||
// Home-network destinations keep their direct route; per-person access is
|
||||
// still enforced on dawn0 before any of this (table inet dawnline).
|
||||
//
|
||||
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
|
||||
// gets from DHCP, from the LAN side, so DNS interception applies as well.
|
||||
//
|
||||
// The netns forwards and NATs every packet a second time (conntrack, the
|
||||
// forward hook): about 40% more CPU per packet on an MT7981. A flowtable on
|
||||
// its two links (dlx1, dll1) lets established TCP and UDP flows skip that
|
||||
// work. The netns holds no access rules: who may reach what is judged on the
|
||||
// tunnel interfaces in the root namespace, which no flowtable here touches.
|
||||
// Without kernel flowtables (kmod-nft-offload) the loop runs as before,
|
||||
// slower, and logs it once.
|
||||
//
|
||||
// Separately, people with Home-only access get a plain resolver
|
||||
// (dawnline.resolver). While the netns exists it runs inside it and sends its
|
||||
// upstream queries back out through the transit link as forwarded traffic —
|
||||
@@ -41,6 +52,7 @@ const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.la
|
||||
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
|
||||
export const RESOLVER_CONF = resolver.CONF;
|
||||
const STATE = `${RUN_DIR}/loop.json`;
|
||||
const NS_RULES = '/var/etc/dawnline-ns.nft';
|
||||
|
||||
const WHO = L_('Internet like a home device');
|
||||
|
||||
@@ -106,39 +118,64 @@ function used_addresses(dev) {
|
||||
return used;
|
||||
}
|
||||
|
||||
/** The MAC the netns's LAN link has now; null without the link. */
|
||||
function our_mac() {
|
||||
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
|
||||
}
|
||||
|
||||
/** 32-bit FNV-1a of a string, continuing from `h`. */
|
||||
function fnv1a(s, h) {
|
||||
for (let i = 0; i < length(s); i++)
|
||||
h = ((h ^ ord(s, i)) * 16777619) & 0xffffffff;
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* A LAN address for the netns: keep the saved one while it is valid and not
|
||||
* taken by someone else, otherwise the highest free host above the DHCP pool
|
||||
* (then below it), skipping static leases and anything that answers.
|
||||
* The MAC for the netns's LAN link, from the bridge's MAC: a locally
|
||||
* administered unicast address hashed from it, so it is the same every time
|
||||
* and differs between routers. Not the bridge's MAC with a bit flipped: radios
|
||||
* and ports often get those.
|
||||
*/
|
||||
function pick_address(lan, facts, saved, dev) {
|
||||
export function lan_mac(bridge) {
|
||||
let s = lc(trim(bridge ?? ''));
|
||||
let h1 = fnv1a(`dawnline lan ${s}`, 0x811c9dc5), h2 = fnv1a(s, h1);
|
||||
let b = [ ((h1 >> 24) & 0xfc) | 0x02, (h1 >> 16) & 0xff, (h1 >> 8) & 0xff, h1 & 0xff, (h2 >> 24) & 0xff, (h2 >> 16) & 0xff ];
|
||||
return join(':', map(b, (x) => sprintf('%02x', x)));
|
||||
};
|
||||
|
||||
/**
|
||||
* True when the netns may use a LAN address (a number): a host of the
|
||||
* network, not the router's, not a static lease, outside the DHCP pool and
|
||||
* not held by another device in `used` (address → MAC, or true without one).
|
||||
* An entry with one of the MACs in `mine` is the netns itself, also from
|
||||
* before it was created again.
|
||||
*/
|
||||
export function address_free(ip, lan, facts, used, mine) {
|
||||
if (ip <= lan.net || ip >= lan.net + lan.size - 1 || ip == lan.ip || index(facts.statics, ip) >= 0)
|
||||
return false;
|
||||
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
||||
return false;
|
||||
let u = used[int2ip(ip)];
|
||||
return u == null || index(mine, u) >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* A LAN address for the netns: keep the saved one while it is free (see
|
||||
* address_free; `mine` are the netns's MACs), otherwise the highest free host
|
||||
* above the DHCP pool (then below it) that does not answer.
|
||||
*/
|
||||
function pick_address(lan, facts, saved, dev, mine) {
|
||||
let used = used_addresses(dev);
|
||||
let mine = our_mac();
|
||||
let taken = (ip) => {
|
||||
let s = int2ip(ip);
|
||||
if (ip == lan.ip || index(facts.statics, ip) >= 0)
|
||||
return true;
|
||||
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
|
||||
return true;
|
||||
let u = used[s];
|
||||
return u != null && !(mine && u == mine);
|
||||
};
|
||||
let sv = ip2int(saved ?? '');
|
||||
if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv))
|
||||
if (sv != null && address_free(sv, lan, facts, used, mine))
|
||||
return int2ip(sv);
|
||||
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
|
||||
if (taken(ip))
|
||||
if (!address_free(ip, lan, facts, used, mine))
|
||||
continue;
|
||||
// Last check: nobody answers on it.
|
||||
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
|
||||
let again = used_addresses(dev)[int2ip(ip)];
|
||||
if (again != null && !(mine && again == mine))
|
||||
continue;
|
||||
return int2ip(ip);
|
||||
if (address_free(ip, lan, facts, used_addresses(dev), mine))
|
||||
return int2ip(ip);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -271,7 +308,9 @@ export function plan(m) {
|
||||
return { error: { code: 'no_ipv4', dev } };
|
||||
let facts = dhcp_facts(d.logical, lan);
|
||||
let st = settings();
|
||||
let addr = pick_address(lan, facts, st.lan_address, dev);
|
||||
let mac = lan_mac(readfile(`/sys/class/net/${dev}/address`));
|
||||
// The netns's MACs: the one it gets, and the one it has (a random one from an older version).
|
||||
let addr = pick_address(lan, facts, st.lan_address, dev, [ mac, our_mac() ]);
|
||||
if (!addr)
|
||||
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
|
||||
let last = read_json(STATE, {});
|
||||
@@ -291,6 +330,7 @@ export function plan(m) {
|
||||
dev,
|
||||
gateway: int2ip(lan.ip),
|
||||
address: addr,
|
||||
mac,
|
||||
prefix: lan.prefix,
|
||||
dns: facts.dns ?? int2ip(lan.ip),
|
||||
transit: tx,
|
||||
@@ -303,10 +343,20 @@ export function plan(m) {
|
||||
|
||||
/* ---------- apply ---------- */
|
||||
|
||||
function ns_rules(p) {
|
||||
/**
|
||||
* The netns's nft script as text (nothing is loaded). With `fast`, a
|
||||
* flowtable on the netns's own two links takes established TCP and UDP flows
|
||||
* past conntrack and the forward hook here. Only dlx1 and dll1: the root
|
||||
* namespace's links (dawn0, dlx0) stay out, the guard there sees every packet.
|
||||
*/
|
||||
export function ns_rules(p, fast) {
|
||||
return `table inet dawnline
|
||||
delete table inet dawnline
|
||||
table inet dawnline {
|
||||
table inet dawnline {${fast ? `
|
||||
flowtable ft {
|
||||
hook ingress priority 0;
|
||||
devices = { "${TX_NS}", "${LAN_NS}" };
|
||||
}` : ''}
|
||||
chain nat_pre {
|
||||
type nat hook prerouting priority dstnat; policy accept;
|
||||
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
|
||||
@@ -316,7 +366,8 @@ table inet dawnline {
|
||||
oifname "${LAN_NS}" masquerade
|
||||
}
|
||||
chain filter_forward {
|
||||
type filter hook forward priority filter; policy drop;
|
||||
type filter hook forward priority filter; policy drop;${fast ? `
|
||||
ct state established meta l4proto { tcp, udp } flow add @ft` : ''}
|
||||
ct state established,related accept
|
||||
iifname "${TX_NS}" oifname "${LAN_NS}" accept
|
||||
}
|
||||
@@ -329,8 +380,40 @@ table inet dawnline {
|
||||
}
|
||||
}
|
||||
`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Load the netns's rules, with the flowtable when the kernel takes it, else
|
||||
* without (the loop works either way). { fast, slow, err }: slow is why the
|
||||
* flowtable failed, err why the rules without it failed too.
|
||||
*/
|
||||
function load_ns_rules(p) {
|
||||
ensure_dir('/var/etc');
|
||||
let load = (fast) => {
|
||||
writefile(NS_RULES, ns_rules(p, fast));
|
||||
return run([ `ip netns exec ${NS} nft -f ${NS_RULES}` ])[0];
|
||||
};
|
||||
let slow = load(true);
|
||||
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The policy rules plan `p` wants (pure), in order: [{ pref, iif, to, table }]
|
||||
* (to null: all). Per server interface: DNS to the netns address through the
|
||||
* netns, home networks and the tunnel network by main, the rest into the netns.
|
||||
*/
|
||||
export function rules(p) {
|
||||
let out = [];
|
||||
let rule = (pref, iif, to, table) => push(out, { pref, iif, to, table });
|
||||
for (let s in p?.servers ?? []) {
|
||||
rule(PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}`);
|
||||
for (let n in s.direct)
|
||||
rule(PREF_MAIN, s.ifname, n, 'main');
|
||||
rule(PREF_LOOP, s.ifname, null, `${p.table}`);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
|
||||
function current_rules(ifnames) {
|
||||
let out = [];
|
||||
@@ -345,31 +428,58 @@ function current_rules(ifnames) {
|
||||
}
|
||||
|
||||
|
||||
function rule_key(pref, iif, to, table) {
|
||||
// `ip -j rule` shows a /32 destination without its length.
|
||||
if (to && index(to, '/') < 0)
|
||||
to += '/32';
|
||||
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
|
||||
// A rule of ours with a source (none of rules() has one) is told apart, so it is removed.
|
||||
function rule_key(pref, from, iif, to, table) {
|
||||
// `ip -j rule` shows a /32 source or destination without its length.
|
||||
let full = (n) => n && index(n, '/') < 0 ? `${n}/32` : n;
|
||||
return `${pref} ${full(from) ?? 'all'} ${iif} ${full(to) ?? 'all'} ${table}`;
|
||||
}
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
let want = [];
|
||||
for (let s in p?.servers ?? []) {
|
||||
push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]);
|
||||
for (let n in s.direct)
|
||||
push(want, [ PREF_MAIN, s.ifname, n, 'main' ]);
|
||||
push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]);
|
||||
/**
|
||||
* A source or destination as `ip -j rule` has it ("10.9.0.2", or with its
|
||||
* length), or null for all: a rule without a source shows `"src": "all"`
|
||||
* (iproute2 prints "from all"), one without a destination no `dst`.
|
||||
*/
|
||||
function rule_net(addr, len) {
|
||||
return addr && addr != 'all' ? `${addr}${len != null ? '/' + len : ''}` : null;
|
||||
}
|
||||
|
||||
/** The command that removes one of current_rules(). */
|
||||
function rule_del(r) {
|
||||
let from = rule_net(r.src, r.srclen), to = rule_net(r.dst, r.dstlen);
|
||||
return `ip -4 rule del priority ${r.priority}${from ? ' from ' + from : ''} iif ${q(r.iif)}${to ? ' to ' + to : ''} lookup ${r.table}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands that turn rules `current` (ours, as `ip -j -4 rule show`
|
||||
* prints them) into rules(p) (pure): the missing ones added first, then the
|
||||
* ones no longer wanted removed, so a device's traffic never falls between
|
||||
* two rules while others change. [] when they are as wanted.
|
||||
*/
|
||||
export function rule_cmds(p, current) {
|
||||
let have = {}, want = {}, cmds = [], twice = [];
|
||||
for (let r in current) {
|
||||
let k = rule_key(r.priority, rule_net(r.src, r.srclen), r.iif, rule_net(r.dst, r.dstlen), r.table);
|
||||
if (have[k])
|
||||
push(twice, rule_del(r));
|
||||
have[k] = r;
|
||||
}
|
||||
let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table));
|
||||
let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3]));
|
||||
if (join('\n', sort(have)) == join('\n', sort(wantk)))
|
||||
return [];
|
||||
let cmds = [];
|
||||
for (let r in current_rules(ifnames))
|
||||
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
|
||||
for (let w in want)
|
||||
push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`);
|
||||
for (let w in rules(p)) {
|
||||
let k = rule_key(w.pref, null, w.iif, w.to, w.table);
|
||||
if (!have[k] && !want[k])
|
||||
push(cmds, `ip -4 rule add priority ${w.pref} iif ${q(w.iif)}${w.to ? ' to ' + w.to : ''} lookup ${w.table}`);
|
||||
want[k] = true;
|
||||
}
|
||||
for (let k, r in have)
|
||||
if (!want[k])
|
||||
push(cmds, rule_del(r));
|
||||
// The same rule twice (one deletion removes one of them).
|
||||
push(cmds, ...twice);
|
||||
return cmds;
|
||||
};
|
||||
|
||||
function sync_rules(p, ifnames) {
|
||||
return rule_cmds(p, current_rules(ifnames));
|
||||
}
|
||||
|
||||
function tunnel_ifnames() {
|
||||
@@ -382,21 +492,25 @@ function tunnel_ifnames() {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove the netns, links and rules. */
|
||||
/** Remove the netns, links and rules, and the router's neighbour entry for the netns. */
|
||||
export function remove(ifnames) {
|
||||
ifnames ??= tunnel_ifnames();
|
||||
let cmds = [];
|
||||
for (let r in current_rules(ifnames))
|
||||
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
|
||||
let t = read_json(STATE, {})?.plan?.table;
|
||||
if (t)
|
||||
push(cmds, `ip -4 route flush table ${t}`);
|
||||
let last = read_json(STATE, {})?.plan;
|
||||
// Read while the link is there: the entry is ours when it carries the netns's MAC.
|
||||
let held = last?.dev ? used_addresses(last.dev)[last.address] : null;
|
||||
let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0;
|
||||
let cmds = map(current_rules(ifnames), rule_del);
|
||||
if (last?.table)
|
||||
push(cmds, `ip -4 route flush table ${last.table}`);
|
||||
if (exists(TX_ROOT))
|
||||
push(cmds, `ip link del ${TX_ROOT}`);
|
||||
if (exists(LAN_ROOT))
|
||||
push(cmds, `ip link del ${LAN_ROOT}`);
|
||||
if (stat(`/var/run/netns/${NS}`))
|
||||
push(cmds, `ip netns del ${NS}`);
|
||||
// Left there, it would hold the address for a MAC nobody has.
|
||||
if (stale)
|
||||
push(cmds, `ip -4 neigh del ${q(last.address)} dev ${q(last.dev)}`);
|
||||
run(cmds);
|
||||
unlink(STATE);
|
||||
};
|
||||
@@ -427,13 +541,18 @@ export function ensure(m, force) {
|
||||
if (same && healthy && !length(rules))
|
||||
return p;
|
||||
|
||||
// A link made by an older version has a random MAC (its plan had none, so
|
||||
// this runs once after an update): it gets the stable one.
|
||||
let remac = exists(LAN_ROOT) && our_mac() != p.mac;
|
||||
let cmds = [];
|
||||
if (!stat(`/var/run/netns/${NS}`))
|
||||
push(cmds, `ip netns add ${NS}`);
|
||||
if (!exists(TX_ROOT))
|
||||
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
|
||||
if (!exists(LAN_ROOT))
|
||||
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`);
|
||||
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} address ${p.mac} netns ${NS}`);
|
||||
if (remac)
|
||||
push(cmds, `ip -n ${NS} link set ${LAN_NS} down`, `ip -n ${NS} link set ${LAN_NS} address ${p.mac}`);
|
||||
let errs = run(cmds);
|
||||
cmds = [
|
||||
`ip addr flush dev ${TX_ROOT}`,
|
||||
@@ -457,10 +576,13 @@ export function ensure(m, force) {
|
||||
];
|
||||
for (let s in p.servers)
|
||||
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
|
||||
ensure_dir('/var/etc');
|
||||
writefile('/var/etc/dawnline-ns.nft', ns_rules(p));
|
||||
push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`);
|
||||
// The router knows the address by the old MAC: ask again now, not when the entry expires.
|
||||
if (remac)
|
||||
push(cmds, `ip -4 neigh flush to ${p.address} dev ${q(p.dev)}`);
|
||||
push(errs, ...run(cmds));
|
||||
let ft = load_ns_rules(p);
|
||||
if (ft.err)
|
||||
push(errs, ft.err);
|
||||
push(errs, ...run(sync_rules(p, ifnames)));
|
||||
|
||||
if (length(errs)) {
|
||||
@@ -472,11 +594,17 @@ export function ensure(m, force) {
|
||||
return { error: why };
|
||||
}
|
||||
ensure_dir(RUN_DIR);
|
||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
|
||||
write_json(STATE, { applied: time(), plan: p, transit: p.transit, fast: ft.fast }, 0o644);
|
||||
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
|
||||
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
|
||||
else if (!healthy)
|
||||
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
|
||||
// Once, not again on every apply while the module is still missing.
|
||||
if (!ft.fast && last.fast !== false)
|
||||
log(L_('runs without its fast path'), 'info', join('\n', [
|
||||
L_('Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.'),
|
||||
ft.slow,
|
||||
]));
|
||||
return p;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// Dawnline — the live meter (the Overview's Speed now): each server's
|
||||
// throughput, one point a second over the last two minutes.
|
||||
//
|
||||
// The meter RPC (dawnline.rpc.status) calls want() and read(); the agent's
|
||||
// watcher makes a point from every read it already does (sample(), point())
|
||||
// and keeps the last two minutes in memory (keep()) whether anyone looks or
|
||||
// not, so a look gets them all at once. It writes them to FILE (save()) only
|
||||
// while WANT is younger than WANT_FOR seconds: the first second of a look,
|
||||
// then with each new point. When WANT goes stale it removes FILE: with nobody
|
||||
// looking the watcher pays a little arithmetic and one stat() a second, and
|
||||
// writes nothing. FILE holds server ids and byte rates only, no keys, names
|
||||
// or personal codes. Who is online and the per-minute rates are not here
|
||||
// (dawnline.live, the agent's tick).
|
||||
//
|
||||
// Bytes are the peers' counters (dawnline.awg.dump): tx includes the
|
||||
// disguise (S prefixes, padding, junk), rx the packets as they were
|
||||
// received without their prefix, so both are close to what is on the wire.
|
||||
|
||||
import { writefile, stat, unlink } from 'fs';
|
||||
import { read_json, write_file, ensure_dir, RUN_DIR } from 'dawnline.util';
|
||||
|
||||
/** Touched by every meter RPC: the watcher samples while it is fresh. */
|
||||
export const WANT = `${RUN_DIR}/meter.want`;
|
||||
/** The points, written by the watcher each second while WANT is fresh. */
|
||||
export const FILE = `${RUN_DIR}/meter.json`;
|
||||
/** Seconds after the last meter RPC the watcher keeps sampling. */
|
||||
export const WANT_FOR = 10;
|
||||
/** Points kept: two minutes, one a second. */
|
||||
export const POINTS = 120;
|
||||
|
||||
/** Ask the watcher to sample for the next WANT_FOR seconds (the meter RPC). */
|
||||
export function want() {
|
||||
ensure_dir(RUN_DIR);
|
||||
writefile(WANT, `${time()}`);
|
||||
};
|
||||
|
||||
/** Someone asked for the meter within WANT_FOR seconds of `now`. */
|
||||
export function wanted(now) {
|
||||
let st = stat(WANT);
|
||||
return st != null && now - st.mtime < WANT_FOR && st.mtime - now < WANT_FOR;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the watcher wrote, for the RPC: { now, want: WANT_FOR, keep: POINTS,
|
||||
* ts (newest point, 0 for none), points } with only the points newer than
|
||||
* `since` when it is given (a page that polls asks for what it lacks).
|
||||
* No points when nobody asked within WANT_FOR seconds or the agent is not
|
||||
* running: FILE is gone (the agent removes it as it stops and starts), or,
|
||||
* from one that died while someone looked, its newest point is over
|
||||
* WANT_FOR seconds old (ts then stops moving).
|
||||
*/
|
||||
export function read(since) {
|
||||
let f = read_json(FILE, null);
|
||||
let ts = +(f?.ts ?? 0);
|
||||
let pts = type(f?.points) == 'array' && time() - ts <= WANT_FOR ? f.points : [];
|
||||
if (since > 0)
|
||||
pts = filter(pts, (p) => p.ts > since);
|
||||
return { now: time(), want: WANT_FOR, keep: POINTS, ts: ts, points: pts };
|
||||
};
|
||||
|
||||
/** Monotonic seconds, with the fraction: the gap between two samples. */
|
||||
function mono() {
|
||||
let c = clock(true);
|
||||
return c[0] + c[1] / 1e9;
|
||||
}
|
||||
|
||||
/**
|
||||
* One sample at `now` from the dump the watcher just read (`d`): { t, ts,
|
||||
* servers: [ server id ] (those whose tunnel was read), dev: { device id:
|
||||
* [ rx, tx, server id ] } (its peer's counters, on those servers) }. Nothing
|
||||
* but the dump is read.
|
||||
*/
|
||||
export function sample(m, d, now) {
|
||||
let s = { t: mono(), ts: now, servers: [], dev: {} };
|
||||
let read = {};
|
||||
for (let sid, srv in m.servers)
|
||||
if (d.reads[srv.ifname] == 'read') {
|
||||
read[sid] = true;
|
||||
push(s.servers, sid);
|
||||
}
|
||||
for (let id, dev in m.devices) {
|
||||
let peer = d.peers[dev.public_key];
|
||||
let sid = m.people[dev.person]?.server;
|
||||
if (peer && read[sid])
|
||||
s.dev[id] = [ peer.rx, peer.tx, sid ];
|
||||
}
|
||||
return s;
|
||||
};
|
||||
|
||||
/** A counter's change, 0 when it went down (a tunnel set up again starts from zero). */
|
||||
function delta(a, b) {
|
||||
return (b ?? 0) >= (a ?? 0) ? (b ?? 0) - (a ?? 0) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The point between samples `a` and `b`, null when they are not a second or
|
||||
* so apart (the first sample, a stalled watcher): { ts, servers: { server
|
||||
* id: [ rx, tx ] } }, bytes per second of its devices together (rx what came
|
||||
* from them, tx what went to them, as a server's per-minute `rate`), for
|
||||
* every server whose tunnel `b` read ([ 0, 0 ] when nothing moved). A device
|
||||
* is counted from its second sample on, on the server it was on in both.
|
||||
*/
|
||||
export function point(a, b) {
|
||||
let dt = b.t - a.t;
|
||||
if (!(dt > 0.2 && dt < 5))
|
||||
return null;
|
||||
let sum = {};
|
||||
for (let sid in b.servers)
|
||||
sum[sid] = [ 0, 0 ];
|
||||
for (let id, v in b.dev) {
|
||||
let o = a.dev[id];
|
||||
if (!o || o[2] != v[2])
|
||||
continue;
|
||||
sum[v[2]][0] += delta(o[0], v[0]);
|
||||
sum[v[2]][1] += delta(o[1], v[1]);
|
||||
}
|
||||
let p = { ts: b.ts, servers: {} };
|
||||
for (let sid, v in sum)
|
||||
p.servers[sid] = [ int(v[0] / dt), int(v[1] / dt) ];
|
||||
return p;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep point `p` in `ring` ([ [ ts, the point as JSON ] ], newest last; each
|
||||
* point is turned into text once, when it is made, not again every second for
|
||||
* as long as it is kept): at most POINTS of them, none older than POINTS
|
||||
* seconds before `p` (the watcher may have stalled in between) and none from
|
||||
* its second or later (the clock went back).
|
||||
*/
|
||||
export function keep(ring, p) {
|
||||
while (length(ring) && ring[length(ring) - 1][0] >= p.ts)
|
||||
pop(ring);
|
||||
push(ring, [ p.ts, sprintf('%J', p) ]);
|
||||
while (length(ring) > POINTS || ring[0][0] <= p.ts - POINTS)
|
||||
shift(ring);
|
||||
};
|
||||
|
||||
/** Write the points kept in `ring` (keep()) to FILE. */
|
||||
export function save(ring) {
|
||||
let ts = length(ring) ? ring[length(ring) - 1][0] : 0;
|
||||
ensure_dir(RUN_DIR);
|
||||
write_file(FILE, `{"ts":${ts},"points":[${join(',', map(ring, (r) => r[1]))}]}`, 0o644);
|
||||
};
|
||||
|
||||
/** Nobody looks any more: FILE goes (the next look gets the points kept then). */
|
||||
export function stop() {
|
||||
if (stat(FILE))
|
||||
unlink(FILE);
|
||||
};
|
||||
@@ -163,7 +163,7 @@ export function snapshot(fresh) {
|
||||
let flags = hex(sysread(dev, 'flags') || '0');
|
||||
let kind = +(sysread(dev, 'type') || '0');
|
||||
let master = readlink(`${SYS}/${dev}/master`);
|
||||
master = master ? replace(master, /^.*\//, '') : null;
|
||||
master = master ? substr(master, rindex(master, '/') + 1) : null;
|
||||
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
|
||||
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
|
||||
let nets = routes[dev] ? collapse(routes[dev]) : [];
|
||||
@@ -295,10 +295,13 @@ export function lan_names() {
|
||||
return out;
|
||||
};
|
||||
|
||||
// A module constant, compiled once: event_hosts runs for every event of the log.
|
||||
const ANY_IPV4 = /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g;
|
||||
|
||||
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
|
||||
export function event_hosts(e, names) {
|
||||
let out = null;
|
||||
for (let ip in match(e.detail ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
|
||||
for (let ip in match(e.detail ?? '', ANY_IPV4) ?? [])
|
||||
if (names[ip[0]])
|
||||
(out ??= {})[ip[0]] = names[ip[0]];
|
||||
return out;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// tunnel of your own, one from an imported config) is left alone and the
|
||||
// server is reported instead. Why a server is kept down is kept in
|
||||
// core.BLOCKED as a code with its values (awg.blocked_text says it).
|
||||
// drift() tells the watchdog when one of them was edited outside Dawnline.
|
||||
|
||||
import { cursor } from 'uci';
|
||||
import { stat, unlink, writefile } from 'fs';
|
||||
@@ -30,6 +31,14 @@ export function owner(ifname, c) {
|
||||
return c.get('network', ifname, '_dawnline') ?? '';
|
||||
};
|
||||
|
||||
/** What sync() writes into network.<ifname> apart from the markers: what netifd sets the tunnel up from. */
|
||||
function options(srv) {
|
||||
let o = awg.netifd_options(srv);
|
||||
o.disabled = srv.enabled ? null : '1';
|
||||
o.auto = srv.enabled ? null : '0';
|
||||
return o;
|
||||
}
|
||||
|
||||
/** Bring network config in line with the servers; true when it changed. */
|
||||
export function sync(m) {
|
||||
let c = cursor();
|
||||
@@ -70,13 +79,15 @@ export function sync(m) {
|
||||
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
|
||||
continue;
|
||||
}
|
||||
// Disguise values AmneziaWG refuses or crashes on (a hand edit in uci;
|
||||
// import and restore refuse them) never reach setconf and the kernel.
|
||||
// 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;
|
||||
let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
|
||||
if (why) {
|
||||
block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
|
||||
block(srv, why, awg.blocked_fix(why));
|
||||
continue;
|
||||
}
|
||||
delete srv.blocked;
|
||||
@@ -85,17 +96,16 @@ export function sync(m) {
|
||||
continue;
|
||||
// Per server: with several, each changed one has to be brought up again.
|
||||
let mine = uci_section(c, 'network', ifn, 'interface');
|
||||
let set = (opt, val) => {
|
||||
if (uci_put(c, 'network', ifn, opt, val))
|
||||
for (let k, v in options(srv))
|
||||
if (uci_put(c, 'network', ifn, k, v))
|
||||
mine = true;
|
||||
};
|
||||
for (let k, v in awg.netifd_options(srv))
|
||||
set(k, v);
|
||||
set('disabled', srv.enabled ? null : '1');
|
||||
set('auto', srv.enabled ? null : '0');
|
||||
set('_dawnline', id);
|
||||
// The markers are saved, but netifd does not read them: a renamed server
|
||||
// keeps its tunnel and every session in it.
|
||||
if (uci_put(c, 'network', ifn, '_dawnline', id))
|
||||
changed = true;
|
||||
// For the log once the server is gone.
|
||||
set('_dawnline_name', srv.name);
|
||||
if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name))
|
||||
changed = true;
|
||||
if (mine) {
|
||||
changed = true;
|
||||
push(touched, ifn);
|
||||
@@ -125,6 +135,9 @@ export function sync(m) {
|
||||
if (changed) {
|
||||
c.commit('network');
|
||||
ack_config([ 'network' ]);
|
||||
}
|
||||
// Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload).
|
||||
if (length(touched) || length(stale)) {
|
||||
system('ubus call network reload');
|
||||
for (let ifn in touched)
|
||||
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
|
||||
@@ -134,3 +147,29 @@ export function sync(m) {
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
|
||||
/**
|
||||
* For the watchdog: what of each running server's interface differs from
|
||||
* what sync() writes, by option name (a LuCI or uci edit of network.<ifname>,
|
||||
* which would otherwise last until the next apply): { server id: [ names ] },
|
||||
* an empty list when it is as Dawnline set it. Only enabled servers whose
|
||||
* section exists and is theirs (a missing one is the tunnel probe's); the
|
||||
* markers are not compared, netifd does not read them. A dry run on a
|
||||
* cursor of its own: nothing is saved. Meaningful while amneziawg-tools is
|
||||
* installed (sync() leaves the interfaces alone without it).
|
||||
*/
|
||||
export function drift(m) {
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
let out = {};
|
||||
for (let id, srv in m.servers) {
|
||||
if (!srv.enabled || !length(core.tunnels(srv)) || owner(srv.ifname, c) != id || c.get('network', srv.ifname) != 'interface')
|
||||
continue;
|
||||
let diff = [];
|
||||
for (let k, v in options(srv))
|
||||
if (uci_put(c, 'network', srv.ifname, k, v))
|
||||
push(diff, k);
|
||||
out[id] = diff;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
@@ -10,7 +10,8 @@ import * as core from 'dawnline.core';
|
||||
import * as net from 'dawnline.net';
|
||||
import * as loop from 'dawnline.loop';
|
||||
|
||||
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
/** Private IPv4 ranges: internet people never reach them (awg.BYPASS4 is the rest). */
|
||||
export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
|
||||
/** The sets whose members change at run time (update replaces them together). */
|
||||
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
|
||||
|
||||
@@ -18,8 +19,11 @@ function ip4(a) {
|
||||
return ip2int(a ?? '') != null;
|
||||
}
|
||||
|
||||
/** Per-person runtime membership: which tunnel addresses may reach what. */
|
||||
export function access_sets(m, usage, states) {
|
||||
/**
|
||||
* Per-person runtime membership: which tunnel addresses may reach what.
|
||||
* `snap` is the network (net.snapshot() when not given).
|
||||
*/
|
||||
export function access_sets(m, usage, states, snap) {
|
||||
// lan_ok: home access (the router itself, the mesh); lan_all: every home
|
||||
// network; lan_part: device . network for people limited to some networks;
|
||||
// mesh_pairs: device . device within a circle (or one person's own devices);
|
||||
@@ -27,7 +31,7 @@ export function access_sets(m, usage, states) {
|
||||
let sets = {};
|
||||
for (let k in SETS)
|
||||
sets[k] = [];
|
||||
let snap = net.snapshot();
|
||||
snap ??= net.snapshot();
|
||||
let homes = {}, groups = {};
|
||||
for (let id, d in m.devices) {
|
||||
let p = m.people[d.person];
|
||||
@@ -91,13 +95,23 @@ function portal_ports(m) {
|
||||
return ports;
|
||||
}
|
||||
|
||||
function table(m, sets) {
|
||||
/**
|
||||
* What the table is made from besides the model, read from the router: the
|
||||
* netns's DNS address (loop.client_dns), where the Home-only resolver runs
|
||||
* (loop.resolver_target), the LAN's DNS and the network snapshot.
|
||||
*/
|
||||
function router_ctx() {
|
||||
return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() };
|
||||
}
|
||||
|
||||
function table(m, sets, ctx) {
|
||||
ctx ??= router_ctx();
|
||||
let ifs = [], tun = [];
|
||||
let dns_addr = loop.client_dns();
|
||||
let dns_addr = ctx.dns_addr;
|
||||
if (!ip4(dns_addr))
|
||||
dns_addr = null;
|
||||
let rt = loop.resolver_target();
|
||||
let snap = net.snapshot();
|
||||
let rt = ctx.resolver;
|
||||
let snap = ctx.snap;
|
||||
// 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 = {};
|
||||
@@ -194,7 +208,7 @@ function table(m, sets) {
|
||||
push(t, ' }');
|
||||
// Devices ask the tunnel address; send each query where it belongs.
|
||||
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
|
||||
let lan_dns = loop.lan_dns();
|
||||
let lan_dns = ctx.lan_dns;
|
||||
if (!ip4(lan_dns))
|
||||
lan_dns = null;
|
||||
push(t, ' chain dns {');
|
||||
@@ -228,9 +242,13 @@ export function load(script) {
|
||||
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
|
||||
};
|
||||
|
||||
/** The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. */
|
||||
export function render(m, sets) {
|
||||
return table(m, sets);
|
||||
/**
|
||||
* The table as text, for a check (`nft -c -f`) or a test; nothing is loaded.
|
||||
* `ctx` (a test's) stands for what is read from the router: { dns_addr,
|
||||
* resolver, lan_dns, snap } (router_ctx).
|
||||
*/
|
||||
export function render(m, sets, ctx) {
|
||||
return table(m, sets, ctx);
|
||||
};
|
||||
|
||||
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
|
||||
|
||||
@@ -47,13 +47,28 @@ export function version(name) {
|
||||
return found ? trim(found[2]) : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The package a control text names: { name, version }, each null when it
|
||||
* does not say. Pure: an ipk's control file (ipk true), else `apk adbdump`
|
||||
* of an apk, whose first name and version are the package's own (its files
|
||||
* are "- name:" entries further down).
|
||||
*/
|
||||
export function control_info(text, ipk) {
|
||||
if (ipk)
|
||||
return { name: match(text, /(^|\n)Package: *([^\n]+)/)?.[2], version: match(text, /(^|\n)Version: *([^\n]+)/)?.[2] };
|
||||
return { name: match(text, /\n *name: *([^\n]+)/)?.[1], version: match(text, /\n *version: *([^\n]+)/)?.[1] };
|
||||
};
|
||||
|
||||
/** The package inside a file: { name, version }, each null when the file does not say. */
|
||||
export function file_info(path) {
|
||||
if (match(path, /\.ipk$/))
|
||||
return control_info(run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out, true);
|
||||
return control_info(run(`apk adbdump ${q(path)}`).out, false);
|
||||
};
|
||||
|
||||
/** The version inside a package file, or null. */
|
||||
export function file_version(path) {
|
||||
if (match(path, /\.ipk$/)) {
|
||||
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
|
||||
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
|
||||
}
|
||||
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
|
||||
return file_info(path).version;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -105,22 +120,54 @@ function preflight(files, need_kb, log) {
|
||||
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
|
||||
}
|
||||
|
||||
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
|
||||
/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */
|
||||
const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc';
|
||||
|
||||
/**
|
||||
* The packages an apk install did not leave at their file's version: apk
|
||||
* takes a given file as it is (an older version too, a rollback) but leaves
|
||||
* an installed version alone, whatever the file. Pure: want [{ name,
|
||||
* version, file }] from the files (file_info()), have { name: installed
|
||||
* version }. [] when every package took.
|
||||
*/
|
||||
export function mismatched(want, have) {
|
||||
return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version);
|
||||
};
|
||||
|
||||
/**
|
||||
* Package files (from a release): true when every one is installed. force
|
||||
* also reinstalls the same version or goes back to an older one (opkg; apk
|
||||
* takes a file as it is: Dawnline's own package is checked by a file of it,
|
||||
* any other by its installed version).
|
||||
*/
|
||||
export function install_files(files, force, log) {
|
||||
preflight(files, 0, log);
|
||||
let args = join(' ', map(files, q));
|
||||
if (!is_apk())
|
||||
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
|
||||
// apk leaves an installed version alone, whatever the file: a reinstall
|
||||
// that changed nothing is a failure, not a silent "done".
|
||||
let marker = '/usr/share/ucode/dawnline/util.uc';
|
||||
let before = force ? stat(marker)?.mtime : null;
|
||||
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
|
||||
if (ok && force && before != null && stat(marker)?.mtime == before) {
|
||||
log?.(' ' + _('apk did not reinstall the version that is already installed'));
|
||||
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
|
||||
let want = map(files, (f) => ({ ...file_info(f), file: f }));
|
||||
let own = length(filter(want, (w) => w.name == SELF)) > 0;
|
||||
// Dawnline's own reinstall that changed nothing is a failure, not a silent "done".
|
||||
let before = own && force ? stat(SELF_MARKER)?.mtime : null;
|
||||
if (logged(`apk add --allow-untrusted ${args}`, log).code != 0)
|
||||
return false;
|
||||
if (own) {
|
||||
if (force && before != null && stat(SELF_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 true;
|
||||
}
|
||||
return ok;
|
||||
// Any other package took when it is at its file's version (the same
|
||||
// version again counts: apk keeps the installed one).
|
||||
let have = {};
|
||||
for (let w in want)
|
||||
if (w.name != null)
|
||||
have[w.name] = version(w.name);
|
||||
let bad = mismatched(want, have);
|
||||
for (let w in bad)
|
||||
log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-'));
|
||||
return !length(bad);
|
||||
};
|
||||
|
||||
/** Packages by name from the feeds. */
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Dawnline — the personal portal.
|
||||
//
|
||||
// GET /<code> the app shell
|
||||
// GET /<code>/assets/<file> its script, styles and fonts
|
||||
// GET /<code>/assets/<file> its script and styles (gzipped when the browser takes it)
|
||||
// GET /<code>/api/state
|
||||
// POST /<code>/api/devices { name, kind, public_key? }
|
||||
// POST /<code>/api/devices { name, kind, public_key?, lan_bypass? }
|
||||
// GET /<code>/api/devices/<id>/config
|
||||
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
|
||||
//
|
||||
@@ -45,7 +45,7 @@ import { _ } from 'dawnline.i18n';
|
||||
|
||||
const RATE = `${RUN_DIR}/portal-rate.json`;
|
||||
const ASSETS = '/usr/share/dawnline/portal/assets';
|
||||
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2', png: 'image/png' };
|
||||
const TYPES = { js: 'text/javascript', css: 'text/css', png: 'image/png' };
|
||||
const FAIL_LIMIT = 8;
|
||||
const FAIL_WINDOW = 900;
|
||||
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
|
||||
@@ -263,24 +263,26 @@ function place(r) {
|
||||
|
||||
/** The app shell; it reads the code from its own URL and sends it along. */
|
||||
function shell(r) {
|
||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
||||
// The build's time joins the version: every update gives the assets new URLs, so they are cached for good.
|
||||
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||
let base = r.base, title = place(r);
|
||||
// The icon goes in the page: a request of its own would start another CGI process.
|
||||
let icon = readfile(`${ASSETS}/icon.svg`);
|
||||
let favicon = icon ? `<link rel="icon" href="data:image/svg+xml;base64,${b64enc(icon)}" type="image/svg+xml">\n` : '';
|
||||
headers(r, '200 OK', {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
||||
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; " +
|
||||
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
|
||||
});
|
||||
r.io.write(`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>${html_escape(title)}</title>
|
||||
<link rel="icon" href="${base}/assets/icon.svg${v}" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="${base}/assets/portal.css${v}">
|
||||
${favicon}<link rel="stylesheet" href="${base}/assets/portal.css${v}">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" data-base="${html_escape(base)}" data-title="${html_escape(title)}"></div>
|
||||
@@ -291,13 +293,18 @@ function shell(r) {
|
||||
finish();
|
||||
}
|
||||
|
||||
/** Script, styles, icon and fonts (kept outside the web root). */
|
||||
/** Script and styles (kept outside the web root); the shell's ?v= changes with every build, so they never go stale. */
|
||||
function asset(r, name) {
|
||||
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
|
||||
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
|
||||
let ext = match(name, /^[a-z0-9-]+\.(js|css|png)$/)?.[1];
|
||||
// The build keeps a gzipped copy beside each: a third of the bytes for a browser that takes it.
|
||||
let gz = ext && r.gzip ? readfile(`${ASSETS}/${name}.gz`) : null;
|
||||
let data = gz ?? (ext ? readfile(`${ASSETS}/${name}`) : null);
|
||||
if (data == null)
|
||||
not_found(r);
|
||||
headers(r, '200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
|
||||
let h = { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=31536000, immutable', 'Vary': 'Accept-Encoding' };
|
||||
if (gz != null)
|
||||
h['Content-Encoding'] = 'gzip';
|
||||
headers(r, '200 OK', h);
|
||||
r.io.write(data);
|
||||
finish();
|
||||
}
|
||||
@@ -368,7 +375,8 @@ function tz_offset() {
|
||||
function state(r) {
|
||||
let m = r.m, person = r.person;
|
||||
let usage = core.load_usage();
|
||||
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
||||
// Only their server's tunnel: one `awg` process per request, however many servers there are.
|
||||
let v = view.person_view(m, person, usage, live.dump(m, person.server ?? ''), view.states(m, usage));
|
||||
v.state = person_state(m, person, usage);
|
||||
// Day by day this month, for the page's chart (the admin's views have no use for it).
|
||||
v.month_days = view.month_days(usage.people?.[person.id]);
|
||||
@@ -384,6 +392,9 @@ function state(r) {
|
||||
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
||||
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
|
||||
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
|
||||
// The home networks a device with LAN Bypass still sends into the tunnel (home and internet access):
|
||||
// its own local network on the same addresses is out of reach (Add a device says so).
|
||||
home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [],
|
||||
},
|
||||
can_add: length(person.devices) < person.device_limit,
|
||||
locked: index(LOCKED, v.state) >= 0,
|
||||
@@ -419,7 +430,8 @@ function api_add(r) {
|
||||
if (!devices.ready())
|
||||
fail(r, '503 Service Unavailable', not_ready());
|
||||
rate_action(r);
|
||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
|
||||
// lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off.
|
||||
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true }));
|
||||
reload(r);
|
||||
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
|
||||
}
|
||||
@@ -514,6 +526,7 @@ export function handle(io) {
|
||||
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
||||
person: null,
|
||||
base: '',
|
||||
gzip: match(lc(header('accept-encoding') ?? ''), /(^|[ ,])gzip([ ;,]|$)/) != null,
|
||||
};
|
||||
let segs = filter(split(path, '/'), (s) => s != '');
|
||||
|
||||
|
||||
@@ -21,11 +21,14 @@ export function name_covers(name, host) {
|
||||
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
|
||||
};
|
||||
|
||||
// A module constant, compiled once, not for each file of the directory.
|
||||
const FULLCHAIN = /^(.+)\.fullchain\.crt$/;
|
||||
|
||||
/** ACME certificates on the router and the names each covers. */
|
||||
export function acme_certs() {
|
||||
let out = [];
|
||||
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
|
||||
let m = match(f, /^(.+)\.fullchain\.crt$/);
|
||||
let m = match(f, FULLCHAIN);
|
||||
if (!m)
|
||||
continue;
|
||||
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
|
||||
|
||||
@@ -56,7 +56,9 @@ function person_update(a) {
|
||||
let s = apply.sync();
|
||||
let m = core.load();
|
||||
let u = core.load_usage();
|
||||
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
|
||||
// One person: only their server's tunnel is read.
|
||||
let p = m.people[a.id];
|
||||
return { person: view.person_view(m, p, u, live.dump(m, p.server ?? ''), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
|
||||
}
|
||||
|
||||
function person_pause(a) {
|
||||
@@ -138,20 +140,28 @@ function person_usage(a) {
|
||||
|
||||
function device_create(a) {
|
||||
devices.need_awg();
|
||||
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
|
||||
return devices.add(a.person, a.name, a.kind, { by: 'admin', lan_bypass: a.lan_bypass === true });
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's configuration. Only `issue` (true: the admin shows its QR code,
|
||||
* downloads or copies it) counts as handing it out; a look at the device
|
||||
* marks nothing, so its "settings changed" stays until it really gets them.
|
||||
*/
|
||||
function device_config(a) {
|
||||
let m = core.load();
|
||||
let d = m.devices[a.id];
|
||||
if (!d)
|
||||
die(_('Unknown device.'));
|
||||
awg.mark_issued(m, d.id);
|
||||
if (a.issue === true)
|
||||
awg.mark_issued(m, d.id);
|
||||
return awg.client_config(m, d);
|
||||
}
|
||||
|
||||
/** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */
|
||||
function device_update(a) {
|
||||
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
|
||||
return devices.update(a.id, { name: a.name, disabled: a.disabled, mtu: a.mtu, keepalive: a.keepalive,
|
||||
lan_bypass: a.lan_bypass == null ? null : a.lan_bypass === true }, { by: 'admin' });
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
@@ -169,9 +179,10 @@ export const methods = {
|
||||
person_links: { args: { id: '' }, call: wrap(person_links) },
|
||||
person_delete: { args: { id: '' }, call: wrap(person_delete) },
|
||||
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
|
||||
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
|
||||
device_config: { args: { id: '' }, call: wrap(device_config) },
|
||||
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
|
||||
device_create: { args: { person: '', name: '', kind: '', lan_bypass: false }, call: wrap(device_create) },
|
||||
device_config: { args: { id: '', issue: false }, call: wrap(device_config) },
|
||||
device_update: { args: { id: '', name: '', disabled: false, mtu: '', keepalive: '', lan_bypass: false }, call: wrap(device_update) },
|
||||
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
|
||||
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) },
|
||||
// New keys: the device is set up again, as with the portal's Reconnect.
|
||||
device_rotate: { args: { id: '' }, call: wrap((a) => devices.reconnect(a.id, { by: 'admin' })) },
|
||||
};
|
||||
@@ -325,7 +325,8 @@ function server_create(a) {
|
||||
set('detected_wan', snap.wan);
|
||||
if (snap.lan)
|
||||
set('detected_lan', snap.lan);
|
||||
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
|
||||
// Off unless asked for: the loop through the LAN costs speed (the wizard says how much).
|
||||
set('lan_like', a.lan_like === true || a.lan_like === 1 || a.lan_like === '1' ? '1' : '0');
|
||||
set('enabled', '1');
|
||||
if (a.portal_enabled != null) {
|
||||
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
|
||||
@@ -595,6 +596,10 @@ function server_ports(a) {
|
||||
function server_obfuscation(a) {
|
||||
let preset = str(a.preset) || default_method();
|
||||
let o = awg.obf_preset(check_method(preset));
|
||||
// A cheap self-check: new values pass what a restore would be held to.
|
||||
let errs = awg.obf_errors(o);
|
||||
if (length(errs))
|
||||
die(join(' ', errs));
|
||||
let srv = store.transact((c, m) => {
|
||||
let srv = m.servers[a.id];
|
||||
if (!srv)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Dawnline rpcd methods: the live revision, the Overview status (servers,
|
||||
// people, totals, map, recent activity), the activity log and traffic history.
|
||||
// people, totals, map, recent activity), the live meter, the activity log and
|
||||
// traffic history.
|
||||
|
||||
import { readfile } from 'fs';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
@@ -13,6 +14,7 @@ import * as loop from 'dawnline.loop';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as lookup from 'dawnline.lookup';
|
||||
import * as health from 'dawnline.health';
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||
|
||||
/** The router's public IPv4 (null when none or private). */
|
||||
@@ -127,7 +129,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
|
||||
blocked: awg.blocked_text(srv),
|
||||
// Home networks (interfaces) for the per-person picker.
|
||||
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
|
||||
peers, online, obf: srv.obf,
|
||||
// The header protection key is a secret every device shares: whether there is one.
|
||||
peers, online, obf: awg.obf_public(srv.obf), hpk: !!srv.obf.header_protection_key,
|
||||
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
|
||||
rate: rates[srv.id] ?? [],
|
||||
// Daily traffic of the people on this server (its Overview chart).
|
||||
@@ -137,7 +140,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
|
||||
|
||||
/*
|
||||
* Everything the pages show at once. Readable by read-only users: no personal
|
||||
* codes or links here (person_links has them).
|
||||
* codes or links here (person_links has them), and no keys but public ones
|
||||
* (device_config has the rest).
|
||||
*/
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
@@ -282,8 +286,21 @@ function rev() {
|
||||
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
|
||||
}
|
||||
|
||||
/*
|
||||
* The live meter (Overview): each call keeps the agent's watcher writing out
|
||||
* the points it keeps for meter.WANT_FOR seconds more (a first call finds
|
||||
* none yet: the watcher writes the last two minutes within a second) and
|
||||
* returns them (dawnline.meter.read), those newer than `since` when given. Read-only users may look: server ids
|
||||
* and bytes per second only, no keys or personal codes.
|
||||
*/
|
||||
function meter_points(a) {
|
||||
meter.want();
|
||||
return meter.read(+a.since || 0);
|
||||
}
|
||||
|
||||
export const methods = {
|
||||
rev: { call: wrap(rev) },
|
||||
meter: { args: { since: 0 }, call: wrap(meter_points) },
|
||||
status: { args: { days: 30 }, call: wrap(status) },
|
||||
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
|
||||
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
|
||||
|
||||
@@ -44,11 +44,14 @@ function awg_tunnels() {
|
||||
return out;
|
||||
}
|
||||
|
||||
// A line of /etc/openwrt_release. A module constant, compiled once, not for each line.
|
||||
const RELEASE_LINE = /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/;
|
||||
|
||||
function status(a) {
|
||||
let m = core.load();
|
||||
let rel = {};
|
||||
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
|
||||
let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
|
||||
let x = match(line, RELEASE_LINE);
|
||||
if (x)
|
||||
rel[lc(x[1])] = x[2];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Dawnline updater: AmneziaWG — the builds published for this firmware by
|
||||
// each source, installing or switching a build (verified against GitHub's
|
||||
// sha256), the Russian LuCI translation, and rolling back to a kept build.
|
||||
// Every install and rollback is recorded (dawnline.awg_builds), with whether
|
||||
// the new kernel module runs or waits for the next boot.
|
||||
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
|
||||
|
||||
import { stat } from 'fs';
|
||||
@@ -89,6 +91,8 @@ export function check(ctx) {
|
||||
current = id;
|
||||
let mine = current ? sources[current] : null;
|
||||
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
|
||||
// An update that waits for a reboot: Components says so after a check.
|
||||
let pending = builds.waits_for_reboot();
|
||||
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
|
||||
ctx.log(cur == null ? _('AmneziaWG is not installed')
|
||||
: !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
|
||||
@@ -99,13 +103,19 @@ export function check(ctx) {
|
||||
update: cur == null || st == 'outdated',
|
||||
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
|
||||
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null };
|
||||
pending,
|
||||
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1))
|
||||
: pending ? _('The AmneziaWG update is installed and starts after a reboot.') : null };
|
||||
};
|
||||
|
||||
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
|
||||
function reload_module(ctx, before, after) {
|
||||
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
|
||||
return;
|
||||
/**
|
||||
* Tunnels on a new kernel module: every AmneziaWG interface is brought down,
|
||||
* the module swapped and the interfaces brought up again. False when the old
|
||||
* module stays loaded: the tunnels come back on it (the tools talk to an
|
||||
* older module at its own netlink version) and the installed one starts
|
||||
* with the next boot, which caps() and Health then wait for.
|
||||
*/
|
||||
function reload_module(ctx) {
|
||||
let ifaces = [];
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
@@ -119,33 +129,58 @@ function reload_module(ctx, before, after) {
|
||||
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
|
||||
sh(`ifdown '${i}'`);
|
||||
}
|
||||
// Both steps must really happen: the new tools against the old module (or
|
||||
// no module at all) leave every tunnel down while the job says "done".
|
||||
ctx.run('rmmod amneziawg');
|
||||
if (stat('/sys/module/amneziawg'))
|
||||
die(_('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update'));
|
||||
ctx.run('modprobe amneziawg');
|
||||
if (!stat('/sys/module/amneziawg'))
|
||||
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
|
||||
ctx.run('rmmod amneziawg');
|
||||
let swapped = !stat('/sys/module/amneziawg');
|
||||
if (swapped) {
|
||||
ctx.run('modprobe amneziawg');
|
||||
if (!stat('/sys/module/amneziawg'))
|
||||
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
|
||||
}
|
||||
for (let i in ifaces)
|
||||
sh(`ifup '${i}'`);
|
||||
return swapped;
|
||||
}
|
||||
|
||||
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
|
||||
function settle(ctx, before, after) {
|
||||
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
|
||||
/**
|
||||
* After packages changed: the module loaded, netifd knowing the protocol,
|
||||
* Dawnline set up again. was: the module loaded before (builds.module_now()).
|
||||
* Returns whether the module that runs is the installed one; false while the
|
||||
* old one stays loaded until the next boot.
|
||||
*/
|
||||
function settle(ctx, before, after, was) {
|
||||
let b = before['kmod-amneziawg'], a = after['kmod-amneziawg'];
|
||||
let fresh = true;
|
||||
// A new module package, one over a module loaded by hand, or an earlier
|
||||
// update that still waits for a boot (Reinstall tries again).
|
||||
if (a && (a != b || was.pending) && (b || was.core != null))
|
||||
fresh = reload_module(ctx);
|
||||
else if (a && !b) {
|
||||
ctx.phase(_('Loading the kernel module'));
|
||||
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
|
||||
die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
|
||||
}
|
||||
else
|
||||
reload_module(ctx, before, after);
|
||||
// netifd reads its protocol handlers when it starts.
|
||||
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
|
||||
ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
|
||||
ctx.run('/etc/init.d/network restart');
|
||||
}
|
||||
ctx.after('apply');
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
* The packages are in: settle them and record the build (source, tag) with
|
||||
* the module that ran before (was). An old module that stays loaded is no
|
||||
* failure: the job says so, and Health until the next boot.
|
||||
*/
|
||||
function finish(ctx, out, source, tag, was) {
|
||||
out.after = builds.installed();
|
||||
out.reloaded = settle(ctx, out.before, out.after, was);
|
||||
builds.record(source, tag, out.after, { prev_gen: was.gen, prev_core: was.core, reloaded: out.reloaded });
|
||||
if (!out.reloaded)
|
||||
ctx.log(_('The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot.'));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The first source that publishes every package for this firmware. */
|
||||
@@ -165,6 +200,7 @@ function pick(fw) {
|
||||
/** arg: [auto|slava|grey][:ru] | rollback */
|
||||
export function install(ctx, arg) {
|
||||
let before = builds.installed();
|
||||
let was = builds.module_now(before['kmod-amneziawg']);
|
||||
let out = { from: before['amneziawg-tools'], to: null, before };
|
||||
let fw = builds.firmware();
|
||||
if (!fw)
|
||||
@@ -182,9 +218,7 @@ export function install(ctx, arg) {
|
||||
if (!pkg.install_files(k.files, true, ctx.log))
|
||||
die(_('Package installation failed'));
|
||||
upd.forget('amneziawg');
|
||||
out.after = builds.installed();
|
||||
settle(ctx, before, out.after);
|
||||
return out;
|
||||
return finish(ctx, out, k.build, fw.tag, was);
|
||||
}
|
||||
let parts = split(arg ?? '', ':');
|
||||
let id = parts[0] || 'auto';
|
||||
@@ -236,8 +270,5 @@ export function install(ctx, arg) {
|
||||
die(_('Package installation failed'));
|
||||
if (!want_ru && pkg.version(builds.RU))
|
||||
pkg.remove([ builds.RU ], ctx.log);
|
||||
out.after = builds.installed();
|
||||
settle(ctx, before, out.after);
|
||||
builds.record(id, fw.tag, out.after);
|
||||
return out;
|
||||
return finish(ctx, out, id, fw.tag, was);
|
||||
};
|
||||
@@ -5,7 +5,7 @@
|
||||
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
|
||||
import { _ } from 'dawnline.i18n';
|
||||
|
||||
export const VERSION = '0.11.0';
|
||||
export const VERSION = '0.16.0';
|
||||
/** GitHub repository with Dawnline releases (updates and the installer). */
|
||||
export const REPO = 'tickcount/luci-app-dawnline';
|
||||
export const RUN_DIR = '/var/run/dawnline';
|
||||
@@ -365,8 +365,14 @@ export function slog_restore() {
|
||||
|
||||
/* ---------- IPv4 ---------- */
|
||||
|
||||
// Module constants, compiled once: a regex literal is compiled again each
|
||||
// time it runs (rules/backend.md), and these run for every address and every
|
||||
// network in a list (status, the portal, the agent's checks).
|
||||
const IPV4 = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/;
|
||||
const CIDR = /^([0-9.]+)(\/([0-9]+))?$/;
|
||||
|
||||
export function ip2int(ip) {
|
||||
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
|
||||
let m = match(ip, IPV4);
|
||||
if (!m)
|
||||
return null;
|
||||
let n = 0;
|
||||
@@ -389,7 +395,7 @@ export function int2ip(n) {
|
||||
* allowed networks use this; parse_cidr is the stricter one for subnets.
|
||||
*/
|
||||
export function cidr_any(s) {
|
||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
let m = match(s ?? '', CIDR);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
@@ -432,10 +438,10 @@ export function cloudflare_ip(a) {
|
||||
|
||||
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
|
||||
export function parse_cidr(cidr) {
|
||||
let m = match(cidr ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
let m = match(cidr ?? '', CIDR);
|
||||
if (!m || m[3] == null)
|
||||
return null;
|
||||
let ip = ip2int(m[1]), prefix = +m[2];
|
||||
let ip = ip2int(m[1]), prefix = +m[3];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
@@ -549,8 +555,94 @@ export function name_rule() {
|
||||
return _('Enter a name: up to 48 characters, without < > " or \\.');
|
||||
};
|
||||
|
||||
// Character sets for checks written without a regex: ucode compiles a regex
|
||||
// literal each time it runs, and musl's regcomp takes milliseconds for a
|
||||
// bounded repeat (rules/backend.md). ltrim stops at a NUL byte, so a string
|
||||
// with one fails these checks (a regex looks only up to it).
|
||||
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
const B64 = `${ASCII_ALNUM}+/`;
|
||||
|
||||
/**
|
||||
* The longest name a device takes, in characters: ordinary words fill a portal card's line about as far as its
|
||||
* status ("Return to save, Esc to cancel"), and fit the server list in the AmneziaVPN app. Names set before the rule stay as they are; it holds when a name is set.
|
||||
*/
|
||||
export const DEVICE_NAME_MAX = 20;
|
||||
// What a device's name may hold of ASCII: letters, digits, spaces and - _ . It goes into configurations, file
|
||||
// names and the AmneziaVPN key: nothing there to escape.
|
||||
const DEVICE_NAME_CHARS = `${ASCII_ALNUM} ._-`;
|
||||
// Past ASCII, letters of any language are welcome; these blocks are not: symbols, punctuation, arrows, maths,
|
||||
// emoji and invisibles (code point ranges, both ends in; web/src/shared/format.ts NAME_SYMBOLS is the same list,
|
||||
// and the page asks Unicode besides that a character is a letter or a digit).
|
||||
const NAME_SYMBOLS = [
|
||||
[ 0x80, 0xbf ], [ 0xd7, 0xd7 ], [ 0xf7, 0xf7 ], [ 0x2000, 0x2bff ], [ 0x3000, 0x303f ], [ 0xd800, 0xf8ff ],
|
||||
[ 0xfe00, 0xfe0f ], [ 0xfe30, 0xfe4f ], [ 0xfeff, 0xfeff ], [ 0xfff0, 0xffff ], [ 0x1f000, 0x1fbff ],
|
||||
[ 0xe0000, 0xe007f ]
|
||||
];
|
||||
|
||||
function name_symbol(cp) {
|
||||
for (let r in NAME_SYMBOLS)
|
||||
if (cp >= r[0] && cp <= r[1])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A device's name (trimmed by the caller): 1-DEVICE_NAME_MAX characters, not blank, each one of
|
||||
* DEVICE_NAME_CHARS or past ASCII outside NAME_SYMBOLS. Read by code points: broken UTF-8, and an
|
||||
* ASCII character spelled long (0xC0 0xAF for "/"), are refused.
|
||||
*/
|
||||
export function valid_device_name(s) {
|
||||
if (type(s) != 'string' || length(trim(s)) == 0 || ulength(s) > DEVICE_NAME_MAX)
|
||||
return false;
|
||||
let i = 0, n = length(s);
|
||||
while (i < n) {
|
||||
let b = ord(s, i), cp, len;
|
||||
if (b < 0x80) {
|
||||
if (index(DEVICE_NAME_CHARS, substr(s, i, 1)) < 0)
|
||||
return false;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if ((b & 0xe0) == 0xc0) {
|
||||
len = 2;
|
||||
cp = b & 0x1f;
|
||||
}
|
||||
else if ((b & 0xf0) == 0xe0) {
|
||||
len = 3;
|
||||
cp = b & 0x0f;
|
||||
}
|
||||
else if ((b & 0xf8) == 0xf0) {
|
||||
len = 4;
|
||||
cp = b & 0x07;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
if (i + len > n)
|
||||
return false;
|
||||
for (let k = 1; k < len; k++) {
|
||||
let c = ord(s, i + k);
|
||||
if ((c & 0xc0) != 0x80)
|
||||
return false;
|
||||
cp = (cp << 6) | (c & 0x3f);
|
||||
}
|
||||
if (cp < 0xc0 || cp > 0x10ffff || name_symbol(cp))
|
||||
return false;
|
||||
i += len;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
|
||||
const KEY_LAST = 'AEIMQUYcgkosw048';
|
||||
|
||||
/**
|
||||
* A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the
|
||||
* same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms
|
||||
* compile on the WR3000P: the agent's watcher checks two keys per line of
|
||||
* `awg show <ifname> dump` every second. This takes about 0.03 ms.
|
||||
*/
|
||||
export function valid_key(s) {
|
||||
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
|
||||
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
|
||||
index(KEY_LAST, substr(s, 42, 1)) >= 0 && ltrim(substr(s, 0, 42), B64) == '';
|
||||
};
|
||||
|
||||
/** An IPv6 address in its usual spelling (no zone, no brackets). */
|
||||
@@ -558,10 +650,25 @@ export function is_ip6(s) {
|
||||
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
|
||||
};
|
||||
|
||||
const LABEL = `${ASCII_ALNUM}-`;
|
||||
|
||||
/**
|
||||
* Dot-separated labels of 1-63 letters, digits and dashes, none starting or
|
||||
* ending with a dash: the same as
|
||||
* /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
|
||||
* without its 10 ms compile on the WR3000P.
|
||||
*/
|
||||
function host_name(s) {
|
||||
for (let l in split(s, '.'))
|
||||
if (length(l) < 1 || length(l) > 63 || ltrim(l, LABEL) != '' ||
|
||||
index(ASCII_ALNUM, substr(l, 0, 1)) < 0 || index(ASCII_ALNUM, substr(l, -1)) < 0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A host name or an IP address, as a public address or the portal's name may be given. */
|
||||
export function valid_host(s) {
|
||||
return type(s) == 'string' && length(s) <= 253 &&
|
||||
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
|
||||
ip2int(s) != null || is_ip6(s));
|
||||
return type(s) == 'string' && length(s) <= 253 && (host_name(s) || ip2int(s) != null || is_ip6(s));
|
||||
};
|
||||
|
||||
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
|
||||
@@ -573,11 +680,18 @@ export function valid_date(s) {
|
||||
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
|
||||
};
|
||||
|
||||
// Runs of other characters become one dash. Module constants: host_label and
|
||||
// tunnel_name run for every device of a status or a portal answer.
|
||||
const NOT_LC_ALNUM = /[^a-z0-9]+/g, NOT_ALNUM = /[^A-Za-z0-9]+/g;
|
||||
// Names Windows keeps for devices: no file may be called that, whatever the case.
|
||||
const WIN_DEVICES = [ 'con', 'prn', 'aux', 'nul', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
|
||||
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9' ];
|
||||
|
||||
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
|
||||
export function slugify(s) {
|
||||
let out = lc(translit(trim(`${s ?? ''}`)));
|
||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||
out = replace(out, /^-+|-+$/g, '');
|
||||
out = replace(out, NOT_LC_ALNUM, '-');
|
||||
out = trim(out, '-');
|
||||
return substr(out, 0, 32) || 'user';
|
||||
};
|
||||
|
||||
@@ -586,8 +700,8 @@ export function slugify(s) {
|
||||
* "telefon"): at most 40 characters, "device" when nothing is left.
|
||||
*/
|
||||
export function host_label(s) {
|
||||
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
|
||||
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
|
||||
let l = replace(lc(translit(`${s ?? ''}`)), NOT_LC_ALNUM, '-');
|
||||
l = rtrim(substr(trim(l, '-'), 0, 40), '-');
|
||||
return l || 'device';
|
||||
};
|
||||
|
||||
@@ -598,9 +712,9 @@ export function host_label(s) {
|
||||
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
|
||||
*/
|
||||
export function tunnel_name(s) {
|
||||
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
|
||||
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
|
||||
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
|
||||
let l = replace(translit(`${s ?? ''}`), NOT_ALNUM, '-');
|
||||
l = rtrim(substr(trim(l, '-'), 0, 15), '-');
|
||||
return l && index(WIN_DEVICES, lc(l)) < 0 ? l : 'dawnline';
|
||||
};
|
||||
|
||||
/* ---------- time ---------- */
|
||||
@@ -660,9 +774,21 @@ export function now() {
|
||||
return time();
|
||||
};
|
||||
|
||||
const IFACE = `${ASCII_ALNUM}_.@-`;
|
||||
|
||||
/**
|
||||
* A netifd interface name (network.interface.<name>, a person's home network):
|
||||
* 1-32 letters, digits and _ . @ -, the same as /^[A-Za-z0-9_.@-]{1,32}$/
|
||||
* without its 3 ms compile on the WR3000P (iface_status runs several times for
|
||||
* the Overview's status, and in the agent's minute checks).
|
||||
*/
|
||||
export function valid_iface(s) {
|
||||
return type(s) == 'string' && length(s) >= 1 && length(s) <= 32 && ltrim(s, IFACE) == '';
|
||||
};
|
||||
|
||||
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
|
||||
export function iface_status(ifname) {
|
||||
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
|
||||
if (!valid_iface(ifname))
|
||||
return null;
|
||||
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
|
||||
if (!s)
|
||||
|
||||
@@ -6,17 +6,17 @@ import * as live from 'dawnline.live';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import { day_key_ago, month_key } from 'dawnline.util';
|
||||
|
||||
/** Daily totals (rx+tx) for the last `n` days, oldest first. */
|
||||
/** Each day's [rx, tx] for the last `n` days, oldest first: the charts draw what came and what went apart. */
|
||||
export function spark(rec, n) {
|
||||
let out = [];
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
let v = rec?.days?.[day_key_ago(i)];
|
||||
push(out, v ? v[0] + v[1] : 0);
|
||||
push(out, v ? [ v[0], v[1] ] : [ 0, 0 ]);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/** Daily totals (rx+tx) from the 1st of this month to today, oldest first (the portal's month chart). */
|
||||
/** Each day's [rx, tx] from the 1st of this month to today, oldest first (the portal's month chart). */
|
||||
export function month_days(rec) {
|
||||
return spark(rec, +substr(day_key_ago(0), 8, 2));
|
||||
};
|
||||
@@ -58,6 +58,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
m._reconnect ??= awg.reconnects();
|
||||
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
|
||||
let p = m.people[d.person];
|
||||
let srv = m.servers[p?.server];
|
||||
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
|
||||
let label = '';
|
||||
if (m.settings.hostnames && p) {
|
||||
@@ -65,6 +66,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
m._labels[p.id] ??= core.device_labels(m, p);
|
||||
label = m._labels[p.id][d.id] ?? 'device';
|
||||
}
|
||||
let online = hs > 0 && live.online(dmp, d.id, peer);
|
||||
let v = {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
@@ -73,7 +75,7 @@ export function device_view(m, d, usage, dmp) {
|
||||
disabled: d.disabled,
|
||||
created: d.created,
|
||||
created_by: d.created_by,
|
||||
online: hs > 0 && live.online(dmp, d.id, peer),
|
||||
online,
|
||||
handshake: hs,
|
||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||
active: !!peer,
|
||||
@@ -84,6 +86,21 @@ export function device_view(m, d, usage, dmp) {
|
||||
browser_key: d.private_key == '',
|
||||
// Its configuration changed since it was last shown or downloaded.
|
||||
config_stale: config_stale(m, d),
|
||||
// How it connects: its own local network outside the tunnel, its own MTU
|
||||
// and keep-alive (0 / null: the server's) and what its configuration carries.
|
||||
lan_bypass: d.lan_bypass,
|
||||
mtu: d.mtu,
|
||||
keepalive: d.keepalive,
|
||||
mtu_used: srv ? core.device_mtu(srv, d) : null,
|
||||
keepalive_used: srv ? core.device_keepalive(srv, d) : null,
|
||||
// Its link failing in a named way, as the agent's watcher shows it
|
||||
// (dawnline.link): { state, since }, or null.
|
||||
link: dmp.link?.[d.id] ?? null,
|
||||
// What its link does right now, for the set-up sheet (dawnline.link
|
||||
// setup_state): { state: 'trying' | 'flowing' | 'nodata', since }, or null.
|
||||
// Without the agent nobody tells data from a bare handshake: a session
|
||||
// that lives counts as data flowing, so the sheet still sees it arrive.
|
||||
setup: dmp.setup != null ? (dmp.setup[d.id] ?? null) : online ? { state: 'flowing', since: hs } : null,
|
||||
};
|
||||
return v;
|
||||
};
|
||||
|
||||
@@ -44,7 +44,23 @@ function restart_services() {
|
||||
function probes(m) {
|
||||
let out = [];
|
||||
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
|
||||
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
|
||||
let tunnels = awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) });
|
||||
push(out, ...tunnels);
|
||||
// A tunnel's interface edited outside Dawnline (LuCI, uci) keeps that until
|
||||
// the next apply: set up again with Dawnline's settings. Only while
|
||||
// AmneziaWG itself works (its target comes first, and is fixed first).
|
||||
if (filter(tunnels, (p) => p.id == 'awg')[0]?.ok)
|
||||
for (let id, diff in netifd.drift(m)) {
|
||||
let srv = m.servers[id];
|
||||
push(out, {
|
||||
id: `cfg_${id}`, src: 'awg', name: `${srv.name} · interface settings`, who: srv.name, ok: !length(diff),
|
||||
problem: sprintf(L_('interface %s was changed outside Dawnline'), srv.ifname),
|
||||
back: sprintf(L_("interface %s has Dawnline's settings again"), srv.ifname),
|
||||
// Option names only: their values hold the server's private key.
|
||||
detail: () => sprintf(L_('Changed: %s.'), join(', ', diff)),
|
||||
repair: { what: L_('setting it up again'), run: () => apply.apply() },
|
||||
});
|
||||
}
|
||||
if (length(m.servers))
|
||||
push(out, {
|
||||
id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
|
||||
@@ -184,6 +200,14 @@ function names() {
|
||||
};
|
||||
}
|
||||
|
||||
/** A target's chip name in the language of the call: names(), a server's interface settings, else as stored. */
|
||||
function chip_name(m, n, id, stored) {
|
||||
if (n[id])
|
||||
return n[id];
|
||||
let srv = substr(id, 0, 4) == 'cfg_' ? m.servers[substr(id, 4)] : null;
|
||||
return srv ? sprintf(_('%s · interface settings'), srv.name) : stored;
|
||||
}
|
||||
|
||||
/**
|
||||
* For the Health page: the watchdog's state and the newest log entries. Target
|
||||
* and repair names in the language of the call; the log as it was written.
|
||||
@@ -195,11 +219,11 @@ export function view(m) {
|
||||
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
|
||||
let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ];
|
||||
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
|
||||
push(targets, { id, name: n[id] ?? x.name, ok: !!x.ok, tries: x.tries ?? 0 });
|
||||
push(targets, { id, name: chip_name(m, n, id, x.name), ok: !!x.ok, tries: x.tries ?? 0 });
|
||||
return {
|
||||
watchdog: {
|
||||
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
|
||||
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })),
|
||||
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })),
|
||||
},
|
||||
log: slog_read(200),
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
|
||||
- `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater).
|
||||
- Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic.
|
||||
- The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`.
|
||||
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.ONLINE_WINDOW`): traffic silence is no signal, a phone asleep is silent too.
|
||||
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.online_window()`: 190 s, longer for a device with a long keep-alive): traffic silence is no signal, a phone asleep is silent too. A device's link trouble (trying, shared, dropped, unstable) is the watcher's too (`dawnline.link`, `live.LINK`).
|
||||
|
||||
## ucode
|
||||
|
||||
@@ -21,9 +21,10 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
|
||||
|
||||
## Cost on the router
|
||||
|
||||
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action.
|
||||
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action. A person's answers read only their server's tunnel (`live.dump(m, sid)`: one `awg` process, however many servers).
|
||||
- **rpcd keeps the admin backend loaded:** LuCI RPC calls are cheap, so the admin UI may poll small methods often (`rev`), and the heavy ones (`status`) only on change or rarely.
|
||||
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show all dump` (about 4 ms with process start), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
|
||||
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show <ifname> dump` per Dawnline tunnel, never `all` (another AmneziaWG interface's peers are not Dawnline's; about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
|
||||
- **A regex literal is compiled every time it runs:** ucode calls regcomp for `/…/` each time the expression is evaluated, and musl's regcomp grows with the pattern. Bounded repeats are copied out (`{42}` about 1.7 ms on the WR3000P, `[A-Za-z0-9_.@-]{1,32}` 3 ms, two `{0,61}` 10 ms), alternations and classes add up (`/^(PrivateKey|Jc|Jmin|Jmax) /` 0.11 ms, `/^[0-9]+$/` 0.02 ms); matching a compiled regex takes 0.01–0.1 ms. In a loop or on a hot path, hoist the regex into a module `const` (compiled once, when the module loads — every portal request pays that too) or check with `length`/`substr`/`ltrim` (`util.valid_key`, `valid_host`, `valid_iface`).
|
||||
- Measure before and after on the router (a loop of 20–200 calls, `/proc/self/stat` CPU ticks, system busy from `/proc/stat`) when adding anything periodic.
|
||||
|
||||
## Checks
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Frontend (TypeScript: admin UI and portal)
|
||||
|
||||
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`).
|
||||
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`). Portal work starts with `DESIGN.md` (its tokens, components and motion).
|
||||
|
||||
## Code
|
||||
|
||||
@@ -16,4 +16,4 @@ Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18
|
||||
|
||||
## Checks
|
||||
|
||||
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm run i18n:check`, `npm test`, `npm run build`; the rebuilt bundles under `package/` and the catalogs are committed (CI fails otherwise).
|
||||
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm run lint`, `npm run knip`, `npm run i18n:check`, `npm test`, `npm run build`; the catalogs are committed, the bundles under `package/` are git-ignored (CI builds them before packaging).
|
||||
@@ -63,6 +63,7 @@ Write like a careful Russian product (Telegram, Яндекс), not a word-for-wo
|
||||
| home network | домашняя сеть |
|
||||
| internet | интернет |
|
||||
| home network + internet | домашняя сеть и интернет |
|
||||
| LAN Bypass (a device's option) | обход локальной сети («Обход локальной сети») |
|
||||
| portal, personal link, personal page | портал, личная ссылка, личная страница |
|
||||
| invite (card) | приглашение (карточка приглашения) |
|
||||
| disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная |
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
The bar is a modern product UI (Linear / Vercel / Raycast level), not a "native" LuCI form. A plain label + input row, a bare radio list, three columns of check marks or a text dump is a first draft, never the result.
|
||||
|
||||
**The portal has its own design system, `DESIGN.md`** (repo root): read it before any portal work, mocks included. Build from its tokens, components and spring tokens, follow its Do's and Don'ts, and update it in the same change when the portal's look or motion changes. The admin follows this file and the LuCI theme.
|
||||
|
||||
## Approach
|
||||
|
||||
- **Mock first.** Any visible change beyond a one-line fix: show a mockup (2–4 genuinely different options when the direction is open) with a recommendation, then build the chosen one. Do not start coding a layout the user has not seen.
|
||||
|
||||
@@ -17,6 +17,11 @@ APK_SDK="${APK_SDK:-itdoginfo/openwrt-sdk-apk:25.12.3}"
|
||||
grep -q "^export const VERSION = '$VERSION';" "$APP/root/usr/share/ucode/dawnline/util.uc" || { echo "util.uc VERSION != $VERSION" >&2; exit 1; }
|
||||
grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; }
|
||||
|
||||
# The web bundles are not committed: web/ builds them (npm run build).
|
||||
for f in htdocs/luci-static/resources/dawnline/app.js root/usr/share/dawnline/portal/assets/portal.js root/usr/share/dawnline/portal/assets/portal.css; do
|
||||
[ -f "$APP/$f" ] || { echo "$APP/$f is missing: run 'npm run build' in web/" >&2; exit 1; }
|
||||
done
|
||||
|
||||
mkdir -p "$OUT"
|
||||
build() {
|
||||
local type="$1" sdk="$2" tag="dawnline-build:$1"
|
||||
|
||||
@@ -18,6 +18,10 @@ grep -q "PKG_VERSION:=$VERSION\$" "$APP/Makefile" || { echo "Makefile PKG_VERSIO
|
||||
grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; }
|
||||
|
||||
[ "${SKIP_WEB:-0}" = 1 ] || (cd "$ROOT/web" && npm run --silent ci)
|
||||
# With SKIP_WEB=1 the bundles come from an earlier build (they are not committed).
|
||||
for f in htdocs/luci-static/resources/dawnline/app.js root/usr/share/dawnline/portal/assets/portal.js root/usr/share/dawnline/portal/assets/portal.css; do
|
||||
[ -f "$APP/$f" ] || { echo "$APP/$f is missing: run 'npm run build' in web/" >&2; exit 1; }
|
||||
done
|
||||
|
||||
mkdir -p "$STAGE/www" "$OUT"
|
||||
cp -R "$APP/root/." "$STAGE/"
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env node
|
||||
// Capture the raw README screenshots of the personal portal into
|
||||
// docs/screenshots/raw/ (2x PNG): the page (portal.png) and the three steps of
|
||||
// adding a phone in front of it (portal-add-1..3.png: Add a device, the set-up
|
||||
// sheet waiting, the phone connected), each sheet alone on a transparent page.
|
||||
// The Russian ones take a -ru suffix. scripts/frame-screenshots.py then frames
|
||||
// them for the README.
|
||||
//
|
||||
// The portal is its demo build (web/dist/demo, `npm run build:demo`, built
|
||||
// first unless --no-build): the real portal over a router that lives in the
|
||||
// page, so no one's real page is shown and adding a device adds none. It is
|
||||
// opened as https://vpn.example.com/<code> and every file is answered from the
|
||||
// build over the DevTools protocol (scripts/cdp.mjs), so its personal link
|
||||
// reads like one. The cast is made up here: the demo's own three devices (the
|
||||
// ones its router keeps, so adding one works) under other names, three more
|
||||
// shown beside them, and the person's and the server's names.
|
||||
//
|
||||
// scripts/capture-portal.mjs [--lang en,ru] [--no-build]
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { die, launch, sleep } from './cdp.mjs';
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const WEB = join(ROOT, 'web');
|
||||
const DEMO = join(WEB, 'dist', 'demo');
|
||||
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
|
||||
const SCALE = 2;
|
||||
/** The page's width, as the README shot always had it. */
|
||||
const WIDTH = 1320;
|
||||
/** Around a sheet in its capture: left, top, right, bottom (frame-screenshots.py FLOW_MARGIN). */
|
||||
const MARGIN = [56, 40, 56, 72];
|
||||
const ORIGIN = 'https://vpn.example.com';
|
||||
/** The demo's personal link (web/src/portal/demo/index.html, data-base). */
|
||||
const CODE = 'kelino-sarupa-motive';
|
||||
const NAMES = { person: 'Aemeath', server: 'Ames Gateway' };
|
||||
/** The device this page is open on (its card says "This device"). */
|
||||
const HERE = 'MacBook Air';
|
||||
/** The phone added in the steps. */
|
||||
const NEW = 'Pixel 9';
|
||||
const SLOTS = 8;
|
||||
|
||||
const args = { langs: ['en', 'ru'], build: true };
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a === '--lang') args.langs = (process.argv[++i] ?? die('--lang needs a value')).split(',');
|
||||
else if (a === '--no-build') args.build = false;
|
||||
else die(`unknown argument ${a}`);
|
||||
}
|
||||
|
||||
const DAY = 86400;
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
/**
|
||||
* What the demo's router keeps (its DemoDb, in localStorage before the page loads): three devices, so one more
|
||||
* fits its limit of four and the steps add it for real.
|
||||
*/
|
||||
function demoDb(t) {
|
||||
const dev = (id, name, kind, n, gb, hs, days) => ({
|
||||
id,
|
||||
name,
|
||||
kind,
|
||||
n,
|
||||
gb,
|
||||
hs,
|
||||
connectAt: 0,
|
||||
created: t - days * DAY,
|
||||
by: 'admin',
|
||||
stale: false,
|
||||
});
|
||||
return {
|
||||
scenario: 'normal',
|
||||
devs: [
|
||||
dev('d_mac', HERE, 'computer', 2, 5.4, t - 20, 60),
|
||||
dev('d_iph', 'iPhone 16', 'phone', 3, 2.3, t - 40, 58),
|
||||
dev('d_gal', 'Galaxy S24', 'phone', 4, 0.66, t - 26 * 3600, 30),
|
||||
],
|
||||
next: 5,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's side, before it loads: the language, the router's devices, the demo's own chrome hidden, and every
|
||||
* answer of its router touched on the way to the page (the names, this device, the slots, the devices shown
|
||||
* beside the ones it keeps).
|
||||
*/
|
||||
const prelude = (lang, db) => `(() => {
|
||||
try {
|
||||
localStorage.setItem('dl.lang', ${JSON.stringify(lang)});
|
||||
localStorage.setItem('dawnline-demo', ${JSON.stringify(JSON.stringify(db))});
|
||||
} catch {}
|
||||
const NAMES = ${JSON.stringify(NAMES)}, HERE = ${JSON.stringify(HERE)}, SLOTS = ${SLOTS};
|
||||
const extra = (devs, t) => {
|
||||
const like = (d, o) => ({ ...d, link: null, setup: null, online: false, config_stale: false, created_by: 'admin', ...o });
|
||||
const mac = devs.find((d) => d.name === HERE) ?? devs[0];
|
||||
const none = { handshake: 0, endpoint: '', month: [0, 0], total: [0, 0], spark: mac.spark.map(() => [0, 0]) };
|
||||
const scale = (p, f) => p.map((v) => Math.round(v * f));
|
||||
return [
|
||||
like(mac, { id: 'x_tv', name: 'Living room TV', kind: 'other', address: '10.8.0.6', handshake: t - 3 * 3600,
|
||||
config_stale: true, month: scale(mac.month, 1.13), total: scale(mac.total, 1.4),
|
||||
spark: mac.spark.map((p) => scale(p, 1.1)), created: t - 45 * 86400 }),
|
||||
like(mac, { id: 'x_ipad', name: 'iPad', kind: 'tablet', address: '10.8.0.7', created: t - 2 * 86400, ...none }),
|
||||
like(mac, { id: 'x_rtr', name: 'Cottage router', kind: 'router', address: '10.8.0.8', created: t - 86400, ...none }),
|
||||
];
|
||||
};
|
||||
const touch = (st) => {
|
||||
if (!st?.person) return;
|
||||
const own = st.person.devices;
|
||||
st.person.name = NAMES.person;
|
||||
if (st.server) st.server.name = NAMES.server;
|
||||
st.person.devices = [...own, ...extra(own, st.now)];
|
||||
st.person.device_limit = SLOTS;
|
||||
st.can_add = st.person.devices.length < SLOTS;
|
||||
st.here = own.find((d) => d.name === HERE)?.id ?? null;
|
||||
};
|
||||
let inner = window.fetch;
|
||||
Object.defineProperty(window, 'fetch', {
|
||||
configurable: true,
|
||||
get: () => inner,
|
||||
// The demo's router takes fetch over (demo/serve.ts): its answers pass through here.
|
||||
set: (f) => {
|
||||
inner = async (...a) => {
|
||||
const r = await f(...a);
|
||||
if (!String(a[0] instanceof Request ? a[0].url : a[0]).includes('/api/')) return r;
|
||||
let j;
|
||||
try { j = await r.clone().json(); } catch { return r; }
|
||||
touch(j?.person ? j : j?.state);
|
||||
return new Response(JSON.stringify(j), { status: r.status, headers: { 'content-type': 'application/json' } });
|
||||
};
|
||||
},
|
||||
});
|
||||
addEventListener('DOMContentLoaded', () => {
|
||||
const s = document.createElement('style');
|
||||
// The demo's chip, GitHub knob and set-up state switch go, and the path takes the row again, as on a router's
|
||||
// page.
|
||||
s.textContent = '.dm-chip, .dm-gh, .dm-way { display: none !important; } .cr-path { flex: 1 !important; }';
|
||||
document.head.append(s);
|
||||
});
|
||||
})()`;
|
||||
|
||||
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' };
|
||||
|
||||
/** Answer the page's requests from the demo build: its page for the personal link, its files by name. */
|
||||
async function serve(page) {
|
||||
page.on('Fetch.requestPaused', async (e) => {
|
||||
const path = new URL(e.request.url).pathname;
|
||||
const file = path === `/${CODE}` || path === '/' ? 'index.html' : path.slice(1);
|
||||
let body;
|
||||
try {
|
||||
body = readFileSync(join(DEMO, file));
|
||||
} catch {
|
||||
await page.send('Fetch.fulfillRequest', { requestId: e.requestId, responseCode: 404, body: '' }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
await page.send('Fetch.fulfillRequest', {
|
||||
requestId: e.requestId,
|
||||
responseCode: 200,
|
||||
responseHeaders: [{ name: 'Content-Type', value: TYPES[extname(file)] ?? 'application/octet-stream' }],
|
||||
body: body.toString('base64'),
|
||||
});
|
||||
});
|
||||
await page.send('Fetch.enable', { patterns: [{ urlPattern: `${ORIGIN}/*`, requestStage: 'Request' }] });
|
||||
}
|
||||
|
||||
async function shoot(page, file, clip) {
|
||||
const { data } = await page.send('Page.captureScreenshot', {
|
||||
format: 'png',
|
||||
clip: { ...clip, scale: 1 },
|
||||
captureBeyondViewport: true,
|
||||
});
|
||||
writeFileSync(join(RAW, file), Buffer.from(data, 'base64'));
|
||||
console.log(`${file}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||
}
|
||||
|
||||
// The page's content: everything on screen but full-width or full-height wrappers, 36px around it (as the
|
||||
// README shot always was; what waits off screen, as a field's measuring copy does, is no content).
|
||||
const PAGE_CLIP = `(() => {
|
||||
let l = innerWidth, r = 0, b = 0;
|
||||
for (const e of document.querySelectorAll('#app *')) {
|
||||
const x = e.getBoundingClientRect();
|
||||
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
|
||||
if (x.left < 0 || x.right > innerWidth) continue;
|
||||
l = Math.min(l, x.left);
|
||||
r = Math.max(r, x.right);
|
||||
b = Math.max(b, x.bottom);
|
||||
}
|
||||
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
|
||||
})()`;
|
||||
|
||||
// The open sheet alone: the page and the scrim out of sight on a transparent page, MARGIN around the sheet.
|
||||
const SHEET_CLIP = `(() => {
|
||||
const r = document.querySelector('.sheet-root.open .sheet').getBoundingClientRect();
|
||||
const [l, t, rr, b] = ${JSON.stringify(MARGIN)};
|
||||
return { x: r.left - l, y: r.top - t, width: r.width + l + rr, height: r.height + t + b };
|
||||
})()`;
|
||||
const ALONE = `(() => {
|
||||
const s = document.createElement('style');
|
||||
s.id = 'alone';
|
||||
s.textContent = 'html, body { background: transparent !important; } #app { visibility: hidden !important; } .scrim { display: none !important; }';
|
||||
document.head.append(s);
|
||||
})()`;
|
||||
|
||||
async function capture(lang) {
|
||||
const suffix = lang === 'en' ? '' : `-${lang}`;
|
||||
const b = await launch([`--lang=${lang}`]);
|
||||
const { page, evaluate, go, waitSel } = b;
|
||||
try {
|
||||
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
|
||||
await page.send('Emulation.setDeviceMetricsOverride', { width: WIDTH, height: 1400, deviceScaleFactor: SCALE, mobile: false });
|
||||
// Where the page paints nothing (a sheet alone), the capture is transparent.
|
||||
await page.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
|
||||
await serve(page);
|
||||
await page.send('Page.addScriptToEvaluateOnNewDocument', { source: prelude(lang, demoDb(now())) });
|
||||
await go(`${ORIGIN}/${CODE}`);
|
||||
await waitSel('.dev[data-id]');
|
||||
await sleep(2500);
|
||||
await shoot(page, `portal${suffix}.png`, await evaluate(PAGE_CLIP));
|
||||
|
||||
// 1: Add a device, a phone, its name typed in.
|
||||
await evaluate(`document.querySelector('.dev.add').click()`);
|
||||
await waitSel('.sheet-root.open .kinds');
|
||||
await sleep(900);
|
||||
await evaluate(`document.querySelectorAll('.sheet-root.open .kind')[1].click()`);
|
||||
await sleep(500);
|
||||
await evaluate(`(() => { const i = document.querySelector('.sheet-root.open .field input'); i.focus(); i.select(); })()`);
|
||||
await page.send('Input.insertText', { text: NEW });
|
||||
await evaluate(`document.activeElement.blur()`);
|
||||
await sleep(900);
|
||||
await evaluate(ALONE);
|
||||
await shoot(page, `portal-add-1${suffix}.png`, await evaluate(SHEET_CLIP));
|
||||
await evaluate(`document.getElementById('alone').remove()`);
|
||||
|
||||
// 2: the set-up sheet, waiting for the phone, its link open as a code for the phone's camera (the page
|
||||
// opens on the app's row, whose code a key makes too dense to read at this size).
|
||||
await evaluate(`document.querySelector('.sheet-root.open .field .go').click()`);
|
||||
await waitSel('.sheet-root.open .way');
|
||||
await sleep(1200);
|
||||
await evaluate(`document.querySelector('.sheet-root.open .acc-row:not(.open) .acc-head').click()`);
|
||||
await sleep(1500);
|
||||
await evaluate(ALONE);
|
||||
await shoot(page, `portal-add-2${suffix}.png`, await evaluate(SHEET_CLIP));
|
||||
await evaluate(`document.getElementById('alone').remove()`);
|
||||
|
||||
// 3: connected (the demo's phone does within 6-9 s), what was under the way folded away.
|
||||
await waitSel('.sheet-root.open .way.done', 15000);
|
||||
await sleep(1150);
|
||||
await evaluate(ALONE);
|
||||
await shoot(page, `portal-add-3${suffix}.png`, await evaluate(SHEET_CLIP));
|
||||
page.close();
|
||||
} finally {
|
||||
await b.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (args.build) execFileSync('npm', ['run', '--silent', 'build:demo'], { cwd: WEB, stdio: 'inherit' });
|
||||
for (const lang of args.langs) await capture(lang);
|
||||
}
|
||||
|
||||
main().catch((e) => die(e.message));
|
||||
@@ -1,29 +1,33 @@
|
||||
#!/usr/bin/env node
|
||||
// Capture the raw README screenshots from a live router into
|
||||
// Capture the raw README screenshots of the admin pages from a live router into
|
||||
// docs/screenshots/raw/<name>.png (2x PNG); scripts/frame-screenshots.py then
|
||||
// puts them into a browser window for the README.
|
||||
// frames them for the README. The portal's come from its demo instead
|
||||
// (scripts/capture-portal.mjs): no one's real page, and adding a device there adds none.
|
||||
//
|
||||
// Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome
|
||||
// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with
|
||||
// on macOS) over the DevTools protocol (scripts/cdp.mjs). Signs in to LuCI with
|
||||
// the password from LUCI_PASSWORD or asked on the terminal; the session lives
|
||||
// only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed.
|
||||
//
|
||||
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
|
||||
// [--mask real=shown ...] [--name real=shown ...]
|
||||
// [--only overview,people] [--demo]
|
||||
// [--only overview,people] [--demo] [--lang ru]
|
||||
//
|
||||
// --lang asks LuCI for the pages in that language (its catalog, po/<lang>/dawnline.po;
|
||||
// the router's LuCI language left on auto) and names the captures <name>-<lang>.png
|
||||
// for that README (README_ru.md); English (the default) keeps <name>.png.
|
||||
// --mask replaces text on every page before the capture (a domain, a name);
|
||||
// --name does the same for a person's name in any case, and for their initials.
|
||||
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
|
||||
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
|
||||
// the router's answers are rewritten in the headless browser on their way to the page.
|
||||
|
||||
import { execFileSync, spawn } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { die, launch, sleep } from './cdp.mjs';
|
||||
import { demoRpc } from './screenshot-demo.mjs';
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
@@ -37,6 +41,7 @@ const args = {
|
||||
names: [],
|
||||
only: [],
|
||||
demo: false,
|
||||
lang: 'en',
|
||||
};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
@@ -47,8 +52,26 @@ for (let i = 2; i < process.argv.length; i++) {
|
||||
else if (a === '--name') args.names.push(v().split('=', 2));
|
||||
else if (a === '--only') args.only = v().split(',');
|
||||
else if (a === '--demo') args.demo = true;
|
||||
else if (a === '--lang') args.lang = v();
|
||||
else die(`unknown argument ${a}`);
|
||||
}
|
||||
const SUFFIX = args.lang === 'en' ? '' : `-${args.lang}`;
|
||||
|
||||
/** The admin's catalog for --lang: msgid -> msgstr, the entries without a context (English: none). */
|
||||
const CATALOG = (() => {
|
||||
const out = new Map();
|
||||
if (args.lang === 'en') return out;
|
||||
let po;
|
||||
try {
|
||||
po = readFileSync(join(ROOT, 'package', 'luci-app-dawnline', 'po', args.lang, 'dawnline.po'), 'utf8');
|
||||
} catch {
|
||||
die(`no admin catalog for --lang ${args.lang}`);
|
||||
}
|
||||
for (const m of po.matchAll(/^(msgctxt .*\n)?msgid "(.*)"\nmsgstr "(.*)"$/gm)) if (!m[1] && m[3]) out.set(m[2], m[3]);
|
||||
return out;
|
||||
})();
|
||||
/** A button's words as the page shows them in --lang (the pages are clicked by what they say). */
|
||||
const tr = (id) => CATALOG.get(id) ?? id;
|
||||
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
|
||||
|
||||
/** As shared/format initials(): first letters of the first and last word, or the first two of one word. */
|
||||
@@ -60,11 +83,6 @@ for (const [real, shown] of args.names)
|
||||
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
|
||||
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
|
||||
|
||||
function die(msg) {
|
||||
console.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
|
||||
const USER = process.env.LUCI_USER || 'root';
|
||||
|
||||
@@ -93,7 +111,7 @@ const SHOTS = [
|
||||
ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas',
|
||||
// The map shows the last 30 days, not only who is online now.
|
||||
prep: `(() => {
|
||||
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days');
|
||||
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('30 days'))});
|
||||
b?.click();
|
||||
})()`,
|
||||
settle: 6000,
|
||||
@@ -113,7 +131,7 @@ const SHOTS = [
|
||||
ready: '.dl-grid-person .dl-row',
|
||||
// Where they connected from, on the map.
|
||||
prep: `(() => {
|
||||
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
|
||||
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('Show map'))});
|
||||
b?.click();
|
||||
})()`,
|
||||
settle: 6000,
|
||||
@@ -131,25 +149,6 @@ const SHOTS = [
|
||||
return { x: c.x, y: 0, width: c.w, height: cut };
|
||||
})()`,
|
||||
},
|
||||
{
|
||||
name: 'portal',
|
||||
url: (s) => s.portal,
|
||||
width: 1320,
|
||||
ready: 'body',
|
||||
settle: 3000,
|
||||
// The content: everything but full-width or full-height wrappers, 36px around it.
|
||||
clip: `(() => {
|
||||
let l = innerWidth, r = 0, b = 0;
|
||||
for (const e of document.body.querySelectorAll('*')) {
|
||||
const x = e.getBoundingClientRect();
|
||||
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
|
||||
l = Math.min(l, x.left);
|
||||
r = Math.max(r, x.right);
|
||||
b = Math.max(b, x.bottom);
|
||||
}
|
||||
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
|
||||
})()`,
|
||||
},
|
||||
];
|
||||
|
||||
const MASK = `((pairs, inits) => {
|
||||
@@ -198,87 +197,20 @@ async function password() {
|
||||
}
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
const c = [
|
||||
process.env.BROWSER,
|
||||
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/usr/bin/chromium',
|
||||
'/usr/bin/google-chrome',
|
||||
];
|
||||
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
|
||||
}
|
||||
|
||||
/** A page over the DevTools protocol: send(method, params) and waitFor(event). */
|
||||
async function connect(wsUrl) {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
await new Promise((ok, fail) => {
|
||||
ws.onopen = ok;
|
||||
ws.onerror = fail;
|
||||
});
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const waiters = [];
|
||||
const listeners = [];
|
||||
ws.onmessage = (m) => {
|
||||
const msg = JSON.parse(m.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { ok, fail } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
||||
} else if (msg.method) {
|
||||
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
|
||||
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
||||
waiters.splice(waiters.indexOf(w), 1);
|
||||
w.ok(msg.params);
|
||||
}
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((ok, fail) => {
|
||||
pending.set(++id, { ok, fail });
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
||||
const on = (method, fn) => listeners.push({ method, fn });
|
||||
return { send, waitFor, on, close: () => ws.close() };
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
||||
|
||||
async function main() {
|
||||
const pass = await password();
|
||||
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
|
||||
const chrome = spawn(
|
||||
findBrowser(),
|
||||
[
|
||||
'--headless=new',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
// The router's certificate is usually for its public name, not router.lan.
|
||||
'--ignore-certificate-errors',
|
||||
'--hide-scrollbars',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
// MapLibre needs WebGL; headless gets it from SwiftShader.
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
// The router's certificate is usually for its public name, not router.lan.
|
||||
const b = await launch(['--ignore-certificate-errors', `--lang=${args.lang}`]);
|
||||
const { page, evaluate, go, waitSel } = b;
|
||||
try {
|
||||
const portFile = join(profile, 'DevToolsActivePort');
|
||||
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
|
||||
const port = readFileSync(portFile, 'utf8').split('\n')[0];
|
||||
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
||||
await page.send('Page.enable');
|
||||
// LuCI on auto speaks the browser's language: this one, whatever this computer's is.
|
||||
await page.send('Network.enable');
|
||||
await page.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': args.lang } });
|
||||
await page.send('Emulation.setEmulatedMedia', {
|
||||
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
|
||||
});
|
||||
// The person shown on the Person page; known once People has loaded (or from --person).
|
||||
const s = { person: args.person, portal: '' };
|
||||
const s = { person: args.person };
|
||||
if (args.demo) {
|
||||
page.on('Fetch.requestPaused', async (e) => {
|
||||
try {
|
||||
@@ -302,27 +234,6 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
const evaluate = async (expression) => {
|
||||
const r = await page.send('Runtime.evaluate', {
|
||||
expression,
|
||||
awaitPromise: true,
|
||||
returnByValue: true,
|
||||
});
|
||||
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||
return r.result.value;
|
||||
};
|
||||
const go = async (url) => {
|
||||
const loaded = page.waitFor('Page.loadEventFired');
|
||||
await page.send('Page.navigate', { url });
|
||||
await loaded;
|
||||
};
|
||||
const waitSel = async (sel, ms = 20000) => {
|
||||
for (let t = 0; t < ms; t += 250) {
|
||||
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error(`timed out waiting for ${sel}`);
|
||||
};
|
||||
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
|
||||
const viewport = (width, height = 2600) =>
|
||||
page.send('Emulation.setDeviceMetricsOverride', {
|
||||
@@ -350,24 +261,16 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
// The person to show (the first one on People unless --person) and their personal link.
|
||||
// The person to show: the first one on People unless --person.
|
||||
await go(`${LUCI}/server?section=people`);
|
||||
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
|
||||
if (!s.person)
|
||||
s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
|
||||
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
|
||||
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
|
||||
.then((r) => r.link ?? r.links?.[0] ?? '')`);
|
||||
|
||||
for (const shot of SHOTS) {
|
||||
if (args.only.length && !args.only.includes(shot.name)) continue;
|
||||
const url = shot.url(s);
|
||||
if (!url) {
|
||||
console.log(`skip ${shot.name}: no URL (the portal is off?)`);
|
||||
continue;
|
||||
}
|
||||
await viewport(shot.width);
|
||||
await go(url);
|
||||
await go(shot.url(s));
|
||||
await waitSel(shot.ready);
|
||||
await sleep(2000);
|
||||
if (shot.prep) await evaluate(shot.prep);
|
||||
@@ -379,14 +282,12 @@ async function main() {
|
||||
clip: { ...clip, scale: 1 },
|
||||
captureBeyondViewport: true,
|
||||
});
|
||||
writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64'));
|
||||
console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||
writeFileSync(join(RAW, `${shot.name}${SUFFIX}.png`), Buffer.from(data, 'base64'));
|
||||
console.log(`${shot.name}${SUFFIX}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
|
||||
}
|
||||
page.close();
|
||||
} finally {
|
||||
chrome.kill();
|
||||
await sleep(300);
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
await b.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// A headless Chromium driven over the DevTools protocol, no npm packages: what
|
||||
// the README screenshot scripts share (capture-screenshots.mjs from a router,
|
||||
// capture-portal.mjs from the portal demo). BROWSER=/path/to/chrome picks the
|
||||
// browser (default: Brave or Chrome on macOS); its profile is a throwaway one.
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
||||
|
||||
export function die(msg) {
|
||||
console.error(msg);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
export function findBrowser() {
|
||||
const c = [
|
||||
process.env.BROWSER,
|
||||
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/usr/bin/chromium',
|
||||
'/usr/bin/google-chrome',
|
||||
];
|
||||
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
|
||||
}
|
||||
|
||||
/** A page over the DevTools protocol: send(method, params), waitFor(event) and on(event, fn). */
|
||||
export async function connect(wsUrl) {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
await new Promise((ok, fail) => {
|
||||
ws.onopen = ok;
|
||||
ws.onerror = fail;
|
||||
});
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const waiters = [];
|
||||
const listeners = [];
|
||||
ws.onmessage = (m) => {
|
||||
const msg = JSON.parse(m.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
const { ok, fail } = pending.get(msg.id);
|
||||
pending.delete(msg.id);
|
||||
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
||||
} else if (msg.method) {
|
||||
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
|
||||
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
||||
waiters.splice(waiters.indexOf(w), 1);
|
||||
w.ok(msg.params);
|
||||
}
|
||||
}
|
||||
};
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((ok, fail) => {
|
||||
pending.set(++id, { ok, fail });
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
||||
const on = (method, fn) => listeners.push({ method, fn });
|
||||
return { send, waitFor, on, close: () => ws.close() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the browser headless on a fresh profile and connect to its first page. `flags` go on its command line
|
||||
* (a language, certificate errors). Returns the page, its helpers, and close() that ends the browser and removes
|
||||
* the profile.
|
||||
*/
|
||||
export async function launch(flags = []) {
|
||||
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
|
||||
const chrome = spawn(
|
||||
findBrowser(),
|
||||
[
|
||||
'--headless=new',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
'--hide-scrollbars',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
// MapLibre needs WebGL; headless gets it from SwiftShader.
|
||||
'--use-angle=swiftshader',
|
||||
'--enable-unsafe-swiftshader',
|
||||
...flags,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
const close = async () => {
|
||||
chrome.kill();
|
||||
await sleep(300);
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
};
|
||||
try {
|
||||
const portFile = join(profile, 'DevToolsActivePort');
|
||||
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
|
||||
const port = readFileSync(portFile, 'utf8').split('\n')[0];
|
||||
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
||||
await page.send('Page.enable');
|
||||
const evaluate = async (expression) => {
|
||||
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
||||
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||
return r.result.value;
|
||||
};
|
||||
const go = async (url) => {
|
||||
const loaded = page.waitFor('Page.loadEventFired');
|
||||
await page.send('Page.navigate', { url });
|
||||
await loaded;
|
||||
};
|
||||
const waitSel = async (sel, ms = 20000) => {
|
||||
for (let t = 0; t < ms; t += 250) {
|
||||
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error(`timed out waiting for ${sel}`);
|
||||
};
|
||||
return { page, evaluate, go, waitSel, close };
|
||||
} catch (e) {
|
||||
await close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
"""Frame the README screenshots the way the portal draws its own surfaces.
|
||||
|
||||
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
|
||||
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
|
||||
per CSS pixel (scripts/capture-screenshots.mjs takes the admin's from a router,
|
||||
scripts/capture-portal.mjs the portal's from its demo); the framed images
|
||||
are written to docs/screenshots/<name>.png at the same scale. Each page sits on
|
||||
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
|
||||
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
|
||||
@@ -22,14 +23,13 @@ import tempfile
|
||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
|
||||
OUT = os.path.join(ROOT, 'docs', 'screenshots')
|
||||
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
|
||||
'geist-latin-wght-normal.woff2')
|
||||
|
||||
SHOTS = ['overview', 'people', 'person', 'portal']
|
||||
# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
|
||||
# adding a device there would add one.
|
||||
SHOTS = ['overview', 'people', 'person', 'portal', 'overview-ru', 'people-ru', 'person-ru', 'portal-ru']
|
||||
# name -> the steps in front of its page, in order (raw captures). The portal's come from its demo
|
||||
# (scripts/capture-portal.mjs), not a router: adding a device there would add one. -ru: README_ru's.
|
||||
FLOWS = {
|
||||
'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
|
||||
'portal-ru': ['portal-add-1-ru', 'portal-add-2-ru', 'portal-add-3-ru'],
|
||||
}
|
||||
PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
|
||||
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
|
||||
@@ -45,7 +45,6 @@ CANDIDATES = [
|
||||
]
|
||||
|
||||
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
|
||||
@font-face{{font-family:Geist;src:url('file://{font}') format('woff2');font-weight:100 900}}
|
||||
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
|
||||
body{{position:relative;background:#080808}}
|
||||
.panel{{position:absolute;left:{px}px;top:{py}px;width:{pw}px;height:{ph}px;
|
||||
@@ -54,7 +53,7 @@ body{{position:relative;background:#080808}}
|
||||
box-shadow:0 0 0 1px rgba(255,255,255,.04)}}
|
||||
.sheet{{position:absolute;display:block;filter:drop-shadow(0 24px 48px rgba(0,0,0,.6))}}
|
||||
.n{{position:absolute;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;
|
||||
font:600 16px Geist,sans-serif;color:#ededed;background:#232323;
|
||||
font:600 16px system-ui,-apple-system,sans-serif;color:#ededed;background:#232323;
|
||||
box-shadow:0 0 0 1px rgba(255,255,255,.12),0 6px 16px rgba(0,0,0,.5)}}
|
||||
</style></head><body><div class="panel"></div><img class="page" src="file://{src}">{steps}</body></html>"""
|
||||
|
||||
@@ -111,7 +110,7 @@ def main():
|
||||
html = os.path.join(tmp, f'{name}.html')
|
||||
with open(html, 'w', encoding='utf-8') as f:
|
||||
f.write(TEMPLATE.format(w=w, h=h, x=x, y=y, iw=iw, ih=ih, px=x - INSET, py=y - INSET, pw=iw + 2 * INSET,
|
||||
ph=ih + 2 * INSET, src=src, font=FONT, steps=steps))
|
||||
ph=ih + 2 * INSET, src=src, steps=steps))
|
||||
out = os.path.join(OUT, f'{name}.png')
|
||||
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
|
||||
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
|
||||
|
||||
@@ -41,9 +41,13 @@ def strip_comments(text):
|
||||
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
|
||||
|
||||
|
||||
def blank_comments(text):
|
||||
"""Comments replaced by their newlines: line numbers stay, their text goes."""
|
||||
return re.sub(r'//[^\n]*|/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S)
|
||||
def blank_comments_templates(text):
|
||||
"""Comments and template literals replaced by their newlines, strings kept:
|
||||
line numbers stay, and a `}` that starts a line of a template (nft rules)
|
||||
ends no function. A template inside another one's `${…}` reads as code:
|
||||
good enough for how Dawnline writes them."""
|
||||
return re.sub(r"//[^\n]*|/\*.*?\*/|'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"|`(?:\\.|[^`\\])*`",
|
||||
lambda m: m.group(0) if m.group(0)[0] in '\'"' else '\n' * m.group(0).count('\n'), text, flags=re.S)
|
||||
|
||||
|
||||
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
|
||||
@@ -66,7 +70,7 @@ for f in files:
|
||||
problem(f"{f}:{line}: {name}() is used before its definition")
|
||||
# In a module an exported function is an expression statement: its closing
|
||||
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
|
||||
lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
|
||||
lines = blank_comments_templates(open(f, encoding='utf-8').read()).split('\n')
|
||||
inside = None
|
||||
for n, text in enumerate(lines, 1):
|
||||
if inside is None and re.match(r'^export function \w+\(', text):
|
||||
|
||||
@@ -129,16 +129,31 @@ const seen = (when, now) => {
|
||||
}[k] ?? 0
|
||||
);
|
||||
};
|
||||
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
|
||||
/**
|
||||
* A week of daily [rx, tx] that adds up to about a quarter of the month, today last (nothing before it was first
|
||||
* seen), rx (from the device) about an eighth.
|
||||
*/
|
||||
const week = (gb, last, now) =>
|
||||
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
|
||||
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => {
|
||||
const b = !gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7);
|
||||
return [Math.round(b * 0.12), b - Math.round(b * 0.12)];
|
||||
});
|
||||
/**
|
||||
* One second of the cast's traffic through a server (the k-th), [rx, tx] in bytes/s: a few devices streaming,
|
||||
* their uploads small. The same for a second whichever call asks, so the live chart keeps its shape.
|
||||
*/
|
||||
const meterRate = (ts, k) => {
|
||||
const wave = (a, b) => Math.sin(ts / a + k) * 0.45 + Math.sin(ts / b + 2 * k) * 0.25;
|
||||
const noise = (((ts * 7919 + k * 104729) % 1000) / 1000 - 0.5) * 0.35;
|
||||
return [Math.round(Math.max(0, 1.8e5 * (1 + wave(7, 17) + noise))), Math.round(Math.max(0, 1.6e6 * (1 + wave(9, 23) + noise)))];
|
||||
};
|
||||
let ipN = 10;
|
||||
/** A documentation address (the capture swaps public addresses for these anyway). */
|
||||
const ip = () => `203.0.113.${ipN++}`;
|
||||
const where = (city) => `${city} · ${CITIES[city][4]}`;
|
||||
|
||||
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
|
||||
const demo = { events: [], people: new Map(), days: [], now: 0 };
|
||||
/** What the last status made of the router's ids, for the calls that come after it (events, usage, the meter). */
|
||||
const demo = { events: [], people: new Map(), days: [], now: 0, servers: [] };
|
||||
|
||||
/**
|
||||
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
|
||||
@@ -255,6 +270,12 @@ function demoStatus(st, first) {
|
||||
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
|
||||
spark: week(gb, hs, now),
|
||||
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
|
||||
// As set up: nothing failing, its own link values the server's, its data flowing while online.
|
||||
link: null,
|
||||
setup: online ? { state: 'flowing', since: hs } : null,
|
||||
lan_bypass: false,
|
||||
mtu: 0,
|
||||
keepalive: null,
|
||||
};
|
||||
});
|
||||
for (const [name, ago, by] of c.added ?? []) {
|
||||
@@ -313,6 +334,7 @@ function demoStatus(st, first) {
|
||||
demo.events = events;
|
||||
points.sort((a, b) => b.ts - a.ts);
|
||||
demo.now = now;
|
||||
demo.servers = (st.servers ?? []).map((x) => x.id);
|
||||
demo.days = (st.series ?? []).map((x) => x.day);
|
||||
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
|
||||
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
|
||||
@@ -384,6 +406,16 @@ export function demoRpc(request, response, first) {
|
||||
},
|
||||
],
|
||||
};
|
||||
// Speed now, live: the last two minutes of the cast's traffic, not the router's.
|
||||
if (method === 'meter' && Array.isArray(data.points)) {
|
||||
const ids = demo.servers.length ? demo.servers : [...new Set(data.points.flatMap((p) => Object.keys(p.servers ?? {})))];
|
||||
const keep = data.keep > 1 ? data.keep : 120;
|
||||
const since = +args?.since || 0;
|
||||
const points = [];
|
||||
for (let ts = data.now - keep + 1; ts <= data.now; ts++)
|
||||
if (ts > since) points.push({ ts, servers: Object.fromEntries(ids.map((id, k) => [id, meterRate(ts, k)])) });
|
||||
return { ...r, result: [r.result[0], { ...data, ts: data.now, points }] };
|
||||
}
|
||||
if (method === 'events' && Array.isArray(data.events)) {
|
||||
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// dawnline.access: the Check access walk for a device that keeps its own
|
||||
// local network out of the tunnel (lan_bypass), and the way its internet
|
||||
// leaves, on a model and a network snapshot of the test's own (nothing read
|
||||
// from the container).
|
||||
import * as access from 'dawnline.access';
|
||||
|
||||
const KEY_TV = 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', KEY_PHONE = 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=';
|
||||
|
||||
/** Bob (Internet only) on a server that sends everyone direct: a TV with lan_bypass and a phone without. */
|
||||
function model() {
|
||||
return {
|
||||
settings: { portal_enabled: false },
|
||||
servers: {
|
||||
home: { id: 'home', name: 'Home', ifname: 'awghome', subnet: '10.9.0.0/29', private_key: 'k', enabled: true, lan_like: false,
|
||||
auto_wan: false, wan_device: 'eth1', auto_lan: false, lan_devices: [ 'br-lan' ], mesh: 'all', device_mesh: true, dns: [] },
|
||||
},
|
||||
people: { bob: { id: 'bob', name: 'Bob', server: 'home', access: 'internet', services: [], devices: [ 'tv', 'phone' ] } },
|
||||
devices: {
|
||||
tv: { id: 'tv', person: 'bob', name: 'TV', address: '10.9.0.2', public_key: KEY_TV, lan_bypass: true },
|
||||
phone: { id: 'phone', person: 'bob', name: 'Phone', address: '10.9.0.3', public_key: KEY_PHONE, lan_bypass: false },
|
||||
},
|
||||
services: {},
|
||||
circles: {},
|
||||
};
|
||||
}
|
||||
|
||||
const CTX = {
|
||||
states: { bob: 'active' },
|
||||
dmp: { peers: {}, windows: {} },
|
||||
snap: {
|
||||
devices: {
|
||||
'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] },
|
||||
eth1: { nets: [ '203.0.113.0/24' ], zone: 'wan', addrs: [ '203.0.113.7/24' ] },
|
||||
awghome: { nets: [ '10.9.0.0/29' ], addrs: [ '10.9.0.1/29' ] },
|
||||
},
|
||||
lan: 'br-lan',
|
||||
wan: 'eth1',
|
||||
},
|
||||
};
|
||||
|
||||
function last(r) {
|
||||
return r.steps[length(r.steps) - 1];
|
||||
}
|
||||
|
||||
test('check: a device with its local network outside the tunnel', () => {
|
||||
let m = model();
|
||||
let r = access.check(m, 'tv', '192.168.1.20', CTX);
|
||||
eq([ r.ok, last(r).ok, last(r).title ], [ false, false, "Its configuration doesn't send it to the router" ],
|
||||
'a home address: on its own network, not blocked in the tunnel');
|
||||
ok(index(last(r).detail, "the device's own network handles it") >= 0, 'says where it goes');
|
||||
r = access.check(m, 'tv', '192.168.1.1:80', CTX);
|
||||
eq(last(r).title, "Its configuration doesn't send it to the router", 'the router\'s LAN address is on its own network too');
|
||||
r = access.check(m, 'tv', '10.9.0.1:53', CTX);
|
||||
eq([ r.ok, r.steps[1].title ], [ true, '10.9.0.1 is this router: DNS is open to everyone' ], 'its DNS stays in the tunnel');
|
||||
r = access.check(m, 'tv', '8.8.8.8', CTX);
|
||||
eq([ r.ok, last(r).title, last(r).detail ], [ true, '8.8.8.8 is on the internet', 'It leaves through eth1.' ], 'the internet through the tunnel');
|
||||
|
||||
r = access.check(m, 'phone', '192.168.1.20', CTX);
|
||||
eq([ r.ok, last(r).title ], [ false, '192.168.1.20 is at home (br-lan)' ], 'without it: into the tunnel, and blocked there');
|
||||
});
|
||||
|
||||
test('check: the way out is the server\'s', () => {
|
||||
let m = model();
|
||||
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves through eth1.', 'direct');
|
||||
m.servers.home.lan_like = true;
|
||||
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves like a home device would.', 'like a home device');
|
||||
});
|
||||
@@ -1,8 +1,18 @@
|
||||
// dawnline.awg: disguise presets against their own validation, the parser
|
||||
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
|
||||
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
|
||||
// dawnline.awg: disguise presets against their own validation, the values
|
||||
// AmneziaWG refuses (obf_unsafe, one case per rule), the parser of `awg show
|
||||
// <ifname> dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 and how
|
||||
// each tunnel's read went (the stand-in awg in fixtures/bin prints the
|
||||
// fixture put at AWG_DUMP), the devices a tunnel should hold, Reconnect, a
|
||||
// device's configuration from the fixture model, what the server's interface
|
||||
// and the read-only status get of it.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { valid_key, cidr_any } from 'dawnline.util';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as backup from 'dawnline.backup';
|
||||
import * as rpc_status from 'dawnline.rpc.status';
|
||||
import * as nft from 'dawnline.nft';
|
||||
|
||||
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
|
||||
let fixtures = sourcepath(0, true) + '/fixtures';
|
||||
@@ -32,7 +42,8 @@ test('obf_preset balanced', () => {
|
||||
|
||||
test('obf_preset max', () => {
|
||||
let o = awg.obf_preset('max');
|
||||
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey');
|
||||
ok(valid_key(o.header_protection_key), 'a header protection key');
|
||||
ok(o.header_protection_key != awg.obf_preset('max').header_protection_key, 'made for each server, without 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');
|
||||
@@ -44,55 +55,279 @@ test('obf_preset max', () => {
|
||||
shapes[awg.obf_preset('max').i1] = true;
|
||||
ok(length(keys(shapes)) > 1, 'signature packets differ between servers');
|
||||
// The preset passes the server's own validation (jmin/jmax may be small: 0.5.2).
|
||||
eq(awg.obf_errors(o), [], 'max is valid');
|
||||
for (let i = 0; i < 25; i++)
|
||||
eq(awg.obf_errors(awg.obf_preset('max')), [], 'max is valid');
|
||||
});
|
||||
|
||||
test('obf_errors', () => {
|
||||
test('obf_errors: Dawnline\'s own bounds on top of obf_unsafe', () => {
|
||||
eq(awg.obf_errors({}), [], 'nothing set');
|
||||
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range');
|
||||
eq(awg.obf_errors(null), [], 'no values');
|
||||
eq(awg.obf_errors({ jc: '11' }), [ 'Jc must be from 0 to 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_errors({ jmin: '2000', jmax: '3000' }), [ 'Jmin must be from 0 to 1024.', 'Jmax must be from 0 to 1024.' ], 'junk sizes');
|
||||
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 'S2 must not be S1 + 56: the handshake initiation and response would have the same size.' ],
|
||||
'the handshake size clash');
|
||||
eq(awg.obf_errors({ s4: '33' }), [ 'S4 must be from 0 to 32.' ], 's4 range');
|
||||
// What AmneziaWG refuses comes first, said once.
|
||||
eq(awg.obf_errors({ jc: 'x' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'not a number');
|
||||
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'Jmin must not be larger than Jmax.' ], 'order');
|
||||
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'duplicate headers');
|
||||
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');
|
||||
});
|
||||
|
||||
// One case per rule of obf_unsafe: what an import, a restore or a hand edit must never hand to the kernel.
|
||||
const HPK = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||
const MAX = { s1: '12', s2: '12', s3: '12', s4: '12', header_protection_key: HPK };
|
||||
|
||||
test('obf_unsafe: what the presets and older servers hold passes', () => {
|
||||
eq(awg.obf_unsafe(null), [], 'no values');
|
||||
eq(awg.obf_unsafe(awg.obf_preset('off')), [], 'off');
|
||||
for (let i = 0; i < 25; i++) {
|
||||
eq(awg.obf_unsafe(awg.obf_preset('balanced')), [], 'balanced');
|
||||
eq(awg.obf_unsafe(awg.obf_preset('max')), [], 'max');
|
||||
}
|
||||
// Values from before 0.8 and hand-tuned ones the kernel takes: none of Dawnline's own bounds here.
|
||||
let old = { jc: '12', jmin: '50', jmax: '1400', s1: '100', s2: '156', h1: '1234567', h2: '2345678', h3: '3456789', h4: '4567890' };
|
||||
eq(awg.obf_unsafe(old), [], 'older and hand-tuned values');
|
||||
ok(length(awg.obf_errors(old)) > 0, 'which a new server would not get');
|
||||
});
|
||||
|
||||
test('obf_unsafe: 16-bit numbers', () => {
|
||||
eq(awg.obf_unsafe({ jc: '65535', s4: '0' }), [], 'the ends');
|
||||
eq(awg.obf_unsafe({ jc: '65536' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'too large');
|
||||
eq(awg.obf_unsafe({ s3: '-1' }), [ 'S3 must be a whole number from 0 to 65535.' ], 'negative');
|
||||
eq(awg.obf_unsafe({ jmax: '1e3' }), [ 'Jmax must be a whole number from 0 to 65535.' ], 'not digits');
|
||||
});
|
||||
|
||||
test('obf_unsafe: Jmin not above Jmax', () => {
|
||||
eq(awg.obf_unsafe({ jmin: '50', jmax: '50' }), [], 'equal');
|
||||
eq(awg.obf_unsafe({ jmin: '51', jmax: '50' }), [ 'Jmin must not be larger than Jmax.' ], 'the kernel would write past its junk buffer');
|
||||
eq(awg.obf_unsafe({ jmin: '51' }), [], 'Jmax not given');
|
||||
});
|
||||
|
||||
test('obf_unsafe: header values are numbers or ranges', () => {
|
||||
eq(awg.obf_unsafe({ h1: '100-200', h2: '300', h3: '4294967295', h4: '0' }), [], 'numbers and ranges');
|
||||
eq(awg.obf_unsafe({ h1: '200-100' }), [ 'H1 must be a number or a range like 100-200, up to 4294967295.' ], 'reversed');
|
||||
eq(awg.obf_unsafe({ h2: '4294967296' }), [ 'H2 must be a number or a range like 100-200, up to 4294967295.' ], 'past 32 bits');
|
||||
eq(awg.obf_unsafe({ h3: '5-6-7' }), [ 'H3 must be a number or a range like 100-200, up to 4294967295.' ], 'two dashes');
|
||||
eq(awg.obf_unsafe({ h4: 'abc' }), [ 'H4 must be a number or a range like 100-200, up to 4294967295.' ], 'not a number');
|
||||
});
|
||||
|
||||
test('obf_unsafe: header values do not overlap', () => {
|
||||
eq(awg.obf_unsafe({ h1: '10-20', h2: '20-30', h3: '40', h4: '50' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'a shared end');
|
||||
eq(awg.obf_unsafe({ h1: '10-20', h2: '30', h3: '15', h4: '50' }), [ 'H1 and H3 overlap: each packet type needs values of its own.' ], 'one inside a range');
|
||||
// One not given keeps WireGuard's type: 1-4.
|
||||
eq(awg.obf_unsafe({ h1: '1-10' }), [ 'H1 and H2 overlap: each packet type needs values of its own.', 'H1 and H3 overlap: each packet type needs values of its own.',
|
||||
'H1 and H4 overlap: each packet type needs values of its own.' ], 'over the default types');
|
||||
eq(awg.obf_unsafe({ h1: '5-10' }), [], 'clear of them');
|
||||
});
|
||||
|
||||
test('obf_unsafe: header protection needs a key and 12-byte padding', () => {
|
||||
eq(awg.obf_unsafe(MAX), [], 'the 3.1 values');
|
||||
eq(awg.obf_unsafe({ ...MAX, header_protection_key: 'abc' }), [ 'The header protection key is not a key.' ], 'not a key');
|
||||
eq(awg.obf_unsafe({ ...MAX, s3: '11' }), [ 'S3 must be at least 12 with header protection.' ], 'too little padding');
|
||||
eq(awg.obf_unsafe({ ...MAX, s4: null }), [ 'S4 must be at least 12 with header protection.' ], 'no padding');
|
||||
eq(awg.obf_unsafe({ s1: '0', s2: '0' }), [], 'none needed without the key');
|
||||
});
|
||||
|
||||
test('obf_unsafe: 3.1 timers and counts', () => {
|
||||
eq(awg.obf_unsafe({ rekey_after_time: '100-120', rekey_timeout: '3', keepalive_timeout: '0', max_handshake_attempts: '0-0' }), [],
|
||||
'numbers, ranges and 0 (the default)');
|
||||
eq(awg.obf_unsafe({ rekey_timeout: '0-7' }), [ 'RekeyTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'a 0 in a range');
|
||||
eq(awg.obf_unsafe({ keepalive_timeout: '15-5' }), [ 'KeepaliveTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'reversed');
|
||||
eq(awg.obf_unsafe({ max_handshake_attempts: '70000' }), [ 'MaxHandshakeAttempts must be a number or a range like 5-15, from 1 to 65535.' ], 'past 16 bits');
|
||||
eq(awg.obf_unsafe({ content_padding_addition: '0-100' }), [], 'padding may start at 0');
|
||||
eq(awg.obf_unsafe({ content_padding_addition: '10-x' }), [ 'ContentPaddingAddition must be a number or a range like 10-100, up to 65535.' ], 'padding');
|
||||
});
|
||||
|
||||
test('obf_unsafe: RejectAfterTime up to 180 seconds', () => {
|
||||
eq(awg.obf_unsafe({ reject_after_time: '150-180' }), [], 'the preset');
|
||||
eq(awg.obf_unsafe({ reject_after_time: '150-181' }), [ 'RejectAfterTime must be at most 180 seconds.' ], 'the kernel drops keys after 180 seconds');
|
||||
});
|
||||
|
||||
test('obf_unsafe: switches', () => {
|
||||
eq(awg.obf_unsafe({ random_trailers: 'on', disable_cookies: '0' }), [], 'on, off, 1, 0');
|
||||
eq(awg.obf_unsafe({ random_trailers: 'yes' }), [ 'RandomTrailers must be on or off.' ], 'what the .conf parser refuses');
|
||||
eq(awg.obf_unsafe({ disable_cookies: 'true' }), [ 'DisableCookies must be on or off.' ], 'the same for cookies');
|
||||
});
|
||||
|
||||
test('obf_unsafe: signature packet tags', () => {
|
||||
let bad = (name, tag) => `${name}: <${tag}> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.`;
|
||||
eq(awg.obf_unsafe({ i1: '<b 0xC0ffee><r 1><rc 1000><rd 12><t>', i2: 'text between tags <r 2> is skipped' }), [], 'every tag both parsers know');
|
||||
eq(awg.obf_unsafe({ i1: '<b 0xabc>' }), [ bad('I1', 'b 0xabc') ], 'an odd number of hex digits');
|
||||
eq(awg.obf_unsafe({ i1: '<b 0x>' }), [ bad('I1', 'b 0x') ], 'no bytes');
|
||||
eq(awg.obf_unsafe({ i1: '<b ff00>' }), [ bad('I1', 'b ff00') ], 'no 0x (the kernel needs it)');
|
||||
eq(awg.obf_unsafe({ i1: '<b 0xzz>' }), [ bad('I1', 'b 0xzz') ], 'not hex');
|
||||
eq(awg.obf_unsafe({ i2: '<r -5>' }), [ bad('I2', 'r -5') ], 'a negative length writes past the packet');
|
||||
eq(awg.obf_unsafe({ i2: '<rc 0>' }), [ bad('I2', 'rc 0') ], 'no length');
|
||||
eq(awg.obf_unsafe({ i2: '<rd 1001>' }), [ bad('I2', 'rd 1001') ], 'too long');
|
||||
eq(awg.obf_unsafe({ i3: '<r 5>' }), [ bad('I3', 'r 5') ], 'two spaces');
|
||||
eq(awg.obf_unsafe({ i3: '<t >' }), [ bad('I3', 't ') ], 'a space after t');
|
||||
eq(awg.obf_unsafe({ i4: '<c>' }), [ bad('I4', 'c') ], 'the kernel\'s counter, which amneziawg-go refuses');
|
||||
for (let t in [ 'd', 'ds', 'dz' ])
|
||||
eq(awg.obf_unsafe({ i4: `<${t}>` }), [ bad('I4', t) ], `amneziawg-go's <${t}>, which the kernel refuses`);
|
||||
eq(awg.obf_unsafe({ i5: '<>' }), [ bad('I5', '') ], 'an empty tag');
|
||||
eq(awg.obf_unsafe({ i5: '<r <5>' }), [ bad('I5', 'r <5') ], 'a tag inside a tag');
|
||||
eq(awg.obf_unsafe({ i5: '<b 0x0102030405060708090a0b0c0d0e0f>' }), [], 'long tags are fine');
|
||||
eq(awg.obf_unsafe({ i5: '<x 0x0102030405060708090a0b0c0d0e0f>' }), [ bad('I5', 'x 0x0102030405060708090a…') ], 'shown cut short');
|
||||
eq(awg.obf_unsafe({ i1: '<r 5' }), [ 'I1 has a tag that is not closed with >.' ], 'not closed');
|
||||
eq(awg.obf_unsafe({ i1: '<r 5><b 0x00> # note' }), [ 'I1 may not contain # or a line break.' ], 'a comment in a .conf');
|
||||
eq(awg.obf_unsafe({ i1: '<r 5>\n<t>' }), [ 'I1 may not contain # or a line break.' ], 'a line break');
|
||||
});
|
||||
|
||||
test('obf_unsafe: I1-I5 fit one configuration', () => {
|
||||
// A tag of 100 characters.
|
||||
let tag = '<b 0x';
|
||||
for (let n = 0; n < 47; n++)
|
||||
tag += 'ab';
|
||||
tag += '>';
|
||||
let many = (n) => {
|
||||
let out = '';
|
||||
for (let k = 0; k < n; k++)
|
||||
out += tag;
|
||||
return out;
|
||||
};
|
||||
let four = many(4);
|
||||
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: four }), [], '2000 characters');
|
||||
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: many(5) }), [ 'I1-I5 together must be at most 2000 characters, not 2100.' ], 'over 2000');
|
||||
});
|
||||
|
||||
test('obf_unsafe: an import or restore with such values is refused', () => {
|
||||
let dir = '/tmp/dawnline-tests/import';
|
||||
let errs = (text) => {
|
||||
system(`rm -rf ${dir}; mkdir -p ${dir}/.delta`);
|
||||
writefile(`${dir}/dawnline`, text);
|
||||
let c = cursor(dir, `${dir}/.delta`);
|
||||
c.load('dawnline');
|
||||
let out = backup.config_errors(c);
|
||||
system(`rm -rf ${dir}`);
|
||||
return out;
|
||||
};
|
||||
let fixture = readfile('/etc/config/dawnline');
|
||||
let bad = errs(replace(fixture, "option jmax '128'", "option jmax '32'"));
|
||||
ok(index(bad, 'Server Main: Jmin must not be larger than Jmax.') >= 0, `refused: ${join(' ', bad)}`);
|
||||
eq(filter(errs(fixture), (e) => index(e, 'Jmin') >= 0), [], 'the fixture as it is');
|
||||
});
|
||||
|
||||
// The stand-in's call log and failures (fixtures/bin/awg).
|
||||
const AWG_CALLS = '/tmp/dawnline-tests/awg-calls';
|
||||
const AWG_FAIL = '/tmp/dawnline-tests/awg-fail-';
|
||||
const SERVER_KEY = 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=';
|
||||
const PEER_ON = 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=', PEER_NEW = 'TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0=';
|
||||
|
||||
// A fixture's lines as another interface's (`show all` prints the ifname first).
|
||||
function lines_as(name, ifname) {
|
||||
let out = '';
|
||||
for (let l in split(readfile(`${fixtures}/awg-dump-${name}.txt`), '\n'))
|
||||
if (l != '')
|
||||
out += `${ifname}${substr(l, length('awgmain'))}\n`;
|
||||
return out;
|
||||
}
|
||||
|
||||
// lo is in every container's /sys/class/net (index 1), and is no AmneziaWG
|
||||
// interface: the stand-in prints the fixture's lines for it, as for a tunnel.
|
||||
function dump_of(name) {
|
||||
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
|
||||
return awg.dump();
|
||||
writefile(AWG_DUMP, lines_as(name, 'lo'));
|
||||
return awg.dump([ 'lo' ]);
|
||||
}
|
||||
|
||||
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');
|
||||
eq(d.reads, { lo: 'read' }, 'read');
|
||||
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface; its index is the epoch of its counters');
|
||||
eq(d.peers[PEER_ON], { ifname: 'lo', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 },
|
||||
'peer with a session, with the ifname the lines leave out');
|
||||
eq(d.peers[PEER_NEW], { ifname: 'lo', 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');
|
||||
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
|
||||
eq(keys(d.peers), [ PEER_ON ], '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(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
|
||||
eq(length(d.peers), 2, 'two peers');
|
||||
});
|
||||
|
||||
test('dump: the tool fails', () => {
|
||||
// awgmain is not in the container's /sys/class/net, as a tunnel netifd could not bring up.
|
||||
test('dump: a tunnel that is not there is down, without a process', () => {
|
||||
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`));
|
||||
unlink(AWG_CALLS);
|
||||
eq(awg.dump([ 'awgmain' ]), { ok: true, reads: { awgmain: 'down' }, ifaces: {}, peers: {} }, 'its counters are gone');
|
||||
eq(readfile(AWG_CALLS), null, 'awg is not asked about a link the kernel does not have');
|
||||
eq(awg.dump([]), { ok: true, reads: {}, ifaces: {}, peers: {} }, 'no tunnel runs');
|
||||
});
|
||||
|
||||
test('dump: each tunnel on its own', () => {
|
||||
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`) + lines_as('2.0', 'lo'));
|
||||
let d = awg.dump([ 'awgmain', 'lo' ]);
|
||||
eq([ d.ok, d.reads ], [ true, { awgmain: 'down', lo: 'read' } ], 'one down, one read');
|
||||
eq(keys(d.ifaces), [ 'lo' ], 'only what was read');
|
||||
eq(filter(values(d.peers), (p) => p.ifname != 'lo'), [], 'no peers of the one that is down');
|
||||
});
|
||||
|
||||
// The tool says "Operation not supported" for lo on a real system.
|
||||
test('dump: a tunnel that exists but cannot be read', () => {
|
||||
writefile(AWG_DUMP, lines_as('2.0', 'lo'));
|
||||
writefile(`${AWG_FAIL}lo`, 'Unable to access interface: Operation not supported\n');
|
||||
let d = awg.dump([ 'awgmain', 'lo' ]);
|
||||
unlink(`${AWG_FAIL}lo`);
|
||||
eq(d.ok, false, 'not every tunnel was read');
|
||||
eq(d.reads, { awgmain: 'down', lo: 'error' }, 'each on its own');
|
||||
eq([ d.ifaces, d.peers ], [ {}, {} ], 'nothing of the failed one');
|
||||
});
|
||||
|
||||
// The agent's watcher reads every second: with one server, one process.
|
||||
test('dump: only the tunnels asked for, one process each', () => {
|
||||
writefile(AWG_DUMP, lines_as('1.0', 'lo') + lines_as('2.0', 'wgclient'));
|
||||
unlink(AWG_CALLS);
|
||||
let d = awg.dump([ 'lo' ]);
|
||||
// The tests after these find no tunnel, as on a router without AmneziaWG running.
|
||||
unlink(AWG_DUMP);
|
||||
let d = awg.dump();
|
||||
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
|
||||
eq(readfile(AWG_CALLS), 'show lo dump\n', 'one call, never `all`');
|
||||
eq(keys(d.ifaces), [ 'lo' ], 'the other tunnel is not read');
|
||||
eq(d.peers[PEER_ON].ifname, 'lo', 'its peers stand in for none of ours');
|
||||
});
|
||||
|
||||
test('tunnel_devices: what sync_peers loads', () => {
|
||||
let m = {
|
||||
servers: { s: { public_key: SERVER_KEY } },
|
||||
people: { a: { id: 'a', server: 's' }, b: { id: 'b', server: 's' }, c: { id: 'c', server: 'other' } },
|
||||
devices: {
|
||||
on: { person: 'a', public_key: PEER_ON, address: '10.9.0.2' },
|
||||
own: { person: 'a', public_key: SERVER_KEY, address: '10.9.0.8' },
|
||||
off: { person: 'a', public_key: PEER_NEW, address: '10.9.0.3', disabled: true },
|
||||
paused: { person: 'b', public_key: SERVER_KEY, address: '10.9.0.4' },
|
||||
elsewhere: { person: 'c', public_key: PEER_NEW, address: '10.9.0.5' },
|
||||
badkey: { person: 'a', public_key: 'not a key', address: '10.9.0.6' },
|
||||
badaddr: { person: 'a', public_key: PEER_NEW, address: '' },
|
||||
nobody: { person: 'gone', public_key: PEER_NEW, address: '10.9.0.7' },
|
||||
},
|
||||
};
|
||||
let st = { a: 'quota', b: 'paused', c: 'active' };
|
||||
eq(map(awg.tunnel_devices(m, 's', st), (d) => d.address), [ '10.9.0.2' ],
|
||||
'over the limit stays; off, paused, other servers, lines syncconf would refuse and the server\'s own key (ignored by the kernel) do not');
|
||||
eq(map(awg.tunnel_devices(m, 'other', st), (d) => d.address), [ '10.9.0.5' ], 'the other server');
|
||||
eq(awg.tunnel_devices(m, 'none', st), [], 'none');
|
||||
});
|
||||
|
||||
test('peer_diff: by key, per tunnel', () => {
|
||||
let dmp = { peers: {} };
|
||||
dmp.peers[PEER_ON] = { ifname: 'awgmain' };
|
||||
dmp.peers[SERVER_KEY] = { ifname: 'awgmain' };
|
||||
dmp.peers[PEER_NEW] = { ifname: 'awgother' };
|
||||
let devs = (...ks) => map(ks, (k) => ({ public_key: k }));
|
||||
eq(awg.peer_diff(devs(PEER_ON, SERVER_KEY), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 0 }, 'the same');
|
||||
eq(awg.peer_diff(devs(PEER_ON, PEER_NEW), dmp, 'awgmain'), { loaded: 2, missing: 1, extra: 1 },
|
||||
'a stale peer standing in for a missing one');
|
||||
eq(awg.peer_diff(devs(PEER_ON), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 1 }, 'one too many');
|
||||
eq(awg.peer_diff(devs(PEER_NEW), dmp, 'awgdown'), { loaded: 0, missing: 1, extra: 0 }, 'a tunnel with no peers read');
|
||||
eq(awg.peer_diff([], { peers: {} }, 'awgmain'), { loaded: 0, missing: 0, extra: 0 }, 'nothing either way');
|
||||
});
|
||||
|
||||
test('handshake_since: Reconnect hides older handshakes', () => {
|
||||
@@ -114,4 +349,208 @@ test('blocked reasons', () => {
|
||||
// Files of older versions hold the English fragment after the name.
|
||||
eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment');
|
||||
eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment');
|
||||
// Values AmneziaWG refuses: which ones, from the server's own when read.
|
||||
let bad = { name: 'Home', obf: { jmin: '60', jmax: '50' }, blocked: { code: 'disguise_invalid' } };
|
||||
eq(awg.blocked_text(bad), 'Home is kept down: its disguise has values AmneziaWG cannot take. Jmin must not be larger than Jmax.', 'invalid values');
|
||||
eq(awg.blocked_text({ ...bad, obf: {} }), 'Home is kept down: its disguise has values AmneziaWG cannot take.', 'fixed since');
|
||||
eq(awg.blocked_note(bad.blocked), 'is kept down: its disguise has values AmneziaWG cannot take', 'the log');
|
||||
eq(awg.blocked_fix(bad.blocked), 'Choose a disguise on the Server page: it replaces the values set by hand.', 'what to do about it');
|
||||
eq(awg.blocked_fix({ code: 'taken', ifname: 'wg0' }), 'Choose another interface name in the server settings.', 'what to do about a name');
|
||||
});
|
||||
|
||||
test('netifd_options: the server keeps its defence against handshake floods', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main;
|
||||
srv.obf = awg.obf_preset('max');
|
||||
let o = awg.netifd_options(srv);
|
||||
ok('awg_disable_cookies' in o, 'named, so netifd.sync takes it off an interface that had it');
|
||||
eq(o.awg_disable_cookies, null, 'no DisableCookies on the server');
|
||||
eq([ o.awg_header_protection_key, o.awg_jc, o.awg_i1, o.awg_random_trailers ], [ srv.obf.header_protection_key, srv.obf.jc, srv.obf.i1, 'on' ],
|
||||
'the rest of the disguise stays');
|
||||
ok(index(split(awg.client_config(m, m.devices.alice_phone).conf, '\n'), 'DisableCookies = on') >= 0, 'devices keep it');
|
||||
});
|
||||
|
||||
test('client_config: one keep-alive for the .conf and the AmneziaVPN key', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main, dev = m.devices.alice_phone;
|
||||
let ka = () => {
|
||||
let c = awg.client_config(m, dev);
|
||||
return [ match(c.conf, /\nPersistentKeepalive = ([^\n]*)\n/)?.[1], c.amnezia.persistent_keep_alive ];
|
||||
};
|
||||
eq(ka(), [ '25', '25' ], 'a number without header protection');
|
||||
srv.obf = awg.obf_preset('max');
|
||||
eq(ka(), [ '25-35', '25-35' ], 'jittered with 3.1');
|
||||
srv.keepalive = 0;
|
||||
eq(ka(), [ null, '0' ], 'off');
|
||||
});
|
||||
|
||||
test('status: the header protection key stays out of what read-only users get', () => {
|
||||
eq(awg.obf_public({ jc: '4', header_protection_key: HPK }), { jc: '4' }, 'obf_public');
|
||||
eq(awg.obf_public(null), {}, 'no values');
|
||||
// Server main on Maximum, as a uci change not committed (the fixture file stays as it is).
|
||||
let c = cursor();
|
||||
c.load('dawnline');
|
||||
let o = awg.obf_preset('max');
|
||||
for (let k, v in o)
|
||||
c.set('dawnline', 'main', k, v);
|
||||
c.save('dawnline');
|
||||
let out = rpc_status.methods.status.call({ args: { days: 30 } });
|
||||
c.revert('dawnline');
|
||||
eq(out.error, null, 'status answers');
|
||||
let srv = filter(out.servers ?? [], (x) => x.id == 'main')[0];
|
||||
eq([ srv?.hpk, srv?.obf?.header_protection_key, srv?.obf?.disable_cookies ], [ true, null, 'on' ], 'whether there is a key, not which');
|
||||
let text = sprintf('%J', out);
|
||||
ok(index(text, o.header_protection_key) < 0, 'the key is nowhere in the answer');
|
||||
let found = uniq(map(match(text, /[A-Za-z0-9+\/]{43}=/g) ?? [], (x) => x[0]));
|
||||
eq(found, [ srv.public_key ], 'no key but the server\'s public one');
|
||||
});
|
||||
|
||||
test('client_config: an IPv6 endpoint in brackets, without a regex', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main, dev = m.devices.alice_phone;
|
||||
let ep = (h) => {
|
||||
srv.endpoint = h;
|
||||
return match(awg.client_config(m, dev).conf, /\nEndpoint = ([^\n]*)\n/)?.[1];
|
||||
};
|
||||
eq(ep('vpn.example.com'), 'vpn.example.com:51820', 'a name');
|
||||
eq(ep('203.0.113.7'), '203.0.113.7:51820', 'IPv4');
|
||||
eq(ep('2001:db8::1'), '[2001:db8::1]:51820', 'IPv6');
|
||||
eq(ep('[2001:db8::1]'), '[2001:db8::1]:51820', 'IPv6 in brackets already');
|
||||
eq(ep(''), 'vpn.example.com:51820', 'the portal name when the server has none');
|
||||
// The regexes it stands for, on hosts changed at each character.
|
||||
for (let h in [ '2001:db8::1', '[::1]', 'a.b' ])
|
||||
for (let i = 0; i <= length(h); i++)
|
||||
for (let c in [ ':', '[', ']', 'a', '' ]) {
|
||||
let s = `${substr(h, 0, i)}${c}${substr(h, i + 1)}`;
|
||||
let want = match(s, /:/) && !match(s, /^\[/) ? `[${s}]` : s;
|
||||
eq(ep(s), `${want || 'vpn.example.com'}:51820`, s);
|
||||
}
|
||||
});
|
||||
|
||||
test('config_fingerprint leaves out the private key and the junk', () => {
|
||||
let m = core.load();
|
||||
let dev = m.devices.alice_phone;
|
||||
let f = awg.config_fingerprint(m, dev);
|
||||
ok(match(f, /^[0-9a-f]{8}$/), 'eight hex digits');
|
||||
dev.private_key = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||
eq(awg.config_fingerprint(m, dev), f, 'a private key');
|
||||
m.servers.main.obf.jc = '7';
|
||||
eq(awg.config_fingerprint(m, dev), f, 'another junk count');
|
||||
m.servers.main.port = 51821;
|
||||
ok(awg.config_fingerprint(m, dev) != f, 'another port');
|
||||
eq(awg.config_fingerprint(m, null), null, 'no device');
|
||||
});
|
||||
|
||||
/* ---------- a device's local network, MTU and keep-alive ---------- */
|
||||
|
||||
// Exactly the complement: aligned prefixes, none overlapping another or a
|
||||
// private range, and all of them together the whole address space.
|
||||
test('BYPASS4: every IPv4 address outside the private ranges, once', () => {
|
||||
let nets = [ ...map(awg.BYPASS4, (n) => [ n, false ]), ...map(nft.PRIVATE4, (n) => [ n, true ]) ];
|
||||
let total = 0;
|
||||
for (let i = 0; i < length(nets); i++) {
|
||||
let a = cidr_any(nets[i][0]);
|
||||
ok(a && a.ip == a.net, `${nets[i][0]}: a prefix`);
|
||||
total += a.size;
|
||||
for (let j = i + 1; j < length(nets); j++) {
|
||||
let b = cidr_any(nets[j][0]);
|
||||
ok(a.net + a.size <= b.net || b.net + b.size <= a.net, `${nets[i][0]} and ${nets[j][0]} apart`);
|
||||
}
|
||||
}
|
||||
eq(total, 4294967296, 'together: every address');
|
||||
});
|
||||
|
||||
test('BYPASS6: every IPv6 address outside fc00::/7, fe80::/10 and ff00::/8, once', () => {
|
||||
// Each of them is /16 or wider: the first 16 bits decide.
|
||||
let span = (n) => {
|
||||
let p = split(n, '/'), len = +p[1];
|
||||
ok(len >= 1 && len <= 16 && substr(p[0], -2) == '::', `${n}: a prefix of the first 16 bits`);
|
||||
let g = substr(p[0], 0, length(p[0]) - 2);
|
||||
let start = g == '' ? 0 : hex(g), size = 1 << (16 - len);
|
||||
ok(start % size == 0, `${n}: aligned`);
|
||||
return [ start, size ];
|
||||
};
|
||||
let nets = map([ ...awg.BYPASS6, 'fc00::/7', 'fe80::/10', 'ff00::/8' ], span);
|
||||
let total = 0;
|
||||
for (let i = 0; i < length(nets); i++) {
|
||||
total += nets[i][1];
|
||||
for (let j = i + 1; j < length(nets); j++)
|
||||
ok(nets[i][0] + nets[i][1] <= nets[j][0] || nets[j][0] + nets[j][1] <= nets[i][0], `${i} and ${j} apart`);
|
||||
}
|
||||
eq(total, 65536, 'together: every address');
|
||||
});
|
||||
|
||||
test('allowed_ips: the local network outside the tunnel', () => {
|
||||
let m = core.load();
|
||||
let srv = m.servers.main;
|
||||
// No home network from the container's own interfaces.
|
||||
srv.auto_lan = false;
|
||||
srv.lan_devices = [];
|
||||
let alice = m.people.alice, bob = m.people.bob;
|
||||
eq(awg.allowed_ips(m, srv, bob), [ '0.0.0.0/0', '::/0' ], 'no device: everything');
|
||||
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: false }), [ '0.0.0.0/0', '::/0' ], 'as before');
|
||||
let dns = (list) => [ ...slice(list, 0, 2), '10.9.0.1/32', ...slice(list, 2) ];
|
||||
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'internet: the rest, and its DNS');
|
||||
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...slice(awg.BYPASS4, 0, 2), '10.9.0.0/29', ...slice(awg.BYPASS4, 2), ...awg.BYPASS6 ],
|
||||
'home too: the tunnel network with the other devices (the DNS is in it)');
|
||||
srv.mesh = 'off';
|
||||
srv.device_mesh = false;
|
||||
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'no mesh: the router');
|
||||
srv.dns = [ '192.168.1.1', '192.168.1.53', 'fd00::53', '2001:4860:4860::8888', 'fe80::1' ];
|
||||
let all = awg.allowed_ips(m, srv, bob, { lan_bypass: true });
|
||||
ok(index(all, '192.168.1.1/32') >= 0 && index(all, '192.168.1.53/32') >= 0, 'every private IPv4 DNS server stays in the tunnel, not only the first');
|
||||
eq(slice(all, length(all) - length(awg.BYPASS6) - 2), [ ...awg.BYPASS6, 'fd00::53/128', 'fe80::1/128' ],
|
||||
'a private IPv6 one too; a public IPv6 one is in the rest already');
|
||||
eq(length(all), length(awg.BYPASS4) + 2 + length(awg.BYPASS6) + 2, 'nothing else');
|
||||
srv.dns = [ '1.1.1.1' ];
|
||||
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'a public DNS is in the rest already');
|
||||
alice.access = 'lan';
|
||||
alice.dns_mode = 'home';
|
||||
let lan = awg.allowed_ips(m, srv, alice, { lan_bypass: true });
|
||||
eq(lan, awg.allowed_ips(m, srv, alice), 'Home only: the same either way');
|
||||
let c = awg.client_config(m, { ...m.devices.alice_phone, person: 'bob', lan_bypass: true });
|
||||
eq(c.amnezia.allowed_ips, [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'in the AmneziaVPN key');
|
||||
ok(index(c.conf, `AllowedIPs = ${join(', ', [ ...awg.BYPASS4, ...awg.BYPASS6 ])}\n`) >= 0, 'in the .conf');
|
||||
});
|
||||
|
||||
test('keepalive_range and idle_handshake', () => {
|
||||
let srv = { keepalive: 25, obf: {} };
|
||||
eq(awg.keepalive_range(srv, {}), [ 25, 25 ], 'the server\'s, no range');
|
||||
eq(awg.keepalive_range(srv, { keepalive: 120 }), [ 120, 120 ], 'the device\'s own');
|
||||
eq(awg.keepalive_range(srv, { keepalive: 0 }), null, 'off for the device');
|
||||
eq(awg.keepalive_range({ keepalive: 0, obf: {} }, {}), null, 'off on the server');
|
||||
let max = { keepalive: 25, obf: awg.obf_preset('max') };
|
||||
eq(awg.keepalive_range(max, {}), [ 25, 35 ], 'jittered with 3.1');
|
||||
eq(awg.keepalive_range(max, { keepalive: 60 }), [ 60, 70 ], 'the device\'s own, jittered');
|
||||
// The first keep-alive after the rekey time (120 s; RekeyAfterTime's upper end) starts a handshake.
|
||||
eq(awg.idle_handshake(srv, {}), 145, 'within the rekey time: up to one keep-alive past it');
|
||||
eq(awg.idle_handshake(max, {}), 155, 'Maximum: RekeyAfterTime 100-120, keep-alive up to 35');
|
||||
eq(awg.idle_handshake(srv, { keepalive: 100 }), 220, 'every second keep-alive');
|
||||
eq(awg.idle_handshake(srv, { keepalive: 300 }), 300, 'every keep-alive once they are further apart');
|
||||
eq(awg.idle_handshake({ keepalive: 25, obf: { rekey_after_time: '200-400' } }, {}), 205, 'past 180 s the key is refused anyway');
|
||||
eq(awg.idle_handshake(srv, { keepalive: 0 }), null, 'no keep-alive: none');
|
||||
});
|
||||
|
||||
test('client_config: the device\'s own MTU and keep-alive', () => {
|
||||
let m = core.load();
|
||||
let dev = m.devices.alice_phone;
|
||||
let line = (c, k) => match(c.conf, regexp(`\n${k} = ([^\n]*)\n`))?.[1];
|
||||
let c = awg.client_config(m, dev);
|
||||
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu ], [ '1280', '25', '1280' ], 'the server\'s (a phone)');
|
||||
let fp = awg.config_fingerprint(m, dev);
|
||||
let old = { ...dev };
|
||||
delete old.mtu;
|
||||
delete old.keepalive;
|
||||
delete old.lan_bypass;
|
||||
eq(awg.config_fingerprint(m, old), fp, 'a device without values of its own keeps its fingerprint (as before the options)');
|
||||
dev.mtu = 1420;
|
||||
dev.keepalive = 0;
|
||||
c = awg.client_config(m, dev);
|
||||
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu, c.amnezia.persistent_keep_alive ], [ '1420', null, '1420', '0' ],
|
||||
'its own; keep-alive off');
|
||||
ok(awg.config_fingerprint(m, dev) != fp, 'a change asks it to import again');
|
||||
m.servers.main.obf = awg.obf_preset('max');
|
||||
dev.keepalive = 120;
|
||||
c = awg.client_config(m, dev);
|
||||
eq([ line(c, 'PersistentKeepalive'), c.amnezia.persistent_keep_alive ], [ '120-130', '120-130' ], 'jittered with 3.1');
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
// dawnline.awg_builds: the AmneziaWG generation of package and kernel module
|
||||
// versions, whether an installed update waits for a reboot (its old module
|
||||
// stayed loaded) and the generation that really runs meanwhile, which is
|
||||
// what caps() reports.
|
||||
import * as builds from 'dawnline.awg_builds';
|
||||
import * as awg from 'dawnline.awg';
|
||||
|
||||
// The live router's module (3.1) after an update from a 2.0 one that could not be swapped.
|
||||
const KMOD_31 = '6.12.94.3.1.20260906-r1';
|
||||
const WAITING = { reloaded: false, boot: 'boot-1', prev_gen: '2.0', prev_core: 98304 };
|
||||
|
||||
test('gen of package versions', () => {
|
||||
eq(builds.gen(null), null, 'not installed');
|
||||
eq(builds.gen('3.1.20260812-r1'), '3.1', 'amneziawg-tools 3.1');
|
||||
eq(builds.gen('3.1.0-r1'), '3.1', 'luci-proto-amneziawg 3.1');
|
||||
eq(builds.gen('1.0.20250722-r1'), '2.0', 'July 2025 on: 2.0');
|
||||
eq(builds.gen('1.0.20250901'), '2.0', 'no release suffix');
|
||||
eq(builds.gen('1.0.20250610-r1'), '1.0', 'before July 2025');
|
||||
eq(builds.gen('1.0.20241112-r2'), '1.0', '2024');
|
||||
});
|
||||
|
||||
test('gen of kernel module versions', () => {
|
||||
eq(builds.gen(KMOD_31), '3.1', 'kernel release in front');
|
||||
eq(builds.gen('6.12.94.3.1.20260906'), '3.1', 'no release suffix');
|
||||
eq(builds.gen('6.6.73.1.0.20250722-r1'), '2.0', '2.0 module');
|
||||
eq(builds.gen('6.6.73.1.0.20250612-r1'), '1.0', 'first generation module');
|
||||
eq(builds.gen('5.15.150.1.0.20240711-r3'), '1.0', '2024 module on an older kernel');
|
||||
eq(builds.gen('3.1.20260812'), '3.1', 'the version.h string of a 3.1 module');
|
||||
});
|
||||
|
||||
test('pending: an update waits for a reboot', () => {
|
||||
ok(builds.pending(WAITING, 'boot-1', 98304), 'the old module still loaded, same boot');
|
||||
ok(!builds.pending(WAITING, 'boot-2', 98304), 'rebooted');
|
||||
ok(!builds.pending(WAITING, 'boot-1', null), 'no module loaded: the next one is the new one');
|
||||
ok(!builds.pending(WAITING, 'boot-1', 110592), 'another module loaded (reloaded by hand)');
|
||||
ok(!builds.pending({ ...WAITING, reloaded: true }, 'boot-1', 98304), 'the install swapped it');
|
||||
ok(!builds.pending({ ...WAITING, reloaded: null }, 'boot-1', 98304), 'a record of a module Dawnline did not install');
|
||||
ok(!builds.pending({ osrelease: '6.12.94', source: 'slava', tag: 'v25.12.5', installed: 1 }, 'boot-1', 98304),
|
||||
'a record from before boots were kept');
|
||||
ok(!builds.pending({ ...WAITING, boot: null }, null, 98304), 'the kernel gave no boot id');
|
||||
ok(!builds.pending(null, 'boot-1', 98304), 'no record');
|
||||
});
|
||||
|
||||
test('caps: the generation that runs while a reboot is pending', () => {
|
||||
eq(builds.running_gen(WAITING, 'boot-1', 98304, KMOD_31), '2.0', 'the 2.0 module runs, not the 3.1 package');
|
||||
eq(builds.running_gen(WAITING, 'boot-2', 98304, KMOD_31), '3.1', 'after the reboot: the package');
|
||||
eq(builds.running_gen(WAITING, 'boot-1', null, KMOD_31), '3.1', 'nothing loaded: the package loads');
|
||||
eq(builds.running_gen(null, 'boot-1', 98304, KMOD_31), '3.1', 'no record: the package');
|
||||
eq(builds.running_gen({ ...WAITING, prev_gen: null }, 'boot-1', 98304, KMOD_31), null,
|
||||
'a module installed by hand before: unknown, the tools are believed');
|
||||
eq(builds.running_gen(null, null, null, null), null, 'nothing installed');
|
||||
});
|
||||
|
||||
test('caps in a container without AmneziaWG', () => {
|
||||
let c = awg.caps();
|
||||
eq(c.kmod, null, 'no module package');
|
||||
eq(c.pending, false, 'nothing waits for a reboot');
|
||||
eq(builds.module_core(), null, 'no module loaded');
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
// 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.
|
||||
// allocation, the automatic MTU, a device's own MTU, keep-alive and local
|
||||
// network, and other packages' port forwards.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import * as core from 'dawnline.core';
|
||||
|
||||
// A local time that no time zone turns into another day.
|
||||
@@ -27,6 +29,8 @@ test('load reads the fixture', () => {
|
||||
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');
|
||||
let d = m.devices.alice_phone;
|
||||
eq([ d.mtu, d.keepalive, d.lan_bypass ], [ 0, null, false ], 'a device without link values of its own');
|
||||
});
|
||||
|
||||
test('parse_hours', () => {
|
||||
@@ -128,6 +132,82 @@ test('tunnel_mtu / device_mtu', () => {
|
||||
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');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 1420 }), 1420, 'the device\'s own, also above 1280 on a phone');
|
||||
eq(core.device_mtu({ mtu: 1420 }, { kind: 'computer', mtu: 1280 }), 1280, 'the device\'s own below the tunnel\'s');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer', mtu: 9000 }), 1380, 'out of range (a hand edit): the automatic one');
|
||||
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 0 }), 1280, '0: as before');
|
||||
});
|
||||
|
||||
test('device_keepalive', () => {
|
||||
let srv = { keepalive: 25 };
|
||||
eq(core.device_keepalive(srv, { keepalive: null }), 25, 'the server\'s');
|
||||
eq(core.device_keepalive(srv, {}), 25, 'none read');
|
||||
eq(core.device_keepalive(srv, { keepalive: 0 }), 0, 'off for this device');
|
||||
eq(core.device_keepalive(srv, { keepalive: 120 }), 120, 'its own');
|
||||
eq(core.device_keepalive(srv, { keepalive: 700 }), 25, 'out of range: the server\'s');
|
||||
eq(core.device_keepalive({ keepalive: 0 }, { keepalive: 15 }), 15, 'its own on a server without keep-alive');
|
||||
});
|
||||
|
||||
/** A uci cursor that records what is written: { 'section.option': value or null (deleted) }. */
|
||||
function recorder() {
|
||||
let w = {};
|
||||
return { w, c: { set: (cfg, s, k, v) => { w[`${s}.${k}`] = v; }, delete: (cfg, s, k) => { w[`${s}.${k}`] = null; } } };
|
||||
}
|
||||
|
||||
test('set_device_link', () => {
|
||||
let mm = { devices: { d: { id: 'd', mtu: 0, keepalive: null, lan_bypass: false } } };
|
||||
let r = recorder();
|
||||
eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: '0', lan_bypass: true }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'what changed');
|
||||
eq(r.w, { 'd.mtu': '1400', 'd.keepalive': '0', 'd.lan_bypass': '1' }, 'written');
|
||||
r = recorder();
|
||||
mm.devices.d = { id: 'd', mtu: 1400, keepalive: 0, lan_bypass: true };
|
||||
eq(core.set_device_link(r.c, mm, 'd', { mtu: '', keepalive: '', lan_bypass: false }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'back');
|
||||
eq(r.w, { 'd.mtu': null, 'd.keepalive': null, 'd.lan_bypass': null }, 'removed: the server\'s again');
|
||||
r = recorder();
|
||||
eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: ' 0 ' }), [], 'the same values change nothing');
|
||||
eq(r.w, {}, 'nothing written');
|
||||
eq(core.set_device_link(r.c, mm, 'd', {}), [], 'nothing asked');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1279' }), /^MTU must be 1280-1500\.$/, 'MTU too small');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1501' }), /^MTU must be 1280-1500\.$/, 'MTU too large');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1400.5' }), /^MTU/, 'not a whole number');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '601' }), /^Keep-alive must be 0-600 seconds\.$/, 'keep-alive too long');
|
||||
throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '-1' }), /^Keep-alive/, 'negative');
|
||||
throws(() => core.set_device_link(r.c, mm, 'x', { mtu: '' }), /^Unknown device\.$/, 'unknown device');
|
||||
});
|
||||
|
||||
test('create_device: the local network outside the tunnel', () => {
|
||||
let mm = core.load();
|
||||
let r = recorder();
|
||||
let keys = { public_key: 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', preshared_key: '' };
|
||||
let id = core.create_device(r.c, mm, 'bob', 'Laptop', 'computer', { keys, lan_bypass: true });
|
||||
eq([ r.w[`${id}.lan_bypass`], mm.devices[id].lan_bypass, mm.devices[id].mtu, mm.devices[id].keepalive ], [ '1', true, 0, null ], 'set');
|
||||
r = recorder();
|
||||
id = core.create_device(r.c, mm, 'bob', 'Tablet', 'tablet', { keys: { ...keys, public_key: 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=' } });
|
||||
ok(!(`${id}.lan_bypass` in r.w) && !mm.devices[id].lan_bypass, 'off unless asked');
|
||||
});
|
||||
|
||||
test('create_device: not with the server\'s own key', () => {
|
||||
let mm = core.load();
|
||||
let keys = { public_key: mm.servers.main.public_key, preshared_key: '' };
|
||||
throws(() => core.create_device(recorder().c, mm, 'bob', 'Laptop', 'computer', { keys }), /^This key is already in use\.$/,
|
||||
'it is in every configuration of the server');
|
||||
mm.devices.alice_phone.public_key = mm.servers.main.public_key;
|
||||
eq(core.model_errors(mm), [ "Device Phone of Alice: the public key is the server's own." ], 'one set by hand is named');
|
||||
});
|
||||
|
||||
test('model_errors: a device\'s own MTU and keep-alive', () => {
|
||||
let mm = core.load();
|
||||
eq(core.model_errors(mm), [], 'the fixture is consistent');
|
||||
let d = mm.devices.alice_phone;
|
||||
d.mtu = 1400;
|
||||
d.keepalive = 0;
|
||||
eq(core.model_errors(mm), [], 'values of its own in range');
|
||||
d.mtu = 9000;
|
||||
d.keepalive = 601;
|
||||
eq(core.model_errors(mm), [
|
||||
'Device Phone of Alice: MTU 9000 is not between 1280 and 1500.',
|
||||
'Device Phone of Alice: keep-alive 601 is not between 0 and 600 seconds.',
|
||||
], 'named');
|
||||
});
|
||||
|
||||
test('names and codes', () => {
|
||||
@@ -164,3 +244,29 @@ test('device_labels', () => {
|
||||
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
|
||||
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
|
||||
});
|
||||
|
||||
test('wan_forwards leaves out Dawnline\'s own, without a regex', () => {
|
||||
// A firewall config for this case only (the container's own is put back).
|
||||
let path = '/etc/config/firewall', saved = readfile(path);
|
||||
let names = [ 'dawnline_portal', 'dawnline_', 'dawnline', 'Dawnline_x', 'xdawnline_y', 'dawnlinex_1', 'web' ];
|
||||
let conf = '';
|
||||
for (let i = 0; i < length(names); i++)
|
||||
conf += sprintf("config redirect '%s'\n\toption src 'wan'\n\toption proto 'udp'\n\toption src_dport '%d'\n\n", names[i], 6000 + i);
|
||||
writefile(path, conf);
|
||||
let got = null, err = null;
|
||||
try {
|
||||
got = core.wan_forwards('wan', 'udp');
|
||||
}
|
||||
catch (e) {
|
||||
err = e;
|
||||
}
|
||||
if (saved != null)
|
||||
writefile(path, saved);
|
||||
else
|
||||
unlink(path);
|
||||
if (err)
|
||||
die(err.message);
|
||||
// The names the pattern it stands for let through.
|
||||
eq(map(got, (f) => f.name), filter(names, (n) => !match(n, /^dawnline_/)), 'names');
|
||||
eq(got[0], { from: 6002, to: 6002, name: 'dawnline' }, 'a forward');
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// The admin's device methods (dawnline.rpc.people over dawnline.devices): what
|
||||
// counts as handing a configuration out, and New keys as setting the device up
|
||||
// again. The real calls on the fixture: the stand-in awg makes the keys, the
|
||||
// sync's nft and awg steps fail harmlessly in the container. /etc/config/dawnline
|
||||
// and the issued and reconnect marks are put back after.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import { DATA_DIR, ensure_dir } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as people from 'dawnline.rpc.people';
|
||||
|
||||
const CONFIG = '/etc/config/dawnline';
|
||||
const ISSUED = `${DATA_DIR}/issued.json`;
|
||||
const RECONNECT = `${DATA_DIR}/reconnect.json`;
|
||||
|
||||
// fn(), then the files as they were, whatever fn did.
|
||||
function kept(paths, fn) {
|
||||
let had = map(paths, (p) => readfile(p));
|
||||
let err = null;
|
||||
try {
|
||||
fn();
|
||||
}
|
||||
catch (e) {
|
||||
err = e;
|
||||
}
|
||||
for (let i = 0; i < length(paths); i++)
|
||||
had[i] == null ? unlink(paths[i]) : writefile(paths[i], had[i]);
|
||||
if (err)
|
||||
die(err.message ?? `${err}`);
|
||||
}
|
||||
|
||||
function call(name, args) {
|
||||
return people.methods[name].call({ args });
|
||||
}
|
||||
|
||||
test('device_config: a look marks nothing, a delivery does', () => {
|
||||
ensure_dir(DATA_DIR, 0o700);
|
||||
kept([ ISSUED ], () => {
|
||||
let old = sprintf('%J', { alice_phone: '00000000' });
|
||||
writefile(ISSUED, old);
|
||||
ok(index(call('device_config', { id: 'alice_phone' }).conf ?? '', '[Peer]') >= 0, 'the configuration comes back');
|
||||
eq(readfile(ISSUED), old, 'without issue: issued.json left alone');
|
||||
call('device_config', { id: 'alice_phone', issue: false });
|
||||
eq(readfile(ISSUED), old, 'issue false: the same');
|
||||
call('device_config', { id: 'alice_phone', issue: true });
|
||||
let m = core.load();
|
||||
eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'issue: what it holds now counts as handed out');
|
||||
eq(call('device_config', { id: 'nobody', issue: true }).error, 'Unknown device.', 'an unknown device');
|
||||
});
|
||||
});
|
||||
|
||||
test('device_rotate: New keys set the device up again', () => {
|
||||
kept([ CONFIG, ISSUED, RECONNECT ], () => {
|
||||
unlink(RECONNECT);
|
||||
let before = core.load().devices.alice_phone;
|
||||
let t0 = time();
|
||||
let c = call('device_rotate', { id: 'alice_phone' });
|
||||
ok(c.error == null && index(c.conf ?? '', '[Peer]') >= 0, `the new configuration comes back (${c.error})`);
|
||||
let m = core.load();
|
||||
ok(m.devices.alice_phone.preshared_key != before.preshared_key, 'new keys');
|
||||
let at = awg.reconnects().alice_phone;
|
||||
ok(at >= t0 && at <= time(), `a reconnect mark at the rotation (${at})`);
|
||||
eq(awg.handshake_since(t0 - 30, at), 0, "the old keys' last handshake no longer counts: Not set up yet, with Connect");
|
||||
eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'its new configuration is the one handed out');
|
||||
});
|
||||
eq(core.load().devices.alice_phone.private_key, '', 'the fixture is back');
|
||||
});
|
||||
@@ -1,10 +1,29 @@
|
||||
#!/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.
|
||||
# container): `genkey` prints one fixed key, `pubkey` (a key on stdin) the
|
||||
# fixture server's public key, its pair; `show <ifname> dump` prints that
|
||||
# interface's lines of the fixture a test has put at /tmp/dawnline-tests/awg-dump
|
||||
# (written as `awg show all dump` prints them: the ifname first, left out here,
|
||||
# as the tool does), fails as the tool does for an interface that is not there,
|
||||
# and fails with the text of /tmp/dawnline-tests/awg-fail-<ifname> when a test
|
||||
# put one. Every call is appended to /tmp/dawnline-tests/awg-calls. Anything
|
||||
# else fails.
|
||||
T=/tmp/dawnline-tests
|
||||
echo "$*" >> "$T/awg-calls"
|
||||
case "$1 ${2:-} ${3:-}" in
|
||||
'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;;
|
||||
'show all dump') cat /tmp/dawnline-tests/awg-dump ;;
|
||||
'pubkey ') cat >/dev/null; echo 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=' ;;
|
||||
'show '*' dump')
|
||||
if [ -e "$T/awg-fail-$2" ]; then
|
||||
cat "$T/awg-fail-$2" >&2
|
||||
exit 1
|
||||
fi
|
||||
out="$(awk -F '\t' -v i="$2" '$1 == i { sub(/^[^\t]*\t/, ""); print }' "$T/awg-dump" 2>/dev/null)"
|
||||
if [ -z "$out" ]; then
|
||||
echo 'Unable to access interface: No such device' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$out"
|
||||
;;
|
||||
*) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;;
|
||||
esac
|
||||
@@ -41,4 +41,4 @@ config device 'alice_phone'
|
||||
option name 'Phone'
|
||||
option kind 'phone'
|
||||
option address '10.9.0.2'
|
||||
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
|
||||
option public_key 'AuTb2wZ8C1032Ksn76nFgXzOJgT86OgEVbEE7ClpNy8='
|
||||
@@ -0,0 +1,57 @@
|
||||
table inet dawnline {
|
||||
set home_home { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } }
|
||||
set home_work { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } }
|
||||
set tun_nets { type ipv4_addr; flags interval; auto-merge; elements = { 10.9.0.0/29, 10.9.1.0/29 } }
|
||||
set lan_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } }
|
||||
set lan_all { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } }
|
||||
set lan_part { type ipv4_addr . ipv4_addr; flags interval; }
|
||||
set mesh_pairs { type ipv4_addr . ipv4_addr; }
|
||||
set inet_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.1.2, 10.9.0.4, 10.9.0.5, 10.9.1.3 } }
|
||||
set svc_ok { type ipv4_addr . ipv4_addr . inet_service; }
|
||||
set svc_host { type ipv4_addr . ipv4_addr; }
|
||||
set dns_real { type ipv4_addr; elements = { 10.9.0.3 } }
|
||||
chain pre {
|
||||
type filter hook prerouting priority -160; policy accept;
|
||||
iifname { "awghome", "awgwork" } jump guard
|
||||
}
|
||||
chain guard {
|
||||
meta nfproto ipv6 drop
|
||||
ct state related accept
|
||||
ct status dnat accept
|
||||
icmp type { echo-request, echo-reply } fib daddr type local accept
|
||||
fib daddr type local meta l4proto { tcp, udp } th dport 53 accept
|
||||
fib daddr type local tcp dport { 8443 } accept
|
||||
fib daddr type local ip saddr @lan_all accept
|
||||
fib daddr type local ip saddr . ip daddr @lan_part accept
|
||||
fib daddr type local counter drop
|
||||
ip daddr 192.168.1.250 meta l4proto { tcp, udp } th dport 53 accept
|
||||
iifname "awghome" ip daddr @home_home ip daddr != @tun_nets ip saddr @lan_all accept
|
||||
iifname "awgwork" ip daddr @home_work ip daddr != @tun_nets ip saddr @lan_all accept
|
||||
ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept
|
||||
iifname "awghome" ip saddr @lan_ok ip daddr @lan_ok accept
|
||||
iifname "awgwork" ip saddr . ip daddr @mesh_pairs accept
|
||||
meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept
|
||||
ip saddr . ip daddr @svc_host accept
|
||||
ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 169.254.0.0/16, 224.0.0.0/3 } counter drop
|
||||
ip saddr @inet_ok accept
|
||||
counter drop
|
||||
}
|
||||
chain inbound {
|
||||
type filter hook forward priority filter - 5; policy accept;
|
||||
oifname { "awghome", "awgwork" } iifname != { "awghome", "awgwork" } ct state new jump to_device
|
||||
}
|
||||
chain to_device {
|
||||
meta nfproto ipv6 drop
|
||||
ct status dnat accept
|
||||
oifname "awghome" ip saddr @home_home ip saddr != @tun_nets ip daddr @lan_all accept
|
||||
oifname "awgwork" ip saddr @home_work ip saddr != @tun_nets ip daddr @lan_all accept
|
||||
ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept
|
||||
counter reject with icmpx admin-prohibited
|
||||
}
|
||||
chain dns {
|
||||
type nat hook prerouting priority dstnat - 5; policy accept;
|
||||
iifname { "awghome", "awgwork" } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 dnat ip to 169.254.77.2:53
|
||||
iifname "awghome" ip daddr 10.9.0.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.250:53
|
||||
iifname "awgwork" ip daddr 10.9.1.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.1:53
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// dawnline.health: where a public address points, in words. The name's AAAA
|
||||
// records are checked against the router's public IPv6 addresses as well as
|
||||
// its A records against the WAN. The facts take a test's reads instead of
|
||||
// DNS, the WAN and `ip`.
|
||||
import * as health from 'dawnline.health';
|
||||
|
||||
const HOST = 'vpn.example.com';
|
||||
const WAN = '203.0.113.7';
|
||||
// The WAN's own address and the LAN's from the delegated prefix: both reach the router.
|
||||
const ROUTER6 = [ '2001:db8:1::1', '2001:db8:2::1' ];
|
||||
|
||||
function facts(ips, router6, wan) {
|
||||
return health.endpoint_facts(null, HOST, { ips, wan, router6 });
|
||||
}
|
||||
|
||||
function words(ips, router6, wan) {
|
||||
return health.endpoint_words(facts(ips, router6, wan), 'UDP 51820');
|
||||
}
|
||||
|
||||
test('own_ipv6: public addresses on any interface', () => {
|
||||
let links = [
|
||||
{ ifname: 'wan', addr_info: [ { family: 'inet6', local: '2001:db8:1::1', prefixlen: 128, scope: 'global' } ] },
|
||||
{ ifname: 'br-lan', addr_info: [
|
||||
{ family: 'inet6', local: '2001:db8:2::1', prefixlen: 64, scope: 'global' },
|
||||
{ family: 'inet6', local: 'fd12:3456:789a::1', prefixlen: 60, scope: 'global' },
|
||||
{ family: 'inet6', local: '2001:db8:2::99', prefixlen: 64, scope: 'global', dadfailed: true },
|
||||
] },
|
||||
{ ifname: 'lan2', addr_info: [ { family: 'inet6', local: 'FC00::1', prefixlen: 64, scope: 'global' } ] },
|
||||
{ ifname: 'lo' },
|
||||
];
|
||||
eq(health.own_ipv6(links), ROUTER6, 'the WAN and the LAN prefix; no ULA, no failed duplicate');
|
||||
eq(health.own_ipv6([ links[1] ]), [ '2001:db8:2::1' ], 'only the LAN has one');
|
||||
eq(health.own_ipv6([ { ifname: 'br-lan', addr_info: [ links[1].addr_info[1] ] } ]), [], 'only a ULA: none');
|
||||
eq(health.own_ipv6(null), [], 'nothing read');
|
||||
});
|
||||
|
||||
test('endpoint_facts: AAAA records against the router', () => {
|
||||
let f = facts([ WAN, '2001:db8:2::1' ], ROUTER6, WAN);
|
||||
eq([ f.here, f.here6, f.foreign6 ], [ true, true, [] ], 'both records are the router');
|
||||
eq(facts([ WAN, '2001:DB8:2:0:0::1' ], ROUTER6, WAN).here6, true, 'another spelling of the same address');
|
||||
f = facts([ WAN, '2001:db8:2::1', '2001:db8:9::5' ], ROUTER6, WAN);
|
||||
eq([ f.here6, f.foreign6 ], [ false, [ '2001:db8:9::5' ] ], 'one of two is not');
|
||||
f = facts([ WAN, '2001:db8:9::5' ], [], WAN);
|
||||
eq([ f.here6, f.foreign6, f.router6 ], [ false, [ '2001:db8:9::5' ], [] ], 'the router has no IPv6: none is');
|
||||
f = facts([ WAN, '2001:db8:9::5' ], null, WAN);
|
||||
eq([ f.here6, f.foreign6, f.router6 ], [ false, null, null ], 'unknown: no verdict');
|
||||
eq(facts([ WAN ], ROUTER6, WAN).here6, false, 'no AAAA');
|
||||
});
|
||||
|
||||
test('endpoint_words: IPv4 and IPv6 both at the router', () => {
|
||||
eq(words([ WAN, '2001:db8:2::1' ], ROUTER6, WAN),
|
||||
{ status: 'ok', text: 'vpn.example.com points at this router (203.0.113.7, 2001:db8:2::1).' }, 'A and AAAA');
|
||||
eq(words([ WAN ], null, WAN), { status: 'ok', text: 'vpn.example.com points at this router (203.0.113.7).' }, 'A only, as before');
|
||||
eq(words([ WAN, '2001:db8:9::5' ], null, WAN).status, 'ok', 'the router\'s IPv6 unknown: the AAAA gets no verdict');
|
||||
});
|
||||
|
||||
test('endpoint_words: an AAAA record that is not the router', () => {
|
||||
eq(words([ WAN, '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: 'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.' },
|
||||
'a stale prefix');
|
||||
eq(words([ WAN, '2001:db8:9::5', '2001:db8:9::6' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com AAAA → 2001:db8:9::5, 2001:db8:9::6 are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.',
|
||||
'two of them');
|
||||
eq(words([ WAN, '2001:db8:2::1', 'fd12:3456:789a::1' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com AAAA → fd12:3456:789a::1 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'a ULA beside the right one');
|
||||
eq(words([ WAN, '2001:db8:9::5' ], [], WAN), { status: 'warn',
|
||||
text: 'vpn.example.com AAAA → 2001:db8:9::5, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.' },
|
||||
'the router has no IPv6');
|
||||
eq(words([ '198.51.100.4', '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: 'vpn.example.com points at 198.51.100.4, not this router (WAN 203.0.113.7). Check your DNS / DDNS. ' +
|
||||
'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.' },
|
||||
'both wrong: two sentences, IPv4 first');
|
||||
eq(words([ '198.51.100.4', '2001:db8:2::1' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com points at 198.51.100.4, not this router (WAN 203.0.113.7). Check your DNS / DDNS.', 'only the A record wrong: as before');
|
||||
eq(words([ '198.51.100.4', '2001:db8:9::5' ], ROUTER6, null).text,
|
||||
'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'no WAN address: the AAAA alone');
|
||||
});
|
||||
|
||||
test('endpoint_words: IPv6 only', () => {
|
||||
eq(words([ '2001:db8:2::1' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: "vpn.example.com → 2001:db8:2::1: IPv6 only, so only devices with IPv6 connect (the router's IPv4 203.0.113.7 has no name)." },
|
||||
'the v6_only wording stays');
|
||||
eq(words([ '2001:db8:2::1' ], ROUTER6, '100.64.1.2'),
|
||||
{ status: 'ok', text: 'vpn.example.com → 2001:db8:2::1: IPv6 only, so only devices with IPv6 connect.' }, 'behind CGNAT, as before');
|
||||
eq(words([ '2001:db8:9::5' ], ROUTER6, WAN), { status: 'warn',
|
||||
text: 'vpn.example.com → 2001:db8:9::5: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.' },
|
||||
'not the router');
|
||||
eq(words([ '2001:db8:9::5', '2001:db8:9::6' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com → 2001:db8:9::5, 2001:db8:9::6: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.',
|
||||
'two, neither the router');
|
||||
eq(words([ '2001:db8:9::5' ], [], '100.64.1.2'), { status: 'warn',
|
||||
text: 'vpn.example.com → 2001:db8:9::5: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.' },
|
||||
'the router has no IPv6');
|
||||
eq(words([ '2001:db8:2::1', '2001:db8:9::5' ], ROUTER6, WAN).text,
|
||||
'vpn.example.com AAAA → 2001:db8:9::5 is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
|
||||
'one right, one wrong');
|
||||
eq(words([ '2001:db8:9::5' ], null, WAN).text,
|
||||
"vpn.example.com → 2001:db8:9::5: IPv6 only, so only devices with IPv6 connect (the router's IPv4 203.0.113.7 has no name).",
|
||||
'the router\'s IPv6 unknown: as before');
|
||||
});
|
||||
|
||||
test('common home subnets', () => {
|
||||
eq(health.common_home([ '192.168.1.0/24', '10.0.1.0/24' ]), [ '192.168.1.0/24' ], 'the out-of-the-box /24 only');
|
||||
eq(health.common_home([ '192.168.0.0/16' ]), [ '192.168.0.0/16' ], 'a wider network that holds one');
|
||||
eq(health.common_home([ '10.37.12.0/24', '172.20.0.0/24' ]), [], 'rare ones');
|
||||
eq(health.common_home(null), [], 'none');
|
||||
});
|
||||
@@ -0,0 +1,332 @@
|
||||
// dawnline.link: what a device's counters say about its link, on synthetic
|
||||
// sequences of one read a second, run the way the agent's watcher runs them
|
||||
// (observe, the set-up state at once, then classify and settle when
|
||||
// something happened or CHECK_EVERY passed); and the pieces on their own.
|
||||
import * as link from 'dawnline.link';
|
||||
|
||||
const T0 = 1800000000;
|
||||
const A = '203.0.113.7:41821', B = '198.51.100.4:50123';
|
||||
|
||||
/*
|
||||
* `seconds` reads from T0. `at(s)` gives what happened in second s: { drx,
|
||||
* dtx (bytes in, out), hs (a handshake completed), ep (the endpoint now),
|
||||
* gone (the peer is not in the tunnel) }. Returns the history, the changes
|
||||
* of what is shown: [ { s, from, to, since (seconds from T0), ev } ], those of
|
||||
* the set-up state: [ { s, state } ], and the seconds where the set-up state
|
||||
* kept by setup() was not what setup_state() gives then (it should never be).
|
||||
*/
|
||||
function run(seconds, at, opts) {
|
||||
opts ??= {};
|
||||
let ka = opts.ka ?? link.KEEPALIVE, window = opts.window ?? 190;
|
||||
let h = link.fresh(T0);
|
||||
let peer = { endpoint: opts.ep ?? A, handshake: opts.hs0 ?? 0, rx: 1000, tx: 1000 };
|
||||
let changes = [], raws = {}, setups = [], lag = [];
|
||||
for (let s = 0; s < seconds; s++) {
|
||||
let t = T0 + s, x = at(s) ?? {};
|
||||
peer.rx += x.drx ?? 0;
|
||||
peer.tx += x.dtx ?? 0;
|
||||
if (x.hs)
|
||||
peer.handshake = t;
|
||||
if (x.ep)
|
||||
peer.endpoint = x.ep;
|
||||
let on = peer.handshake > 0 && t - peer.handshake < window;
|
||||
let moved = false;
|
||||
if (x.gone)
|
||||
link.gone(h);
|
||||
else
|
||||
moved = link.observe(h, peer, t, ka);
|
||||
if (link.setup(h, t, on, moved))
|
||||
push(setups, { s, state: h.setup?.state ?? null });
|
||||
if (link.setup_state(h, t, on).state != (h.setup?.state ?? null))
|
||||
push(lag, s);
|
||||
if (!moved && t - h.checked < link.CHECK_EVERY)
|
||||
continue;
|
||||
h.checked = t;
|
||||
link.prune(h, t);
|
||||
h.raw = link.classify(h, t, on);
|
||||
if (h.raw)
|
||||
raws[h.raw] ??= s;
|
||||
let ch = link.settle(h, h.raw, t, on);
|
||||
if (ch)
|
||||
push(changes, { s, from: ch.from, to: ch.to, since: h.since ? h.since - T0 : 0,
|
||||
ev: link.event_for(ch, { id: 'd_1', person: 'p_1' }, on)?.type ?? null });
|
||||
}
|
||||
return { h, changes, raws, setups, lag };
|
||||
}
|
||||
|
||||
// A phone in use: keep-alive 25 s, new keys every ~125 s (the initiation in
|
||||
// one second, the packet that confirms it in the next), something sent or
|
||||
// received now and then.
|
||||
function phone(s, busy) {
|
||||
let x = {};
|
||||
if (s % 125 == 3)
|
||||
x = { drx: 148, dtx: 92 };
|
||||
else if (s % 125 == 4)
|
||||
x = { hs: true, drx: 32 };
|
||||
else if (s % 25 == 0)
|
||||
x = { drx: 32 };
|
||||
if (busy && s % 30 < 4)
|
||||
x = { ...x, drx: (x.drx ?? 0) + 1400, dtx: (x.dtx ?? 0) + 9000 };
|
||||
return x;
|
||||
}
|
||||
|
||||
test('no state for a phone in use', () => {
|
||||
let r = run(1800, (s) => phone(s, true));
|
||||
eq(r.changes, [], 'half an hour of normal use');
|
||||
eq(r.raws, {}, 'not even for a moment');
|
||||
});
|
||||
|
||||
test('no state for a sleeping phone', () => {
|
||||
eq(run(1800, (s) => phone(s, false)).changes, [], 'keep-alives and new keys only');
|
||||
// Then it stops sending at all (deep sleep, out of range): it goes offline, nothing else.
|
||||
let r = run(1200, (s) => s < 300 ? phone(s, false) : {});
|
||||
eq(r.changes, [], 'silent after five minutes');
|
||||
eq(r.raws, {}, 'silence is no failure');
|
||||
// The same with the disguise's content padding: keep-alives of 42-132 bytes.
|
||||
eq(run(1800, (s) => s % 25 == 0 ? { drx: 42 + (s % 90) } : phone(s, false), { ka: 132 }).changes, [], 'padded keep-alives');
|
||||
});
|
||||
|
||||
test('no state for a phone that left with traffic still coming', () => {
|
||||
// Online and busy until 100 s, then gone; the internet keeps sending to it for a while.
|
||||
let at = (s) => s < 100 ? phone(s, true) : (s % 3 == 0 ? { dtx: 1400 } : {});
|
||||
eq(run(900, at).changes, [], 'the online window ends it');
|
||||
eq(run(900, at, { window: 400 }).changes, [], 'a long keep-alive window: no handshake within DROP_HS ends it');
|
||||
});
|
||||
|
||||
test('trying: knocks that never finish connecting', () => {
|
||||
// Never connected: an initiation every 5 s for 90 s, then a pause, again and again.
|
||||
let knocking = (s) => (s % 120 < 90 && s % 5 == 0) ? { drx: 148, dtx: 92 } : {};
|
||||
let r = run(600, knocking);
|
||||
// The first read is the baseline: the knocks count from 5 s.
|
||||
eq(r.raws.trying, 15, 'from the third accepted initiation');
|
||||
eq(r.changes[0], { s: 195, from: null, to: 'trying', since: 15, ev: 'device_failing' }, 'shown once it held 3 minutes');
|
||||
eq(length(r.changes), 1, 'and kept through the pauses');
|
||||
// It gets through at 400 s: working again at once.
|
||||
let r2 = run(600, (s) => s < 400 ? knocking(s) : (s == 400 ? { hs: true, drx: 148 + 1400, dtx: 4000 } : phone(s, true)));
|
||||
eq(r2.changes[1], { s: 400, from: 'trying', to: null, since: 0, ev: 'device_recovered' }, 'connected: recovered');
|
||||
// It gives up (the app was turned off): the state goes without a "recovered".
|
||||
let r3 = run(1200, (s) => s < 300 ? knocking(s) : {});
|
||||
eq(r3.changes[1].to, null, 'cleared');
|
||||
eq(r3.changes[1].ev, null, 'nobody saw it work');
|
||||
// The last knock at 295 s: it ages out of TRY_SPAN by 415 s, and HOLD passes by 595 s.
|
||||
eq(r3.changes[1].s, 595, 'only after the knocks aged out and HOLD passed');
|
||||
});
|
||||
|
||||
test('trying after a session that ran out', () => {
|
||||
// Online until 200 s; then its new keys never complete (the answers are lost).
|
||||
let at = (s) => s < 200 ? phone(s, true) : (s % 5 == 0 ? { drx: 148, dtx: 92 } : {});
|
||||
let r = run(900, at);
|
||||
eq(r.changes[0].to, 'trying', 'after the online window');
|
||||
ok(r.changes[0].s > 129 + 190, 'not while the old session still counted');
|
||||
});
|
||||
|
||||
test('shared: one configuration on two devices', () => {
|
||||
// Each takes the session from the other every 20 s; the endpoint flips with every packet.
|
||||
let r = run(600, (s) => ({ hs: s % 20 == 0, drx: 2000, dtx: 6000, ep: s % 2 ? B : A }));
|
||||
eq(r.raws.shared, 60, 'from the fourth handshake');
|
||||
eq(r.changes[0], { s: 240, from: null, to: 'shared', since: 60, ev: 'device_failing' }, 'shown once it held');
|
||||
eq(r.raws.unstable, null, 'never taken for a breaking connection');
|
||||
// Two devices behind one NAT: one address, two ports.
|
||||
let r2 = run(600, (s) => ({ hs: s % 20 == 0, drx: 2000, dtx: 6000, ep: s % 2 ? '203.0.113.7:1111' : '203.0.113.7:2222' }));
|
||||
eq(r2.changes[0]?.to, 'shared', 'told apart by port');
|
||||
});
|
||||
|
||||
test('unstable: connecting over and over from one place', () => {
|
||||
let r = run(600, (s) => ({ hs: s % 20 == 0, drx: s % 20 < 5 ? 3000 : 0, dtx: s % 20 < 5 ? 9000 : 0 }));
|
||||
eq(r.raws.unstable, 60, 'from the fourth quick handshake');
|
||||
eq(r.changes[0], { s: 240, from: null, to: 'unstable', since: 60, ev: 'device_failing' }, 'shown once it held');
|
||||
// Moving once (wifi to mobile) while it breaks is still the connection, not a second device.
|
||||
let r2 = run(600, (s) => ({ hs: s % 20 == 0, drx: 3000, dtx: 9000, ep: s < 100 ? A : B }));
|
||||
eq(r2.changes[0]?.to, 'unstable', 'one move is no alternation');
|
||||
// It settles down: working again once the quick handshakes left the span.
|
||||
let r3 = run(1200, (s) => s < 300 ? { hs: s % 20 == 0, drx: 3000, dtx: 9000 } : phone(s, true));
|
||||
eq(r3.changes[1]?.to, null, 'cleared');
|
||||
eq(r3.changes[1]?.ev, 'device_recovered', 'online: recovered');
|
||||
// Normal key renewals never churn, even at RekeyAfterTime's shortest (100 s).
|
||||
eq(run(1800, (s) => ({ hs: s % 100 == 0, drx: s % 25 == 0 ? 32 : 0 })).changes, [], '3.1 timers');
|
||||
});
|
||||
|
||||
/*
|
||||
* An old address after renumbering: every packet it sends is dropped after
|
||||
* decryption (not counted in rx), the router answers with a keepalive every
|
||||
* ~10 s, the device renews its keys every ~125 s (the first packet under them
|
||||
* is data, so only the initiation shows in rx).
|
||||
*/
|
||||
function renumbered(s) {
|
||||
if (s % 125 == 3)
|
||||
return { drx: 148, dtx: 92 };
|
||||
if (s % 125 == 4)
|
||||
return { hs: true };
|
||||
return s % 10 == 7 ? { dtx: 32 } : {};
|
||||
}
|
||||
|
||||
test('dropped: connected, but nothing it sends gets through', () => {
|
||||
let r = run(900, renumbered, { hs0: T0 - 30 });
|
||||
// Classified on the router's next answer after DROP_SPAN (187 s).
|
||||
eq(r.raws.dropped, 187, 'once DROP_SPAN passed without data');
|
||||
eq(r.changes[0], { s: 367, from: null, to: 'dropped', since: 187, ev: 'device_failing' }, 'shown once it held');
|
||||
// Imported again at 500 s: data flows, working at once.
|
||||
let r2 = run(900, (s) => s < 500 ? renumbered(s) : (s == 500 ? { hs: true, drx: 3000, dtx: 9000 } : phone(s, true)), { hs0: T0 - 30 });
|
||||
eq(r2.changes[1], { s: 500, from: 'dropped', to: null, since: 0, ev: 'device_recovered' }, 'recovered');
|
||||
// With the disguise's padding the router's answers are bigger; still under DROP_TX.
|
||||
let r3 = run(900, (s) => { let x = renumbered(s); if (x.dtx == 32) x.dtx = 32 + 1400; return x; }, { hs0: T0 - 30, ka: 132 });
|
||||
eq(r3.changes[0]?.to, 'dropped', 'padded answers');
|
||||
// Not before the history covers DROP_SPAN (the agent just started).
|
||||
eq(run(170, renumbered, { hs0: T0 - 30 }).raws, {}, 'too early to tell');
|
||||
});
|
||||
|
||||
test('counters that restart are a new baseline', () => {
|
||||
let h = link.fresh(T0);
|
||||
let peer = { endpoint: A, handshake: T0, rx: 50000, tx: 90000 };
|
||||
link.observe(h, peer, T0, 32);
|
||||
peer.rx = 148;
|
||||
peer.tx = 92;
|
||||
link.observe(h, peer, T0 + 1, 32);
|
||||
eq([ h.rx, h.tx, length(h.knocks), h.data ], [ 148, 92, 0, 0 ], 'the peer was added again: no knock, no data');
|
||||
link.gone(h);
|
||||
eq(h.rx, null, 'not in the tunnel');
|
||||
eq(link.observe(h, { ...peer, rx: 5000 }, T0 + 2, 32), false, 'back: a baseline, nothing counted');
|
||||
eq(h.data, 0, 'no data from the jump');
|
||||
});
|
||||
|
||||
test('knock and bare', () => {
|
||||
eq([ link.knock(148), link.knock(296), link.knock(444) ], [ true, true, true ], 'one to three initiations');
|
||||
eq([ link.knock(592), link.knock(180), link.knock(0) ], [ false, false, false ], 'too many, with something else, nothing');
|
||||
eq([ link.bare(32, 32, false), link.bare(0, 32, false), link.bare(180, 32, true), link.bare(124, 32, true), link.bare(92, 32, true) ],
|
||||
[ true, true, true, true, true ], 'keepalive, nothing; in a handshake\'s second: initiation + keepalive, response + keepalive, response');
|
||||
// Plain data is 32 + a multiple of 16: an IPv4 header alone is 64, a TCP ACK 80 or 96.
|
||||
eq([ link.bare(64, 32, false), link.bare(80, 32, true), link.bare(96, 32, false), link.bare(1480, 32, true), link.bare(5000, 32, false) ],
|
||||
[ false, false, false, false, false ], 'data');
|
||||
eq([ link.bare(180, 32, false), link.bare(124, 32, false), link.bare(92, 32, false) ], [ false, false, false ],
|
||||
'handshake messages only count in the second a handshake completed');
|
||||
// Padding makes it fuzzy: in a handshake's second anything up to three initiations, a response and a
|
||||
// padded keepalive; in any other second one padded keepalive, never more.
|
||||
eq([ link.bare(100, 132, false), link.bare(148 + 132, 132, true), link.bare(3 * 148 + 92 + 132, 132, true), link.bare(3 * 148 + 92 + 133, 132, true) ],
|
||||
[ true, true, true, false ], 'padded keepalives');
|
||||
eq([ link.bare(133, 132, false), link.bare(148 + 52, 132, false), link.bare(668, 132, false) ], [ false, false, false ],
|
||||
'small packets on Maximum: data');
|
||||
});
|
||||
|
||||
test('keepalive_max', () => {
|
||||
eq(link.keepalive_max(null), 32, 'no server');
|
||||
eq(link.keepalive_max({ obf: {} }), 32, 'no disguise');
|
||||
eq(link.keepalive_max({ obf: { content_padding_addition: '10-100' } }), 132, 'content padding');
|
||||
eq(link.keepalive_max({ obf: { content_padding_addition: '40' } }), 72, 'a fixed padding');
|
||||
eq(link.keepalive_max({ obf: { content_padding_addition: '10-100', random_trailers: 'on' } }), 132, 'content padding wins over trailers');
|
||||
eq(link.keepalive_max({ obf: { random_trailers: 'on' } }), 1532, 'random trailers: up to a full packet');
|
||||
let m = { servers: { s_1: { obf: { content_padding_addition: '10-100' } } }, people: { p_1: { server: 's_1' } },
|
||||
devices: { d_1: { person: 'p_1' }, d_2: { person: 'p_gone' } } };
|
||||
eq(link.keepalive_sizes(m), { d_1: 132, d_2: 32 }, 'per device');
|
||||
});
|
||||
|
||||
test('settle holds a state before it shows', () => {
|
||||
let h = link.fresh(T0);
|
||||
eq(link.settle(h, 'trying', T0, false), null, 'new: waits');
|
||||
eq(link.settle(h, 'trying', T0 + link.HOLD - 1, false), null, 'still waits');
|
||||
eq(link.settle(h, 'trying', T0 + link.HOLD, false), { from: null, to: 'trying' }, 'held: shown');
|
||||
eq([ h.state, h.since ], [ 'trying', T0 ], 'since it began');
|
||||
eq(link.settle(h, 'unstable', T0 + 200, true), null, 'another state waits too');
|
||||
eq(link.settle(h, 'trying', T0 + 210, true), null, 'and is forgotten when the first comes back');
|
||||
eq(h.pend, null, 'nothing pending');
|
||||
eq(link.settle(h, null, T0 + 220, true), { from: 'trying', to: null }, 'online and fine: at once');
|
||||
eq([ h.state, h.since ], [ null, 0 ], 'nothing shown');
|
||||
eq(link.shown({ d_1: h, d_2: { state: 'shared', since: 5 } }), { d_2: { state: 'shared', since: 5 } }, 'only what shows');
|
||||
eq(link.event_for({ from: 'shared', to: null }, { id: 'd_2', person: 'p_1' }, true),
|
||||
{ type: 'device_recovered', person: 'p_1', device: 'd_2', detail: 'shared' }, 'recovered event');
|
||||
eq(link.event_for({ from: null, to: 'dropped' }, { id: 'd_2', person: 'p_1' }, true),
|
||||
{ type: 'device_failing', person: 'p_1', device: 'd_2', detail: 'dropped' }, 'failing event');
|
||||
eq(link.event_for(null, { id: 'd_2' }, true), null, 'no change');
|
||||
});
|
||||
|
||||
// The agent moves the person's revision on every change settle() makes, so a
|
||||
// state that clears while the device is away (no event) still leaves the page.
|
||||
test('settle clears a state silently while the device is away', () => {
|
||||
let h = link.fresh(T0);
|
||||
link.settle(h, 'trying', T0, false);
|
||||
link.settle(h, 'trying', T0 + link.HOLD, false);
|
||||
eq(link.settle(h, null, T0 + 300, false), null, 'it stopped trying: waits');
|
||||
let ch = link.settle(h, null, T0 + 300 + link.HOLD, false);
|
||||
eq(ch, { from: 'trying', to: null }, 'then a change: nothing shown');
|
||||
eq(link.event_for(ch, { id: 'd_1', person: 'p_1' }, false), null, 'without an activity event');
|
||||
});
|
||||
|
||||
/*
|
||||
* The set-up sheet's states: at once, no HOLD. Each run also checks that the
|
||||
* state setup() keeps, worked out only when something happened, is what
|
||||
* setup_state() gives on every read.
|
||||
*/
|
||||
test('setup: knocks that never finish connecting', () => {
|
||||
let knocking = (s) => (s % 120 < 90 && s % 5 == 0) ? { drx: 148, dtx: 92 } : {};
|
||||
let r = run(300, knocking);
|
||||
// The first read is the baseline: the knocks count from 5 s.
|
||||
eq(slice(r.setups, 0, 3), [ { s: 10, state: 'trying' }, { s: 100, state: null }, { s: 125, state: 'trying' } ],
|
||||
'with the second initiation; gone 15 s after the last one (85 s); back with the next two');
|
||||
eq(run(130, knocking).h.setup, { state: 'trying', since: T0 + 125 }, 'since it began again');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// One initiation that the next second confirms is a connection, not a knock.
|
||||
let ok1 = run(60, (s) => s == 10 ? { drx: 148, dtx: 92 } : s == 11 ? { hs: true, drx: 32 } : {});
|
||||
eq(ok1.setups, [], 'one knock, then the handshake: nothing to tell (idle)');
|
||||
// Knocking again while an older session still counts as online: it is trying now.
|
||||
let late = run(300, (s) => s < 200 ? phone(s, true) : (s % 5 == 0 ? { drx: 148, dtx: 92 } : {}));
|
||||
eq(late.setups[length(late.setups) - 1], { s: 205, state: 'trying' }, 'its new keys never complete');
|
||||
eq(late.lag, [], 'never behind');
|
||||
});
|
||||
|
||||
test('setup: a new device that connects and passes data', () => {
|
||||
// It knocks at 10 s, the next second its first packets under the new keys carry data.
|
||||
let at = (s) => s < 10 ? {} : s == 10 ? { drx: 148, dtx: 92 } : s == 11 ? { hs: true, drx: 32 + 1400, dtx: 4000 } : phone(s, true);
|
||||
let r = run(900, at);
|
||||
eq(r.setups, [ { s: 11, state: 'flowing' } ], 'flowing with the handshake, and through every new key after');
|
||||
eq(r.h.setup, { state: 'flowing', since: T0 + 11 }, 'since then');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// A first keepalive only, data a few seconds later.
|
||||
let r2 = run(60, (s) => s == 11 ? { hs: true, drx: 32 } : s == 14 ? { drx: 1400, dtx: 9000 } : {});
|
||||
eq(r2.setups, [ { s: 14, state: 'flowing' } ], 'with the first data');
|
||||
// Busy until 300 s, then gone: its session ends 190 s after its last handshake (254 s).
|
||||
let r3 = run(600, (s) => s < 300 ? phone(s, true) : {});
|
||||
eq(r3.setups, [ { s: 30, state: 'flowing' }, { s: 444, state: null } ], 'data from 30 s (what came before the handshake does not count); away: nothing');
|
||||
eq(r3.lag, [], 'never behind');
|
||||
});
|
||||
|
||||
test('setup: idle is not "no data"', () => {
|
||||
// Connected, keepalives only: the router sends nothing back, nothing to tell.
|
||||
let r = run(900, (s) => phone(s, false));
|
||||
eq(r.setups, [], 'a sleeping phone');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// The router sends it something now and then, and it answers: data flows.
|
||||
eq(run(120, (s) => s == 4 ? { hs: true, drx: 32 } : s == 30 ? { dtx: 300, drx: 96 } : {}).setups,
|
||||
[ { s: 30, state: 'flowing' } ], 'an answer is data');
|
||||
});
|
||||
|
||||
test('setup: connected, but nothing it sends comes through', () => {
|
||||
// An old address: its first handshake at 4 s, the router's answers to what it drops at 7, 17, 27 s...
|
||||
let r = run(400, renumbered);
|
||||
eq(r.setups, [ { s: 19, state: 'nodata' } ], 'SETUP_QUIET after the handshake, with an answer in it');
|
||||
eq(r.lag, [], 'never behind, through its new keys at 128 s');
|
||||
// Imported again at 300 s: data flows at once.
|
||||
let r2 = run(400, (s) => s < 300 ? renumbered(s) : s == 300 ? { hs: true, drx: 3000, dtx: 9000 } : phone(s, true));
|
||||
eq(r2.setups, [ { s: 19, state: 'nodata' }, { s: 300, state: 'flowing' } ], 'then flowing');
|
||||
// The router answers only after the quiet span: shown with the answer.
|
||||
let slow = run(60, (s) => s == 4 ? { hs: true } : s == 25 ? { dtx: 32 } : {});
|
||||
eq(slow.setups, [ { s: 25, state: 'nodata' } ], 'with the first answer');
|
||||
eq(slow.lag, [], 'never behind');
|
||||
});
|
||||
|
||||
test('setup: light traffic on Maximum is data', () => {
|
||||
// Content padding of 10-100: keep-alives of 42-132 bytes. A phone that only sends small packets (a DNS
|
||||
// query, a SYN, ACKs: 150-600 bytes a second), and an answer now and then in a second it sent nothing.
|
||||
let at = (s) => s == 3 ? { drx: 148, dtx: 92 } : s == 4 ? { hs: true, drx: 42 } :
|
||||
s > 4 && s % 3 == 0 ? { drx: 150 + (s % 5) * 100, dtx: 1200 } : s % 7 == 0 ? { dtx: 600 } : {};
|
||||
let r = run(60, at, { ka: 132 });
|
||||
eq(r.setups, [ { s: 6, state: 'flowing' } ], 'flowing with its first small packets, never "no data"');
|
||||
eq(r.lag, [], 'never behind');
|
||||
// A keep-alive alone in a second is still no data: an idle phone on Maximum stays idle.
|
||||
eq(run(120, (s) => s == 4 ? { hs: true, drx: 42 } : s % 25 == 0 ? { drx: 42 + (s % 90) } : {}, { ka: 132 }).setups, [],
|
||||
'padded keep-alives');
|
||||
});
|
||||
|
||||
test('setups', () => {
|
||||
let h = link.fresh(T0);
|
||||
eq(link.setups({ d_1: h, d_2: { setup: { state: 'trying', since: 5 } } }), { d_2: { state: 'trying', since: 5 } }, 'only devices with one');
|
||||
eq(link.setup_state(h, T0, false), { state: null, due: 0 }, 'nothing seen: nothing');
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
// dawnline.live: event categories and the retention policy, from a settings
|
||||
// object and from the fixture config (real libuci).
|
||||
// object and from the fixture config (real libuci); which tunnels are read,
|
||||
// the counters folded from a read, how long a device counts as online, and
|
||||
// what of the agent's files a read takes (RUN_DIR, put back after).
|
||||
import * as live from 'dawnline.live';
|
||||
import { RUN_DIR } from 'dawnline.util';
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
|
||||
test('category_of', () => {
|
||||
eq(live.category_of('connect'), 'connections', 'connect');
|
||||
@@ -66,3 +70,113 @@ test('fill_places', () => {
|
||||
ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged');
|
||||
ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log');
|
||||
});
|
||||
|
||||
test('tunnel_ifnames: the servers that run, on interfaces of their own', () => {
|
||||
let srv = (ifname, more) => ({ enabled: true, private_key: 'k', ifname, subnet: '10.9.0.0/29', ...(more ?? {}) });
|
||||
let m = { servers: {
|
||||
a: srv('awga'), off: srv('awgoff', { enabled: false }), keyless: srv('awgk', { private_key: '' }),
|
||||
taken: srv('lan', { blocked: { code: 'taken', ifname: 'lan' } }), bad: srv('Bad Name'),
|
||||
} };
|
||||
eq(live.tunnel_ifnames(m), [ 'awga' ], 'not turned off, without keys, kept down or misnamed');
|
||||
eq(live.tunnel_ifnames({ servers: {} }), [], 'none');
|
||||
m.servers.b = srv('awgb');
|
||||
eq(live.tunnel_ifnames(m, 'b'), [ 'awgb' ], 'one server\'s (a person\'s page)');
|
||||
eq([ live.tunnel_ifnames(m, 'off'), live.tunnel_ifnames(m, ''), live.tunnel_ifnames(m, 'gone') ], [ [], [], [] ],
|
||||
'one that does not run, no server, an unknown one: nothing');
|
||||
});
|
||||
|
||||
// What a read that failed, a tunnel that is down and a new link do to the counters.
|
||||
test('collect: counters per tunnel read', () => {
|
||||
let m = {
|
||||
servers: { a: { ifname: 'awga' }, b: { ifname: 'awgb' } },
|
||||
people: { pa: { server: 'a' }, pb: { server: 'b' } },
|
||||
devices: { da: { person: 'pa', public_key: 'KA' }, db: { person: 'pb', public_key: 'KB' } },
|
||||
settings: { retention: {} },
|
||||
};
|
||||
let usage = { devices: { da: { raw: [ 40, 10 ], ifindex: 7 }, db: { raw: [ 500, 500 ] } }, people: {} };
|
||||
let peer = (rx, tx) => ({ KA: { ifname: 'awga', endpoint: '', handshake: 0, rx, tx } });
|
||||
live.collect(m, usage, { ok: false, reads: { awga: 'read', awgb: 'error' }, ifaces: { awga: { ifindex: 7 } }, peers: peer(100, 50) });
|
||||
eq(usage.devices.da.total, [ 60, 40 ], 'the difference since the last read');
|
||||
eq(usage.people.pa.total, [ 60, 40 ], 'their person');
|
||||
eq(usage.devices.db.raw, [ 500, 500 ], 'a tunnel that could not be read keeps its counters');
|
||||
live.collect(m, usage, { ok: true, reads: { awga: 'read', awgb: 'down' }, ifaces: { awga: { ifindex: 7 } }, peers: peer(100, 50) });
|
||||
eq(usage.devices.db.raw, [ 0, 0 ], 'a tunnel that is down starts again from zero');
|
||||
eq(usage.devices.da.total, [ 60, 40 ], 'nothing new');
|
||||
// Set up again: a new link whose counters already passed the old ones.
|
||||
live.collect(m, usage, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: 8 } }, peers: peer(150, 80) });
|
||||
eq(usage.devices.da.total, [ 210, 120 ], 'a new link counts from zero');
|
||||
eq(usage.devices.da.ifindex, 8, 'the record follows its link');
|
||||
// A link whose index is unknown changes nothing about the epoch.
|
||||
live.collect(m, usage, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: null } }, peers: peer(160, 90) });
|
||||
eq([ usage.devices.da.total, usage.devices.da.ifindex ], [ [ 220, 130 ], 8 ], 'counted on');
|
||||
});
|
||||
|
||||
// The window follows the keep-alive the device's configuration carries
|
||||
// (awg.idle_handshake): 190 s for every default, longer only where the
|
||||
// handshakes of an idle device are further apart.
|
||||
test('online_window', () => {
|
||||
let srv = { keepalive: 25, obf: {} };
|
||||
eq(live.online_window(srv, {}), 190, 'the default keep-alive');
|
||||
eq(live.online_window({ keepalive: 25, obf: { header_protection_key: 'k', rekey_after_time: '100-120' } }, {}), 190, 'Maximum');
|
||||
eq(live.online_window(srv, { keepalive: 0 }), 190, 'keep-alive off: the session alone');
|
||||
eq(live.online_window(srv, { keepalive: 100 }), 250, 'a handshake every second keep-alive');
|
||||
eq(live.online_window(srv, { keepalive: 300 }), 330, 'one every keep-alive');
|
||||
eq(live.online_window({ keepalive: 300, obf: {} }, {}), 330, 'the server\'s keep-alive');
|
||||
eq(live.online_window(null, {}), 190, 'no server');
|
||||
let m = { servers: { a: srv }, people: { p: { server: 'a' } }, devices: { d: { person: 'p', keepalive: 300 }, e: { person: 'x' } } };
|
||||
eq(live.online_windows(m), { d: 330, e: 190 }, 'per device');
|
||||
eq(live.online_windows(m, 'a'), { d: 330 }, 'one server\'s devices');
|
||||
});
|
||||
|
||||
test('online: without the agent, by the device\'s window', () => {
|
||||
let peer = { handshake: time() - 300 };
|
||||
eq(live.online({ presence: null, windows: { d: 330 } }, 'd', peer), true, 'within its window');
|
||||
eq(live.online({ presence: null }, 'd', peer), false, 'the shortest window');
|
||||
eq(live.online({ presence: { online: { d: false } }, windows: { d: 330 } }, 'd', peer), false, 'the agent\'s word first');
|
||||
});
|
||||
|
||||
test('collect: online by the device\'s window', () => {
|
||||
let m = {
|
||||
servers: { a: { ifname: 'awga', keepalive: 300, obf: {} } },
|
||||
people: { pa: { server: 'a' } },
|
||||
devices: { da: { person: 'pa', public_key: 'KA' }, db: { person: 'pa', public_key: 'KB', keepalive: 25 } },
|
||||
settings: { retention: {} },
|
||||
};
|
||||
let hs = time() - 300;
|
||||
let peers = { KA: { ifname: 'awga', endpoint: '', handshake: hs, rx: 0, tx: 0 }, KB: { ifname: 'awga', endpoint: '', handshake: hs, rx: 0, tx: 0 } };
|
||||
let v = live.collect(m, { devices: {}, people: {} }, { ok: true, reads: { awga: 'read' }, ifaces: { awga: { ifindex: 1 } }, peers });
|
||||
eq([ v.da.online, v.db.online ], [ true, false ], 'the server\'s keep-alive of 300 s, and a device\'s own of 25 s');
|
||||
});
|
||||
|
||||
// What the agent's watcher shows of each link (dawnline.link) reaches the
|
||||
// read models through dump(), only while the agent runs.
|
||||
test('dump: link and set-up states while the agent runs', () => {
|
||||
let beat = `${RUN_DIR}/agent.beat`;
|
||||
let had_beat = readfile(beat), had_link = readfile(live.LINK), had_setup = readfile(live.SETUP);
|
||||
let shown = { d_1: { state: 'trying', since: 1800000000 } }, setups = { d_1: { state: 'trying', since: 1800000000 } };
|
||||
writefile(live.LINK, sprintf('%J', shown));
|
||||
writefile(live.SETUP, sprintf('%J', setups));
|
||||
writefile(beat, `${time()}`);
|
||||
let m = { servers: {}, people: {}, devices: {} };
|
||||
eq(live.dump(m).link, shown, 'the watcher\'s states');
|
||||
eq(live.dump(m).setup, setups, 'and its set-up states');
|
||||
writefile(beat, `${time() - 600}`);
|
||||
eq(live.dump(m).link, {}, 'a stopped agent\'s states are stale');
|
||||
eq(live.dump(m).setup, null, 'and nobody tells the set-up states');
|
||||
for (let f in [ [ beat, had_beat ], [ live.LINK, had_link ], [ live.SETUP, had_setup ] ])
|
||||
f[1] == null ? unlink(f[0]) : writefile(f[0], f[1]);
|
||||
});
|
||||
|
||||
// A link that keeps failing is one line per device (add_event_merged), not one per device and person.
|
||||
test('add_event_merged: per device', () => {
|
||||
let path = `${RUN_DIR}/events.json`, had = readfile(path);
|
||||
writefile(path, '[]');
|
||||
live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x1', detail: 'trying' }, 3600);
|
||||
live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x1', detail: 'unstable' }, 3600);
|
||||
live.add_event_merged({ type: 'device_failing', person: 'p_x', device: 'd_x2', detail: 'shared' }, 3600);
|
||||
let ev = live.load_events();
|
||||
eq(map(ev, (e) => [ e.device, e.detail ]), [ [ 'd_x1', 'trying, unstable' ], [ 'd_x2', 'shared' ] ], 'merged per device');
|
||||
eq(live.category_of('device_failing'), 'problems', 'a problem');
|
||||
eq(live.category_of('device_recovered'), 'problems', 'and so is its end');
|
||||
had == null ? unlink(path) : writefile(path, had);
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
// dawnline.loop: the "like a home device" link's errors, stored as codes and
|
||||
// put into words when read.
|
||||
// put into words when read; the netns's MAC and which LAN address it may use;
|
||||
// the policy rules for the servers that send their devices this way, and the
|
||||
// commands that bring the rules the kernel shows to them.
|
||||
import * as loop from 'dawnline.loop';
|
||||
import { ip2int, parse_cidr } from 'dawnline.util';
|
||||
|
||||
test('error_text', () => {
|
||||
eq(loop.error_text(null), null, 'no error');
|
||||
@@ -10,3 +13,97 @@ test('error_text', () => {
|
||||
eq(loop.error_text({ code: 'setup', detail: 'ip: RTNETLINK answers: File exists' }), 'Setup failed: ip: RTNETLINK answers: File exists', 'setup');
|
||||
eq(loop.error_text('an old message'), 'an old message', 'older files: as written');
|
||||
});
|
||||
|
||||
test('lan_mac', () => {
|
||||
let mac = loop.lan_mac('d4:0d:ab:06:94:aa\n');
|
||||
// Pinned: another MAC after an update would make the netns look like someone else once.
|
||||
eq(mac, '7a:4e:71:7a:e0:83', 'hashed from the bridge MAC, as sysfs gives it');
|
||||
eq(loop.lan_mac('D4:0D:AB:06:94:AA'), mac, 'the same however it is written');
|
||||
ok(loop.lan_mac('d4:0d:ab:06:94:ab') != mac, 'another bridge, another MAC');
|
||||
for (let b in [ 'd4:0d:ab:06:94:aa', 'd4:0d:ab:06:94:ab', '00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff' ]) {
|
||||
let m = loop.lan_mac(b);
|
||||
ok(match(m, /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/), `${b}: a MAC`);
|
||||
let first = hex(substr(m, 0, 2));
|
||||
eq([ first & 1, first & 2 ], [ 0, 2 ], `${b}: unicast, locally administered`);
|
||||
}
|
||||
});
|
||||
|
||||
test('address_free', () => {
|
||||
let lan = parse_cidr('10.0.1.1/24');
|
||||
let facts = { pool: [ ip2int('10.0.1.100'), ip2int('10.0.1.249') ], statics: [ ip2int('10.0.1.50') ] };
|
||||
let ours = '7a:4e:71:7a:e0:83', old = '7e:8b:31:7d:04:ba', other = '3c:22:fb:01:02:03';
|
||||
let free = (ip, used, mine) => loop.address_free(ip2int(ip), lan, facts, used ?? {}, mine ?? [ ours, null ]);
|
||||
ok(free('10.0.1.254'), 'nobody on it');
|
||||
ok(free('10.0.1.254', { '10.0.1.254': ours }), 'the neighbour entry of the netns before it was created again');
|
||||
ok(free('10.0.1.254', { '10.0.1.254': old }, [ ours, old ]), 'the netns as it is now (an older version gave it a random MAC)');
|
||||
ok(!free('10.0.1.254', { '10.0.1.254': old }), 'a MAC that is not the netns\'s: someone else');
|
||||
ok(!free('10.0.1.254', { '10.0.1.254': other }, [ ours, null ]), 'another device');
|
||||
ok(!free('10.0.1.254', { '10.0.1.254': true }), 'an entry without a MAC');
|
||||
ok(!free('10.0.1.1'), 'the router');
|
||||
ok(!free('10.0.1.50'), 'a static lease');
|
||||
ok(!free('10.0.1.100') && !free('10.0.1.249'), 'the DHCP pool');
|
||||
ok(free('10.0.1.99') && free('10.0.1.250'), 'next to the pool');
|
||||
ok(!free('10.0.1.0') && !free('10.0.1.255'), 'the network and broadcast addresses');
|
||||
ok(loop.address_free(ip2int('10.0.1.120'), lan, { pool: null, statics: [] }, {}, [ ours ]), 'no DHCP on the LAN: the pool is free');
|
||||
});
|
||||
|
||||
// The netns's rules: the flowtable only on the netns's own links, never on
|
||||
// the root namespace's (the guard on dawn0 must see every packet).
|
||||
test('ns_rules', () => {
|
||||
let p = { address: '10.0.1.250', dns: '10.0.1.1' };
|
||||
let fast = loop.ns_rules(p, true), plain = loop.ns_rules(p, false);
|
||||
eq(map(match(fast, /devices = \{ ([^}]*) \}/g), (m) => m[1]), [ '"dlx1", "dll1"' ], 'one flowtable, on dlx1 and dll1 only');
|
||||
ok(!match(fast, /dlx0|dll0/), 'no root namespace link');
|
||||
ok(index(fast, 'ct state established meta l4proto { tcp, udp } flow add @ft') >= 0, 'established flows added');
|
||||
ok(index(plain, 'flowtable') < 0 && index(plain, 'flow add') < 0, 'plain: no flowtable');
|
||||
eq(replace(fast, /\n\tflowtable ft \{(\n\t\t[^\n]*)*\n\t\}|\n\t\tct state established meta l4proto \{ tcp, udp \} flow add @ft/g, ''), plain, 'otherwise the same rules');
|
||||
});
|
||||
|
||||
// A plan with one server sending its devices like a home device (plan() makes
|
||||
// it, from the server's interface, its tunnel and its home networks).
|
||||
const PLAN = { address: '192.168.1.250', table: 2077,
|
||||
servers: [ { ifname: 'awghome', subnet: '10.9.0.0/29', direct: [ '10.9.0.0/29', '192.168.1.0/24' ] } ] };
|
||||
|
||||
test('rules', () => {
|
||||
eq(loop.rules(PLAN), [
|
||||
{ pref: 5205, iif: 'awghome', to: '192.168.1.250/32', table: '2077' },
|
||||
{ pref: 5210, iif: 'awghome', to: '10.9.0.0/29', table: 'main' },
|
||||
{ pref: 5210, iif: 'awghome', to: '192.168.1.0/24', table: 'main' },
|
||||
{ pref: 5290, iif: 'awghome', to: null, table: '2077' },
|
||||
], 'DNS into the netns, home and the tunnel by main, the rest into the netns');
|
||||
eq(loop.rules({ servers: [] }), [], 'no server sends anyone');
|
||||
eq(loop.rules(null), [], 'no plan');
|
||||
});
|
||||
|
||||
// What `ip -j -4 rule show` prints for the rules of PLAN: "src": "all" for a
|
||||
// rule without a source, a /32 without its length (iproute2 iprule.c).
|
||||
const HOME_SHOWN = [
|
||||
{ priority: 5205, src: 'all', iif: 'awghome', dst: '192.168.1.250', table: '2077' },
|
||||
{ priority: 5210, src: 'all', iif: 'awghome', dst: '10.9.0.0', dstlen: 29, table: 'main' },
|
||||
{ priority: 5210, src: 'all', iif: 'awghome', dst: '192.168.1.0', dstlen: 24, table: 'main' },
|
||||
{ priority: 5290, src: 'all', iif: 'awghome', table: '2077' },
|
||||
];
|
||||
|
||||
test('rule_cmds: the rules the kernel shows, against the plan', () => {
|
||||
eq(loop.rule_cmds(PLAN, HOME_SHOWN), [], 'as wanted: nothing to do (no rule added again, none removed)');
|
||||
eq(loop.rule_cmds(PLAN, slice(HOME_SHOWN, 0, 3)), [ "ip -4 rule add priority 5290 iif 'awghome' lookup 2077" ], 'one gone: only it comes back');
|
||||
eq(loop.rule_cmds(PLAN, [ ...HOME_SHOWN, HOME_SHOWN[3] ]), [ "ip -4 rule del priority 5290 iif 'awghome' lookup 2077" ], 'one twice: one of them goes');
|
||||
eq(loop.rule_cmds(PLAN, []), [
|
||||
"ip -4 rule add priority 5205 iif 'awghome' to 192.168.1.250/32 lookup 2077",
|
||||
"ip -4 rule add priority 5210 iif 'awghome' to 10.9.0.0/29 lookup main",
|
||||
"ip -4 rule add priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main",
|
||||
"ip -4 rule add priority 5290 iif 'awghome' lookup 2077",
|
||||
], 'none yet: all of them');
|
||||
eq(loop.rule_cmds({ servers: [] }, HOME_SHOWN), [
|
||||
"ip -4 rule del priority 5205 iif 'awghome' to 192.168.1.250 lookup 2077",
|
||||
"ip -4 rule del priority 5210 iif 'awghome' to 10.9.0.0/29 lookup main",
|
||||
"ip -4 rule del priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main",
|
||||
"ip -4 rule del priority 5290 iif 'awghome' lookup 2077",
|
||||
], 'none wanted: each removed as shown, without "from all"');
|
||||
eq(loop.rule_cmds({ ...PLAN, servers: [ { ...PLAN.servers[0], direct: [ '10.9.0.0/29', '192.168.2.0/24' ] } ] }, HOME_SHOWN), [
|
||||
"ip -4 rule add priority 5210 iif 'awghome' to 192.168.2.0/24 lookup main",
|
||||
"ip -4 rule del priority 5210 iif 'awghome' to 192.168.1.0/24 lookup main",
|
||||
], 'another home network: the new rule first, then the old one goes');
|
||||
eq(loop.rule_cmds(PLAN, [ ...HOME_SHOWN, { priority: 5290, src: '10.9.0.2', iif: 'awghome', table: '2077' } ]),
|
||||
[ "ip -4 rule del priority 5290 from 10.9.0.2 iif 'awghome' lookup 2077" ], 'a rule of ours with a source is not one of them: it goes');
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
// dawnline.meter: the point between two samples (each server's bytes per
|
||||
// second), the sample taken from a dump, the two minutes kept, and the file
|
||||
// the watcher writes and the RPC reads (in RUN_DIR, removed after).
|
||||
import * as meter from 'dawnline.meter';
|
||||
import { stat, unlink } from 'fs';
|
||||
|
||||
test('point', () => {
|
||||
let a = {
|
||||
t: 100.0, ts: 5000, servers: [ 's_1', 's_2' ],
|
||||
dev: { d_1: [ 1000, 2000, 's_1' ], d_2: [ 500, 500, 's_1' ], d_3: [ 9000, 9000, 's_1' ], d_5: [ 0, 0, 's_2' ] },
|
||||
};
|
||||
let b = {
|
||||
t: 101.0, ts: 5001, servers: [ 's_1', 's_2' ],
|
||||
// d_2 sent nothing; d_3's peer was added again (counters from zero); d_4 is new; d_5 moved to s_1.
|
||||
dev: { d_1: [ 3000, 12000, 's_1' ], d_2: [ 500, 500, 's_1' ], d_3: [ 100, 300, 's_1' ], d_4: [ 10, 10, 's_1' ], d_5: [ 50, 50, 's_1' ] },
|
||||
};
|
||||
eq(meter.point(a, b), { ts: 5001, servers: { s_1: [ 2000, 10000 ], s_2: [ 0, 0 ] } },
|
||||
'bytes per second of each server\'s devices together; a server read with nothing moving is 0');
|
||||
eq(meter.point(a, { ...b, t: 102.0 }).servers.s_1, [ 1000, 5000 ], 'over two seconds');
|
||||
eq(meter.point(a, { ...b, t: 100.0 }), null, 'no time passed');
|
||||
eq(meter.point(a, { ...b, t: 110.0 }), null, 'the watcher stalled');
|
||||
eq(meter.point(a, { ...b, servers: [ 's_2' ], dev: { d_5: [ 50, 50, 's_2' ] } }).servers, { s_2: [ 50, 50 ] }, 'only servers read in the newer sample');
|
||||
eq(meter.point({ ...a, dev: {} }, b).servers, { s_1: [ 0, 0 ], s_2: [ 0, 0 ] }, 'a first look at every device: nothing yet');
|
||||
});
|
||||
|
||||
test('sample', () => {
|
||||
let m = {
|
||||
servers: { s_1: { ifname: 'dawn0' }, s_2: { ifname: 'dawn9' } },
|
||||
people: { p: { server: 's_1' }, q: { server: 's_2' } },
|
||||
devices: { d_1: { person: 'p', public_key: 'K1' }, d_2: { person: 'p', public_key: 'K2' }, d_3: { person: 'q', public_key: 'K3' } },
|
||||
};
|
||||
let d = { reads: { dawn0: 'read', dawn9: 'error' }, peers: { K1: { rx: 10, tx: 20 }, K3: { rx: 1, tx: 1 } } };
|
||||
let s = meter.sample(m, d, 5000);
|
||||
eq([ s.ts, s.servers, s.dev ], [ 5000, [ 's_1' ], { d_1: [ 10, 20, 's_1' ] } ],
|
||||
'the servers read and their devices in the tunnel; not a tunnel that could not be read');
|
||||
ok(s.t > 0, 'monotonic time');
|
||||
});
|
||||
|
||||
test('keep', () => {
|
||||
let pt = (ts) => ({ ts: ts, servers: { s_1: [ ts, 0 ] } });
|
||||
let ring = [];
|
||||
for (let ts = 1000; ts < 1000 + meter.POINTS + 5; ts++)
|
||||
meter.keep(ring, pt(ts));
|
||||
eq([ length(ring), ring[0][0], ring[length(ring) - 1][0] ], [ meter.POINTS, 1005, 1000 + meter.POINTS + 4 ],
|
||||
'the last POINTS seconds, newest last');
|
||||
eq(json(ring[0][1]), pt(1005), 'each point kept as its JSON');
|
||||
meter.keep(ring, pt(5000));
|
||||
eq(map(ring, (r) => r[0]), [ 5000 ], 'after a stalled watcher: nothing older than two minutes');
|
||||
meter.keep(ring, pt(5001));
|
||||
meter.keep(ring, pt(5002));
|
||||
meter.keep(ring, pt(5001));
|
||||
eq(map(ring, (r) => r[0]), [ 5000, 5001 ], 'a clock that went back: its points replace the later ones');
|
||||
});
|
||||
|
||||
test('want, save and read', () => {
|
||||
let had = stat(meter.WANT) != null;
|
||||
meter.want();
|
||||
ok(meter.wanted(time()), 'just asked');
|
||||
ok(!meter.wanted(time() + meter.WANT_FOR), 'stale after WANT_FOR');
|
||||
ok(!meter.wanted(time() - meter.WANT_FOR - 1), 'a clock that went back does not keep it');
|
||||
let t = time();
|
||||
meter.save([ [ t - 2, `{"ts":${t - 2},"servers":{}}` ], [ t - 1, `{"ts":${t - 1},"servers":{}}` ], [ t, `{"ts":${t},"servers":{"s_1":[1,2]}}` ] ]);
|
||||
let r = meter.read(0);
|
||||
eq([ r.ts, length(r.points), r.want, r.keep ], [ t, 3, meter.WANT_FOR, meter.POINTS ], 'everything');
|
||||
eq(meter.read(t - 1).points, [ { ts: t, servers: { s_1: [ 1, 2 ] } } ], 'only what is newer');
|
||||
let old = t - meter.WANT_FOR - 1;
|
||||
meter.save([ [ old, `{"ts":${old},"servers":{}}` ] ]);
|
||||
eq([ meter.read(0).ts, meter.read(0).points ], [ old, [] ], 'left by an agent that died while someone looked: no points');
|
||||
meter.stop();
|
||||
eq([ meter.read(0).ts, meter.read(0).points ], [ 0, [] ], 'nobody looks: nothing');
|
||||
if (!had)
|
||||
unlink(meter.WANT);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// dawnline.netifd: drift(), the watchdog's look at a server's interface
|
||||
// (network.<ifname> against what sync() writes, markers aside), on the
|
||||
// fixture's server and a section this test puts into /etc/config/network
|
||||
// the way sync() writes it, and takes out again.
|
||||
import { readfile, writefile, unlink } from 'fs';
|
||||
import { cursor } from 'uci';
|
||||
import { uci_put } from 'dawnline.util';
|
||||
import * as core from 'dawnline.core';
|
||||
import * as awg from 'dawnline.awg';
|
||||
import * as netifd from 'dawnline.netifd';
|
||||
|
||||
const NETWORK = '/etc/config/network';
|
||||
|
||||
test('drift: the interface as Dawnline set it, and edited outside it', () => {
|
||||
let had = readfile(NETWORK);
|
||||
if (had == null)
|
||||
writefile(NETWORK, '');
|
||||
let m = core.load();
|
||||
let srv = m.servers.main;
|
||||
let c = cursor();
|
||||
c.load('network');
|
||||
c.set('network', 'awgmain', 'interface');
|
||||
for (let k, v in awg.netifd_options(srv))
|
||||
uci_put(c, 'network', 'awgmain', k, v);
|
||||
c.set('network', 'awgmain', '_dawnline', 'main');
|
||||
c.set('network', 'awgmain', '_dawnline_name', srv.name);
|
||||
c.commit('network');
|
||||
let edit = (opt, val) => {
|
||||
uci_put(c, 'network', 'awgmain', opt, val);
|
||||
c.commit('network');
|
||||
return netifd.drift(m);
|
||||
};
|
||||
let got = { as_set: netifd.drift(m) };
|
||||
got.renamed = edit('_dawnline_name', 'Renamed in LuCI');
|
||||
got.edited = edit('mtu', '1420');
|
||||
got.more = edit('awg_jc', null);
|
||||
edit('mtu', `${core.tunnel_mtu(srv)}`);
|
||||
got.restored = edit('awg_jc', srv.obf.jc);
|
||||
got.disabled = edit('disabled', '1');
|
||||
edit('disabled', null);
|
||||
got.foreign = edit('_dawnline', 'someone');
|
||||
m.servers.main.enabled = false;
|
||||
got.off = netifd.drift(m);
|
||||
// Put the router back as the other tests know it.
|
||||
c.delete('network', 'awgmain');
|
||||
c.commit('network');
|
||||
if (had == null)
|
||||
unlink(NETWORK);
|
||||
eq(got.as_set, { main: [] }, 'as sync() writes it');
|
||||
eq(got.renamed, { main: [] }, 'the markers are not compared');
|
||||
eq(got.edited, { main: [ 'mtu' ] }, 'an option changed by hand');
|
||||
eq(got.more, { main: [ 'mtu', 'awg_jc' ] }, 'and one removed, by name only');
|
||||
eq(got.restored, { main: [] }, 'put back');
|
||||
eq(got.disabled, { main: [ 'disabled' ] }, 'switched off outside Dawnline');
|
||||
eq(got.foreign, {}, "a section that isn't the server's is not looked at");
|
||||
eq(got.off, {}, 'a server turned off is not looked at');
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// dawnline.nft: the access table rendered for a model with two servers (one
|
||||
// sending everyone like a home device, one direct) and the router read as a
|
||||
// fixed context: exactly what 0.13.0 renders (fixtures/nft-table.txt, made by
|
||||
// that version from this model).
|
||||
import { readfile } from 'fs';
|
||||
import * as nft from 'dawnline.nft';
|
||||
|
||||
const KEY = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||
const SNAP = { devices: { 'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] }, eth1: { nets: [], zone: 'wan' } },
|
||||
wan: 'eth1', lan: 'br-lan', zones: [ 'lan', 'wan' ] };
|
||||
// The netns is up (its DNS address, the Home-only resolver inside it) and the LAN's DNS is the router.
|
||||
const CTX = { dns_addr: '192.168.1.250', resolver: { mode: 'ns', address: '169.254.77.2', port: 53 }, lan_dns: '192.168.1.1', snap: SNAP };
|
||||
const STATES = { alice: 'active', bob: 'active', carol: 'active', dave: 'active', erin: 'active' };
|
||||
let golden = readfile(sourcepath(0, true) + '/fixtures/nft-table.txt');
|
||||
|
||||
/** Server home sends everyone like a home device, work sends everyone direct. */
|
||||
function model() {
|
||||
let srv = (id, ifname, subnet, lan_like, mesh) => ({ id, name: id, ifname, subnet, private_key: KEY, enabled: true, lan_like, mesh,
|
||||
auto_wan: true, auto_lan: true, lan_devices: [], lan_zone: 'lan', wan_zone: 'wan', obf: {} });
|
||||
let person = (id, server, access, extra) => ({ id, name: id, server, access, dns_mode: 'device', services: [], home_nets: [],
|
||||
circle: '', ...(extra ?? {}) });
|
||||
let dev = (person, address) => ({ person, address, disabled: false });
|
||||
return {
|
||||
settings: { portal_enabled: true, portal_port: 8443, portal_host: 'vpn.example.com', portal_alt: [] },
|
||||
servers: { home: srv('home', 'awghome', '10.9.0.0/29', true, 'all'), work: srv('work', 'awgwork', '10.9.1.0/29', false, 'circles') },
|
||||
people: {
|
||||
alice: person('alice', 'home', 'both'), bob: person('bob', 'work', 'internet'),
|
||||
carol: person('carol', 'home', 'lan', { dns_mode: 'home' }), dave: person('dave', 'home', 'internet'),
|
||||
erin: person('erin', 'work', 'both'),
|
||||
},
|
||||
devices: {
|
||||
a1: dev('alice', '10.9.0.2'), b1: dev('bob', '10.9.1.2'), c1: dev('carol', '10.9.0.3'),
|
||||
d1: dev('dave', '10.9.0.4'), d2: dev('dave', '10.9.0.5'), e1: dev('erin', '10.9.1.3'),
|
||||
},
|
||||
services: {}, circles: {},
|
||||
};
|
||||
}
|
||||
|
||||
function render(m, states) {
|
||||
return nft.render(m, nft.access_sets(m, null, states ?? STATES, SNAP), CTX);
|
||||
}
|
||||
|
||||
test('render: the table as it was', () => {
|
||||
ok(golden != null, 'the fixture is there');
|
||||
eq(render(model()), golden, 'line for line');
|
||||
let m = model();
|
||||
m.devices.b1.lan_bypass = true;
|
||||
eq(render(m), golden, 'a device that keeps its own local network out of the tunnel changes nothing here');
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// dawnline.pkg: the package a control text or file names (ipk control,
|
||||
// `apk adbdump`), and when an apk install of package files took: every
|
||||
// package at its file's version, a rollback to an older one included.
|
||||
import * as pkg from 'dawnline.pkg';
|
||||
|
||||
const DIR = '/tmp/dawnline-tests/pkg';
|
||||
|
||||
// AmneziaWG 3.1 as the Components tab installs it, and the 2.0 build before it.
|
||||
const NEW = [
|
||||
{ name: 'kmod-amneziawg', version: '6.12.94.3.1.20260906-r1', file: '/tmp/x/kmod.apk' },
|
||||
{ name: 'amneziawg-tools', version: '3.1.20260812-r1', file: '/tmp/x/tools.apk' },
|
||||
{ name: 'luci-proto-amneziawg', version: '3.1.0-r1', file: '/tmp/x/proto.apk' },
|
||||
];
|
||||
const OLD = { 'kmod-amneziawg': '6.12.94.1.0.20250722-r1', 'amneziawg-tools': '1.0.20250722-r1', 'luci-proto-amneziawg': '2.0.0-r1' };
|
||||
|
||||
function at(list) {
|
||||
let have = {};
|
||||
for (let w in list)
|
||||
have[w.name] = w.version;
|
||||
return have;
|
||||
}
|
||||
|
||||
test('control_info of an ipk control file', () => {
|
||||
eq(pkg.control_info('Package: amneziawg-tools\nVersion: 1.0.20250722-r1\nDepends: libc\nArchitecture: aarch64_cortex-a53\n', true),
|
||||
{ name: 'amneziawg-tools', version: '1.0.20250722-r1' }, 'fields');
|
||||
eq(pkg.control_info('Description: no package here\n', true), { name: null, version: null }, 'nothing said');
|
||||
});
|
||||
|
||||
test('control_info of apk adbdump', () => {
|
||||
let dump = '#%SCHEMA: 00504B47\ninfo:\n name: kmod-amneziawg\n version: 6.12.94.3.1.20260906-r1\n' +
|
||||
' description: AmneziaWG kernel module\n arch: aarch64_cortex-a53\n depends: # 2 items\n - kernel=6.12.94\n' +
|
||||
' - kmod-udptunnel4\npaths: # 2 items\n - name: lib/modules\n - name: lib/modules/6.12.94\n files: # 1 items\n' +
|
||||
' - name: amneziawg.ko\n';
|
||||
eq(pkg.control_info(dump, false), { name: 'kmod-amneziawg', version: '6.12.94.3.1.20260906-r1' }, 'the package, not its files');
|
||||
eq(pkg.control_info('', false), { name: null, version: null }, 'adbdump failed');
|
||||
eq(pkg.control_info(null, false), { name: null, version: null }, 'no output');
|
||||
});
|
||||
|
||||
test('file_info of an ipk', () => {
|
||||
system(`rm -rf ${DIR} && mkdir -p ${DIR}`);
|
||||
ok(system(`cd ${DIR} && printf 'Package: luci-proto-amneziawg\\nVersion: 2.0.0-r1\\n' > control && tar -czf control.tar.gz ./control && tar -czf proto.ipk ./control.tar.gz`) == 0,
|
||||
'made the ipk');
|
||||
eq(pkg.file_info(`${DIR}/proto.ipk`), { name: 'luci-proto-amneziawg', version: '2.0.0-r1' }, 'name and version');
|
||||
eq(pkg.file_version(`${DIR}/proto.ipk`), '2.0.0-r1', 'file_version');
|
||||
});
|
||||
|
||||
test('mismatched: an update took', () => {
|
||||
eq(pkg.mismatched(NEW, at(NEW)), [], 'every package at its file');
|
||||
});
|
||||
|
||||
test('mismatched: a rollback to an older build took', () => {
|
||||
let back = map(keys(OLD), (n) => ({ name: n, version: OLD[n], file: `/tmp/x/${n}.apk` }));
|
||||
eq(pkg.mismatched(back, OLD), [], 'older versions are what the files hold');
|
||||
});
|
||||
|
||||
test('mismatched: apk left a package alone', () => {
|
||||
let have = { ...at(NEW), 'amneziawg-tools': OLD['amneziawg-tools'] };
|
||||
eq(pkg.mismatched(NEW, have), [ NEW[1] ], 'the tools kept their old version');
|
||||
eq(pkg.mismatched(NEW, OLD), NEW, 'nothing changed');
|
||||
});
|
||||
|
||||
test('mismatched: missing or unreadable', () => {
|
||||
let have = at(NEW);
|
||||
delete have['luci-proto-amneziawg'];
|
||||
eq(pkg.mismatched(NEW, have), [ NEW[2] ], 'not installed after the install');
|
||||
let blind = [ { name: null, version: null, file: '/tmp/x/broken.apk' } ];
|
||||
eq(pkg.mismatched(blind, {}), blind, 'a file that names no package never counts as installed');
|
||||
eq(pkg.mismatched([ { name: 'amneziawg-tools', version: null, file: '/tmp/x/t.apk' } ], { 'amneziawg-tools': null }),
|
||||
[ { name: 'amneziawg-tools', version: null, file: '/tmp/x/t.apk' } ], 'no version on either side');
|
||||
eq(pkg.mismatched(NEW, null), NEW, 'no installed versions');
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
// usr/libexec/dawnline/updater: a call without a command it knows prints the usage and changes nothing (no job for
|
||||
// Components, no history, no "update failed" in the service log).
|
||||
import * as fs from 'fs';
|
||||
|
||||
const REPO = `${sourcepath(0, true)}/../..`;
|
||||
const UPDATER = `${REPO}/package/luci-app-dawnline/root/usr/libexec/dawnline/updater`;
|
||||
const MODULES = `${REPO}/package/luci-app-dawnline/root/usr/share/ucode/*.uc`;
|
||||
const JOB = '/var/run/dawnline/update-job.json';
|
||||
|
||||
/** The updater run with `args`: { code, out } (stdout and stderr together). */
|
||||
function updater(args) {
|
||||
let p = fs.popen(`ucode -L '${MODULES}' '${UPDATER}' ${args} 2>&1; echo "exit=$?"`, 'r');
|
||||
let out = p.read('all') ?? '';
|
||||
p.close();
|
||||
let m = match(out, /exit=([0-9]+)\s*$/);
|
||||
return { code: m ? +m[1] : -1, out: replace(out, /exit=[0-9]+\s*$/, '') };
|
||||
}
|
||||
|
||||
test('without a command it knows: the usage, nothing written', () => {
|
||||
for (let args in [ '', 'frobnicate', 'install', "install ''" ]) {
|
||||
fs.unlink(JOB);
|
||||
let r = updater(args);
|
||||
eq(r.code, 2, `exit code for "${args}"`);
|
||||
ok(index(r.out, 'Usage:') == 0, `usage for "${args}"`);
|
||||
ok(index(r.out, 'updater install app | app@<tag>') > 0, `the commands for "${args}"`);
|
||||
ok(!fs.access(JOB), `no job for "${args}"`);
|
||||
}
|
||||
});
|
||||
|
||||
test('asked for help: the usage, exit 0', () => {
|
||||
for (let args in [ '-h', '--help', 'help' ]) {
|
||||
let r = updater(args);
|
||||
eq(r.code, 0, `exit code for "${args}"`);
|
||||
ok(index(r.out, 'Usage:') == 0, `usage for "${args}"`);
|
||||
}
|
||||
});
|
||||
@@ -18,6 +18,38 @@ test('valid_name', () => {
|
||||
ok(!util.valid_name('a\tb'), 'control character');
|
||||
});
|
||||
|
||||
test('valid_device_name', () => {
|
||||
eq(util.DEVICE_NAME_MAX, 20, 'the limit');
|
||||
ok(util.valid_device_name('9999999999999999999'), '19 characters');
|
||||
ok(util.valid_device_name('99999999999999999999'), '20 characters');
|
||||
ok(!util.valid_device_name('999999999999999999999'), '21 characters');
|
||||
ok(util.valid_device_name('Kitchen iPad'), 'letters and a space');
|
||||
ok(util.valid_device_name('my-pc_2.home'), 'dash, underscore and dot');
|
||||
ok(util.valid_device_name('Мой ноутбук'), 'Cyrillic');
|
||||
ok(util.valid_device_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛ'), '20 Cyrillic letters (40 bytes) are 20 characters');
|
||||
ok(!util.valid_device_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛД'), '21 Cyrillic letters');
|
||||
ok(util.valid_device_name('Ordinateur de Zoé'), 'Latin with an accent');
|
||||
ok(util.valid_device_name('客厅电视'), 'Chinese');
|
||||
ok(util.valid_device_name('Ελένη'), 'Greek');
|
||||
ok(!util.valid_device_name('Phone 📱'), 'emoji');
|
||||
ok(!util.valid_device_name('Офис™'), 'trade mark sign');
|
||||
ok(!util.valid_device_name('«Дом»'), 'guillemets');
|
||||
ok(!util.valid_device_name('a\u200bb'), 'zero-width space');
|
||||
ok(!util.valid_device_name('a×b'), 'multiplication sign');
|
||||
// Raw bytes by chr(): a "\xd0" in a literal is the character Ð to some ucode releases.
|
||||
ok(!util.valid_device_name('a' + chr(0xc0) + chr(0xaf) + 'b'), 'a slash spelled long');
|
||||
ok(!util.valid_device_name('a' + chr(0xd0)), 'a character cut short');
|
||||
ok(!util.valid_device_name("Bob's iPhone"), 'apostrophe');
|
||||
ok(!util.valid_device_name('a;rm -rf /'), 'semicolon and slash');
|
||||
ok(!util.valid_device_name('$(reboot)'), 'shell');
|
||||
ok(!util.valid_device_name('a<b'), 'angle bracket');
|
||||
ok(!util.valid_device_name('a\nb'), 'newline');
|
||||
ok(!util.valid_device_name('a\u0000b'), 'NUL');
|
||||
ok(!util.valid_device_name(''), 'empty');
|
||||
ok(!util.valid_device_name(' '), 'blank');
|
||||
ok(!util.valid_device_name(null), 'null');
|
||||
});
|
||||
|
||||
test('valid_host', () => {
|
||||
ok(util.valid_host('vpn.example.com'), 'name');
|
||||
ok(util.valid_host('router'), 'single label');
|
||||
@@ -55,6 +87,76 @@ test('valid_slug and valid_key', () => {
|
||||
ok(!util.valid_key(''), 'empty');
|
||||
});
|
||||
|
||||
test('valid_key without a regex', () => {
|
||||
let k = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
|
||||
ok(util.valid_key('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop0='), 'letters');
|
||||
ok(util.valid_key('qrstuvwxyz0123456789+/qrstuvwxyz0123456789w='), 'digits, + and /');
|
||||
ok(!util.valid_key(`${k}=`), '45 characters');
|
||||
ok(!util.valid_key(substr(k, 1)), '43 characters');
|
||||
ok(!util.valid_key(replace(k, '+', '-')), 'URL-safe alphabet');
|
||||
ok(!util.valid_key(`${substr(k, 0, 20)}=${substr(k, 21)}`), 'padding inside');
|
||||
ok(!util.valid_key(`${substr(k, 0, 20)}\u0000${substr(k, 21)}`), 'NUL byte');
|
||||
ok(!util.valid_key(`${k}\u0000x`), 'NUL and more after the key');
|
||||
ok(!util.valid_key(` ${substr(k, 1)}`), 'space');
|
||||
ok(!util.valid_key(null), 'null');
|
||||
ok(!util.valid_key([ k ]), 'array');
|
||||
// The pattern it stands for, on keys changed at both ends and in the middle.
|
||||
let re = /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/;
|
||||
for (let i in [ 0, 1, 21, 41, 42, 43 ])
|
||||
for (let c in [ 'A', 'z', '0', '9', '+', '/', 'b', 'k', '=', '-', '_', ' ', '.', '\n' ]) {
|
||||
let s = `${substr(k, 0, i)}${c}${substr(k, i + 1)}`;
|
||||
eq(util.valid_key(s), match(s, re) != null, s);
|
||||
}
|
||||
});
|
||||
|
||||
test('valid_host without a regex', () => {
|
||||
ok(util.valid_host('a'), 'one character');
|
||||
ok(util.valid_host('xn--80ak6aa92e.com'), 'dashes inside a label');
|
||||
ok(util.valid_host('Router-1.LAN'), 'upper case');
|
||||
ok(!util.valid_host('example.com.'), 'trailing dot');
|
||||
ok(!util.valid_host('.example.com'), 'leading dot');
|
||||
ok(!util.valid_host('a-.example.com'), 'dash ending a label');
|
||||
ok(!util.valid_host('under_score.example'), 'underscore');
|
||||
ok(!util.valid_host('example.com\u0000x'), 'NUL byte');
|
||||
// The pattern it stands for (and the address checks after it), on names with
|
||||
// each character replaced, removed or with one inserted before it.
|
||||
let re = /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
||||
let old = (s) => length(s) <= 253 && (match(s, re) != null || util.ip2int(s) != null || util.is_ip6(s));
|
||||
let label = replace(sprintf('%63s', ''), ' ', 'b');
|
||||
for (let h in [ 'vpn.example.com', 'a.b-c.d', `${label}.x`, `x.${label}`, '203.0.113.7', '2001:db8::1' ]) {
|
||||
let at = [];
|
||||
for (let i = 0; i <= length(h); i++)
|
||||
if (length(h) < 20 || i < 2 || i > length(h) - 3 || (i > 60 && i < 66))
|
||||
push(at, i);
|
||||
for (let i in at)
|
||||
for (let c in [ 'a', 'Z', '0', '-', '.', '_', ' ', '*', ':', '\n', '' ]) {
|
||||
let s = `${substr(h, 0, i)}${c}${substr(h, i + 1)}`, t = `${substr(h, 0, i)}${c}${substr(h, i)}`;
|
||||
eq(util.valid_host(s), old(s), s);
|
||||
eq(util.valid_host(t), old(t), t);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('valid_iface without a regex', () => {
|
||||
ok(util.valid_iface('wan'), 'wan');
|
||||
ok(util.valid_iface('lan.100'), 'dot');
|
||||
ok(util.valid_iface('@wan6'), 'alias');
|
||||
ok(!util.valid_iface(''), 'empty');
|
||||
ok(!util.valid_iface(replace(sprintf('%33s', ''), ' ', 'a')), '33 characters');
|
||||
ok(!util.valid_iface('wan\u0000x'), 'NUL byte');
|
||||
ok(!util.valid_iface(null), 'null');
|
||||
ok(!util.valid_iface([ 'wan' ]), 'array');
|
||||
// The pattern it stands for, as above.
|
||||
let re = /^[A-Za-z0-9_.@-]{1,32}$/;
|
||||
for (let n in [ 'wan', 'br-lan.10', 'A_z@0', replace(sprintf('%32s', ''), ' ', 'x') ])
|
||||
for (let i = 0; i <= length(n); i++)
|
||||
for (let c in [ 'a', 'Z', '9', '_', '.', '@', '-', ' ', '$', ';', '/', '\n', '' ]) {
|
||||
let s = `${substr(n, 0, i)}${c}${substr(n, i + 1)}`, t = `${substr(n, 0, i)}${c}${substr(n, i)}`;
|
||||
eq(util.valid_iface(s), match(s, re) != null, s);
|
||||
eq(util.valid_iface(t), match(t, re) != null, t);
|
||||
}
|
||||
});
|
||||
|
||||
test('ip2int / int2ip / cidr_any', () => {
|
||||
eq(util.ip2int('10.9.0.1'), 168361985, 'ip2int');
|
||||
eq(util.int2ip(168361985), '10.9.0.1', 'int2ip');
|
||||
@@ -85,6 +187,40 @@ test('parse_cidr', () => {
|
||||
ok(!util.in_cidr('10.9.1.1', util.parse_cidr('10.9.0.0/24')), 'not in_cidr');
|
||||
});
|
||||
|
||||
test('parse_cidr and cidr_any share one pattern', () => {
|
||||
// The patterns each had, on networks changed at each character.
|
||||
let old_any = (s) => {
|
||||
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = util.ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
|
||||
if (ip == null || prefix > 32)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
return { net: ip - ip % size, prefix, size, ip };
|
||||
};
|
||||
let old_cidr = (s) => {
|
||||
let m = match(s ?? '', /^([0-9.]+)\/([0-9]+)$/);
|
||||
if (!m)
|
||||
return null;
|
||||
let ip = util.ip2int(m[1]), prefix = +m[2];
|
||||
if (ip == null || prefix < 8 || prefix > 30)
|
||||
return null;
|
||||
let size = 1 << (32 - prefix);
|
||||
let net = ip - ip % size;
|
||||
return { net, prefix, size, first: net + 1, last: net + size - 2, ip };
|
||||
};
|
||||
for (let n in [ '10.9.0.0/24', '192.168.1.77/30', '0.0.0.0/8', '10.0.0.5', '1.2.3.4/32', '//', '' ])
|
||||
for (let i = 0; i <= length(n); i++)
|
||||
for (let c in [ '0', '9', '.', '/', ' ', 'a', '-', '\n', '' ]) {
|
||||
let s = `${substr(n, 0, i)}${c}${substr(n, i + 1)}`, t = `${substr(n, 0, i)}${c}${substr(n, i)}`;
|
||||
eq(util.parse_cidr(s), old_cidr(s), s);
|
||||
eq(util.parse_cidr(t), old_cidr(t), t);
|
||||
eq(util.cidr_any(s), old_any(s), s);
|
||||
eq(util.cidr_any(t), old_any(t), t);
|
||||
}
|
||||
});
|
||||
|
||||
test('cloudflare_ip', () => {
|
||||
ok(util.cloudflare_ip('104.16.1.1'), 'v4 range');
|
||||
ok(util.cloudflare_ip('2606:4700::1'), 'v6 range');
|
||||
@@ -140,3 +276,45 @@ test('text: ulength, ucut, translit, host_label, tunnel_name', () => {
|
||||
eq(util.host_label('!!!'), 'device', 'nothing left');
|
||||
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
|
||||
});
|
||||
|
||||
test('host_label, tunnel_name, slugify: dashes trimmed without a regex', () => {
|
||||
// What they were with the dash patterns and the device-name regex, on names
|
||||
// changed at each character (names come from uci, which holds no NUL byte).
|
||||
let old_label = (s) => {
|
||||
let l = replace(lc(util.translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
|
||||
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
|
||||
return l || 'device';
|
||||
};
|
||||
let old_tunnel = (s) => {
|
||||
let l = replace(util.translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
|
||||
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
|
||||
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
|
||||
};
|
||||
let old_slug = (s) => {
|
||||
let out = lc(util.translit(trim(`${s ?? ''}`)));
|
||||
out = replace(out, /[^a-z0-9]+/g, '-');
|
||||
out = replace(out, /^-+|-+$/g, '');
|
||||
return substr(out, 0, 32) || 'user';
|
||||
};
|
||||
let same = (s) => {
|
||||
eq(util.host_label(s), old_label(s), s);
|
||||
eq(util.tunnel_name(s), old_tunnel(s), s);
|
||||
eq(util.slugify(s), old_slug(s), s);
|
||||
};
|
||||
let long = replace(sprintf('%13s', ''), ' ', 'x');
|
||||
for (let n in [ 'Outline Home', '--a--b--', ' (My VPN)! ', 'Дом у моря', `${long}-yz`, `${long}y-z`,
|
||||
`${long}${long}${long}-ab`, `${replace(sprintf('%31s', ''), ' ', 'q')}--r`, '-', '' ])
|
||||
for (let i = 0; i <= length(n); i++)
|
||||
for (let c in [ 'a', 'Z', '0', '-', ' ', '!', '.', '_', 'Ж', '\n', '' ]) {
|
||||
same(`${substr(n, 0, i)}${c}${substr(n, i + 1)}`);
|
||||
same(`${substr(n, 0, i)}${c}${substr(n, i)}`);
|
||||
}
|
||||
// Windows device names in any case, and their neighbours.
|
||||
for (let b in [ 'con', 'prn', 'aux', 'nul', 'com', 'lpt', 'co', 'conx' ])
|
||||
for (let d in [ '', '0', '1', '5', '9', 'x', '10', '-1', ' 2' ]) {
|
||||
same(`${b}${d}`);
|
||||
same(uc(`${b}${d}`));
|
||||
same(`${uc(substr(b, 0, 1))}${substr(b, 1)}${d}`);
|
||||
}
|
||||
same(null);
|
||||
});
|
||||
@@ -31,8 +31,29 @@ test('month_days', () => {
|
||||
days[day_key_ago(n)] = [ 100, 100 ];
|
||||
let s = view.month_days({ days });
|
||||
eq(length(s), n, 'one bar a day, from the 1st to today');
|
||||
eq(s[n - 1], 12, 'today last, received and sent together');
|
||||
eq(s[0], n > 1 ? 3 : 12, 'the 1st first');
|
||||
eq(s[n - 1], [ 5, 7 ], 'today last, received and sent apart');
|
||||
eq(s[0], n > 1 ? [ 1, 2 ] : [ 5, 7 ], 'the 1st first');
|
||||
eq(length(view.month_days(null)), n, 'no usage yet: zeros');
|
||||
eq(view.month_days(null)[0], 0, 'a day without traffic is zero');
|
||||
eq(view.month_days(null)[0], [ 0, 0 ], 'a day without traffic is zero both ways');
|
||||
eq(view.spark({ days }, 1), [ [ 5, 7 ] ], 'the week the same way, today last');
|
||||
});
|
||||
|
||||
// What the set-up sheet reads off a device: the watcher's state, or without the agent a session that lives.
|
||||
test('device_view: set-up state', () => {
|
||||
let m = {
|
||||
settings: { hostnames: false },
|
||||
servers: { s_1: { id: 's_1', keepalive: 25, obf: {} } },
|
||||
people: { p_1: { id: 'p_1', server: 's_1', devices: [ 'd_1' ] } },
|
||||
devices: { d_1: { id: 'd_1', person: 'p_1', kind: 'phone', public_key: 'K1', private_key: 'x', mtu: 0, keepalive: null } },
|
||||
_reconnect: {}, _issued: {},
|
||||
};
|
||||
let hs = time() - 10;
|
||||
let peers = { K1: { ifname: 'awga', endpoint: '203.0.113.7:4000', handshake: hs, rx: 100, tx: 100 } };
|
||||
let usage = { devices: {}, people: {} };
|
||||
let watched = { peers, presence: { online: { d_1: true } }, windows: {}, link: {}, setup: { d_1: { state: 'nodata', since: hs + 15 } } };
|
||||
eq(view.device_view(m, m.devices.d_1, usage, watched).setup, { state: 'nodata', since: hs + 15 }, 'the watcher\'s');
|
||||
eq(view.device_view(m, m.devices.d_1, usage, { ...watched, setup: {} }).setup, null, 'the watcher sees nothing');
|
||||
let alone = { peers, presence: null, windows: {}, link: {}, setup: null };
|
||||
eq(view.device_view(m, m.devices.d_1, usage, alone).setup, { state: 'flowing', since: hs }, 'no agent: a live session');
|
||||
eq(view.device_view(m, m.devices.d_1, usage, { ...alone, peers: {} }).setup, null, 'no agent, not online: nothing');
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
node_modules/
|
||||
coverage/
|
||||
package-lock.json
|
||||
src/portal/fonts/
|
||||
src/admin/styles/*.css
|
||||
dist/
|
||||
@@ -31,7 +31,9 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as prettier from 'prettier';
|
||||
import ts from 'typescript';
|
||||
import * as ts from 'typescript/unstable/ast';
|
||||
import { createVirtualFileSystem } from 'typescript/unstable/fs';
|
||||
import { API } from 'typescript/unstable/sync';
|
||||
import { keyOf, parsePo, pluralForms, translated, writePo, type Entry, type Po } from './po.ts';
|
||||
|
||||
const WEB = path.resolve(import.meta.dirname, '..');
|
||||
@@ -149,14 +151,39 @@ class Errors {
|
||||
}
|
||||
|
||||
function isFunctionLike(n: ts.Node): boolean {
|
||||
return ts.isFunctionLike(n) || ts.isPropertyDeclaration(n) || ts.isClassStaticBlockDeclaration(n);
|
||||
return ts.isFunctionLikeDeclaration(n) || ts.isPropertyDeclaration(n) || ts.isClassStaticBlockDeclaration(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* The syntax trees of the files, parsed in one run by TypeScript 7 (its JS API
|
||||
* drives the native compiler, tsgo). They go to it as a virtual project, ucode
|
||||
* as JavaScript: nothing else is read, no import followed, no type checked.
|
||||
*/
|
||||
function parseAll(files: string[]): Map<string, ts.SourceFile> {
|
||||
const name = (f: string) => (f.endsWith('.ts') ? f : `${f}.js`);
|
||||
const config = '/dawnline-i18n/tsconfig.json';
|
||||
const vfs: Record<string, string> = {
|
||||
[config]: JSON.stringify({ compilerOptions: { allowJs: true, noLib: true, noResolve: true, types: [] }, files: files.map(name) }),
|
||||
};
|
||||
for (const f of files) vfs[name(f)] = fs.readFileSync(f, 'utf8');
|
||||
const api = new API({ cwd: WEB, fs: createVirtualFileSystem(vfs) });
|
||||
try {
|
||||
const program = api.updateSnapshot({ openProjects: [config] }).getProject(config)?.program;
|
||||
if (!program) throw new Error('TypeScript did not open the virtual project');
|
||||
return new Map(
|
||||
files.map((f) => {
|
||||
const sf = program.getSourceFile(name(f));
|
||||
if (!sf) throw new Error(`TypeScript did not parse ${rel(f)}`);
|
||||
return [f, sf];
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
api.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Every translation call in one file. */
|
||||
function scan(file: string, lazy: boolean, logs: boolean, errors: Errors, out: Found[]) {
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
const kind = file.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS;
|
||||
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
|
||||
function scan(file: string, sf: ts.SourceFile, lazy: boolean, logs: boolean, errors: Errors, out: Found[]) {
|
||||
const wrapper = WRAPPERS.has(file);
|
||||
const visit = (node: ts.Node) => {
|
||||
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && CALLS[node.expression.text] && !wrapper) {
|
||||
@@ -201,7 +228,7 @@ function scan(file: string, lazy: boolean, logs: boolean, errors: Errors, out: F
|
||||
out.push(e);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
node.forEachChild(visit);
|
||||
};
|
||||
visit(sf);
|
||||
}
|
||||
@@ -213,9 +240,9 @@ function scanMenu(file: string, out: Found[]) {
|
||||
}
|
||||
|
||||
/** One catalog's strings, deduplicated and sorted (by code unit: the same order on every machine). */
|
||||
function collect(spec: CatalogSpec, errors: Errors): Entry[] {
|
||||
function collect(spec: CatalogSpec, trees: Map<string, ts.SourceFile>, errors: Errors): Entry[] {
|
||||
const found: Found[] = [];
|
||||
for (const f of spec.sources()) scan(f, spec.lazy(f), !!spec.logs, errors, found);
|
||||
for (const f of spec.sources()) scan(f, trees.get(f)!, spec.lazy(f), !!spec.logs, errors, found);
|
||||
for (const f of spec.menus?.() ?? []) scanMenu(f, found);
|
||||
const byKey = new Map<string, Found>();
|
||||
for (const e of found) {
|
||||
@@ -316,7 +343,8 @@ async function main() {
|
||||
}
|
||||
const usedDrafts = new Set<string>();
|
||||
|
||||
const collected = CATALOGS.map((spec) => ({ spec, entries: collect(spec, errors) }));
|
||||
const trees = parseAll([...new Set(CATALOGS.flatMap((spec) => spec.sources()))]);
|
||||
const collected = CATALOGS.map((spec) => ({ spec, entries: collect(spec, trees, errors) }));
|
||||
const only = opt.only.map((f) => rel(path.resolve(f)));
|
||||
const under = (r: string) => only.some((o) => r === o || r.startsWith(`${o}/`));
|
||||
// Linting some files: the problems of those (other files may be half-way through a change).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dawnline-web",
|
||||
"version": "0.11.0",
|
||||
"version": "0.16.0",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
@@ -12,18 +12,27 @@
|
||||
"test": "vitest run",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"ci": "npm run format:check && npm run typecheck && npm run i18n:check && npm run test && npm run build",
|
||||
"lint": "oxlint --deny-warnings",
|
||||
"knip": "knip",
|
||||
"ci": "npm run format:check && npm run typecheck && npm run lint && npm run knip && npm run i18n:check && npm run test && npm run build",
|
||||
"i18n": "node i18n/extract.ts",
|
||||
"i18n:check": "node i18n/extract.ts --check"
|
||||
},
|
||||
"dependencies": {
|
||||
"qrcode-generator": "1.4.4"
|
||||
"qrcode-generator": "2.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "22.20.5",
|
||||
"prettier": "3.6.2",
|
||||
"tsup": "8.5.0",
|
||||
"typescript": "5.9.3",
|
||||
"vitest": "3.2.4"
|
||||
"@types/node": "26.6.5",
|
||||
"esbuild": "0.28.2",
|
||||
"knip": "6.43.0",
|
||||
"oxlint": "1.89.0",
|
||||
"prettier": "3.9.10",
|
||||
"tsup": "9.0.0",
|
||||
"typescript": "7.0.2",
|
||||
"vitest": "5.0.5"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.28.2": true,
|
||||
"fsevents@2.3.3": true
|
||||
}
|
||||
}
|
||||