Dawnline 0.11.0

- Russian translation. The admin pages, the LuCI menu and the router's
  messages (errors, Health checks, update steps, the service log) come in
  Russian with the new luci-i18n-dawnline-ru package, released beside the
  app. LuCI shows it when its language is Russian, or "auto" with a Russian
  browser
- The translation installs with install.sh when LuCI is in Russian (or with
  --lang ru), follows every Dawnline update and rollback, and can be added
  or removed in Components → Dawnline → Translation
- The portal speaks the visitor's language: it opens in the system's
  language and switches between English and Russian in place, from the
  language pill beside its QR code. It carries its own translation and needs
  no package
- Set-up steps quote the apps' own menus word for word, in Russian too:
  AmneziaVPN is "+ → Insert → Continue" (it has no "Add server"), and the
  Mac and Windows menus of WireGuard and AmneziaWG have their real names
- Questions in the portal (Reconnect, Remove) read from the left edge and
  close with Cancel, without ×
- Numbers, sizes and dates follow the page's language. A server that can't
  start says why in one sentence; event details and service log lines read
  as whole sentences
- README in Russian (README_ru.md). rules/i18n.md: how strings are written
  and translated; CI checks the catalogs (npm run i18n:check)
This commit is contained in:
Aemeath committed 2026-10-20 19:33:52 +03:00
1 parent caed976e63
commit b5ff53b65e
173 files changed
+25645 -2823

No files matched your search

+7 -5
View File
@@ -1,8 +1,9 @@
name: Build packages
# A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk
# (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with
# both packages and sha256sums.txt, the files install.sh and the in-app updater
# A tag vX.Y.Z builds luci-app-dawnline and its translation packages
# (luci-i18n-dawnline-<lang>) as .ipk (OpenWrt 24.10, opkg) and .apk (OpenWrt
# 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with the
# packages and sha256sums.txt, the files install.sh and the in-app updater
# download. The release notes list what changed since the previous tag, from the
# commits (scripts/release-notes.sh). Run it by hand to get the packages as
# workflow artifacts only.
@@ -89,7 +90,8 @@ jobs:
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: package-${{ matrix.type }}
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }}
# The app and its translation packages (luci-i18n-dawnline-<lang>).
path: dist/luci-*-${{ needs.version.outputs.version }}.${{ matrix.type }}
if-no-files-found: error
retention-days: 7
@@ -123,7 +125,7 @@ jobs:
- name: Checksums
working-directory: release
run: |
sha256sum luci-app-dawnline-* > sha256sums.txt
sha256sum luci-* > sha256sums.txt
cat sha256sums.txt
- name: Publish the release
+10
View File
@@ -51,6 +51,15 @@ jobs:
id: types
run: npm run --silent typecheck
# The catalogs follow the code: every string collected, translated, its placeholders kept.
- name: Translations
id: i18n
run: |
if ! npm run --silent i18n:check; then
echo "::error::The translation catalogs are out of date or incomplete. Run 'npm run i18n' in web/, translate the new entries in each ru.po and commit them (rules/i18n.md)."
exit 1
fi
- name: Tests
id: tests
run: npm test
@@ -79,6 +88,7 @@ jobs:
echo "|---|---|"
echo "| Formatting | ${{ steps.format.outcome }} |"
echo "| Types | ${{ steps.types.outcome }} |"
echo "| Translations | ${{ steps.i18n.outcome }} |"
echo "| Tests | ${{ steps.tests.outcome }} |"
echo "| Bundles | ${{ steps.build.outcome }} |"
} >> "$GITHUB_STEP_SUMMARY"
+5 -3
View File
@@ -9,13 +9,15 @@ 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.
- `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/`).
## 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/` — 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`).
- `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`.
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
@@ -24,7 +26,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 test`, `npm run build` — and commit the rebuilt bundles (CI fails on a changed or new file under `package/`).
- 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/`).
- `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`).
@@ -33,6 +35,6 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
- No `Co-Authored-By` or other agent attribution in commits.
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` and `sha256sums.txt`.
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` (the app and `luci-i18n-dawnline-ru`) and `sha256sums.txt`.
- Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead.
- On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256).
+26 -7
View File
@@ -20,6 +20,8 @@
[**Quick start**](#-quick-start) &nbsp;·&nbsp; [**Live demo**](https://dawnline-demo.vercel.app) &nbsp;·&nbsp; [Features](#-features) &nbsp;·&nbsp; [How it works](#-how-it-works) &nbsp;·&nbsp; [Screenshots](#-a-closer-look) &nbsp;·&nbsp; [FAQ](#-faq) &nbsp;·&nbsp; [Development](#-development)
**English** &nbsp;·&nbsp; [Русский](README_ru.md)
</div>
<br>
@@ -124,6 +126,13 @@ follows a modern design.
<p>Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🌐 English and Russian</h3>
<p>The portal follows the visitor's language and switches in its header. The admin pages and the router's messages come in Russian with the <code>luci-i18n-dawnline-ru</code> package.</p>
</td>
<td valign="top"></td>
</tr>
</table>
## 🧩 How it works
@@ -187,7 +196,8 @@ The installer checks the firmware, the clock, free space and DNS, lets you pick
a release (the latest is the default), shows the plan and asks before it
changes anything. It downloads the package for your package manager, checks it
against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
missing, then installs Dawnline and checks that LuCI can reach it.
missing, then installs Dawnline (with its Russian translation when LuCI is in
Russian) and checks that LuCI can reach it.
> [!NOTE]
> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
@@ -208,6 +218,7 @@ wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luc
sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
sh /tmp/dawnline-install.sh --lang ru # with the admin's Russian translation
```
| Option | |
@@ -216,8 +227,9 @@ sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov], then [2Grey] (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same |
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov], then [2Grey] (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Components**). `DAWNLINE_AWG` does the same |
| `--no-awg` | Same as `--awg skip` |
| `--lang auto\|ru\|none` | The admin's translation, `luci-i18n-dawnline-<lang>`: `auto` (the default) adds it when LuCI is set to that language or has its LuCI translation; `none` adds none. An installed one is always kept up to date. Later: **Dawnline → Components → Translation**. `DAWNLINE_LANG` does the same |
</details>
@@ -248,9 +260,12 @@ opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # Open
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
```
The Russian translation is `luci-i18n-dawnline-ru-<version>` from the same
release, installed the same way after the app (then `/etc/init.d/uhttpd restart`).
</details>
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Updates</kbd>, or run the installer
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Components</kbd>, or run the installer
again. Settings, keys and history are kept, and a backup is made first.
### Remove
@@ -374,7 +389,9 @@ package/luci-app-dawnline/
root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets
root/usr/bin/dawnline command line (`dawnline help`)
htdocs/ LuCI views and the generated module dawnline/app.js
po/ the admin's string catalog (dawnline.pot, ru/dawnline.po)
web/ TypeScript sources of the admin UI and the portal
web/i18n/ catalog tools: collect strings, merge .po files, compile .lmo
build/Dockerfile package build with the OpenWrt SDK
scripts/ build, deploy and check scripts
```
@@ -383,7 +400,8 @@ scripts/ build, deploy and check scripts
cd web
npm ci
npm run format # Prettier
npm run ci # format check, types, tests, minified bundles
npm run ci # format check, types, 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
@@ -393,9 +411,10 @@ scripts/capture-screenshots.mjs --demo # README screenshots from a router, a d
scripts/frame-screenshots.py # frame them for this README
```
The web bundles are committed: CI fails when they are out of date. Pushing a
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK
and publishes a release with `sha256sums.txt`.
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`
(matching `PKG_VERSION`) builds the packages and their translations with the
OpenWrt SDK and publishes a release with `sha256sums.txt`.
---
+431
View File
@@ -0,0 +1,431 @@
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
</picture>
<h1>Dawnline</h1>
**Ваш роутер на OpenWrt как личный VPN для тех, кого вы выберете.**
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Последний релиз" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Загрузки" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Лицензия" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<br>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 и 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
[**Быстрый старт**](#-быстрый-старт) &nbsp;·&nbsp; [**Демо**](https://dawnline-demo.vercel.app) &nbsp;·&nbsp; [Возможности](#-возможности) &nbsp;·&nbsp; [Как это работает](#-как-это-работает) &nbsp;·&nbsp; [Скриншоты](#-как-это-выглядит) &nbsp;·&nbsp; [Вопросы](#-вопросы-и-ответы) &nbsp;·&nbsp; [Разработка](#-разработка)
[English](README.md) &nbsp;·&nbsp; **Русский**
</div>
<br>
Dawnline запускает сервер [AmneziaWG] на вашем роутере с OpenWrt и даёт каждому,
кого вы пригласите, **личную ссылку**. По ней человек **сам добавляет свои
телефоны и компьютеры** и подключается через AmneziaVPN, AmneziaWG или WireGuard.
Вы решаете, **что ему доступно** (домашняя сеть, интернет или и то и другое), и
**на какой срок, сколько трафика и в какие часы**.
<p align="center">
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
<br>
<sub>Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился.
<a href="https://dawnline-demo.vercel.app"><b>Попробуйте в демо</b></a>: ничего не устанавливается и никуда не подключается.</sub>
</p>
## 💡 Почему Dawnline?
Обычно, чтобы поделиться домашним VPN, приходится вручную делать файл
конфигурации, отправлять его в мессенджере и надеяться, что дальше он никуда не
уйдёт. Dawnline делает наоборот:
| | VPN вручную | С Dawnline |
|---|---|---|
| **Настройка устройства** | Вы делаете конфиг и отправляете его | Человек добавляет устройство сам по своей ссылке |
| **Кому что можно** | Всем одно и то же | Дом, интернет или и то и другое, для каждого своё |
| **Конец доступа** | Найти и удалить его пиры | Дата, лимит трафика или один клик |
| **Что происходит** | Читать `wg show` | Кто в сети, трафик, места, журнал |
| **Когда что-то ломается** | Узнаёте от людей | Автовосстановление замечает и чинит |
Это преемник [Liminal]: та же идея, перестроенная вокруг людей, а не пиров, с
личным порталом, лимитами, трафиком в реальном времени и современной админкой
в LuCI.
## 🚀 Быстрый старт
1. **Установите** на роутер (установщик спрашивает, прежде чем что-то менять):
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
2. **Настройте** в LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, дальше по
мастеру. Он предложит порт, публичный адрес и сети.
3. **Пригласите** человека: <kbd>Добавить человека</kbd>, затем отправьте ему
ссылку или карточку приглашения с QR-кодом. Остальное он сделает сам.
> [!TIP]
> Если портал за Cloudflare, дайте ему порт, который Cloudflare проксирует:
> 2053, 2083, 2087, 2096 или 8443.
## ✨ Возможности
<table>
<tr>
<td width="50%" valign="top">
<h3>🔗 Ссылка вместо аккаунта</h3>
<p>Три слова, например <code>vpn.example.com/kamiro-telosu-bavine</code>. Ссылка и есть ключ: без регистрации и пароля, а новая ссылка сразу отключает старую.</p>
</td>
<td width="50%" valign="top">
<h3>📱 Свои устройства</h3>
<p>Люди сами добавляют, переименовывают и удаляют устройства в пределах лимита. При добавлении портал ведёт по шагам: нужное приложение, затем QR-код, ссылка, ключ или файл.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>👥 Люди, а не пиры</h3>
<p>Карточка на каждого человека: устройства, кто в сети, трафик, дата окончания и лимит. Фильтры по тем, кто требует внимания или на паузе.</p>
</td>
<td valign="top">
<h3>🧭 Кому что доступно</h3>
<p>Домашняя сеть, интернет или и то и другое; только часть домашних сетей или устройств (NAS, Home Assistant). Семья видит семью, гости видят гостей.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>⏳ Лимиты</h3>
<p>Даты окончания, лимит трафика на месяц или за всё время, часы доступа, кнопка паузы. Изменения применяются сразу и не обрывают подключения остальных.</p>
</td>
<td valign="top">
<h3>🕶️ Маскировка</h3>
<p>Пресеты, которые мешают распознать и заблокировать VPN-трафик, и что каждый из них требует от приложений.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🏠 Интернет как у домашних устройств</h3>
<p>Устройства людей выходят в интернет так же, как домашние, поэтому ваши прокси, фильтры рекламы и DNS работают и для них.</p>
</td>
<td valign="top">
<h3>🗺️ Обзор и места</h3>
<p>Кто в сети и с чего, скорость сейчас, последние 30 дней и карта, откуда подключаются, с точностью до города.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🩺 Чинит себя сам</h3>
<p>Проверки состояния с исправлением в один клик и автовосстановление, которое каждую минуту проверяет туннели, правила доступа и портал и чинит их.</p>
</td>
<td valign="top">
<h3>📦 Обновления и резервные копии</h3>
<p>Dawnline и AmneziaWG, собранный под вашу прошивку, в одном месте; ночные резервные копии, экспорт и импорт для переезда на другой роутер.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🌐 Английский и русский</h3>
<p>Портал подстраивается под язык посетителя и переключается в шапке. Админка и сообщения роутера на русском с пакетом <code>luci-i18n-dawnline-ru</code>.</p>
</td>
<td valign="top"></td>
</tr>
</table>
## 🧩 Как это работает
```mermaid
flowchart LR
you(["🛠️ Вы, в LuCI"]) -- "добавляете человека" --> link["🔗 Его ссылка"]
link -- "он открывает её" --> portal["📱 Его портал"]
portal -- "добавляет устройство" --> app["Приложение и подключение"]
app == "туннель AmneziaWG" ==> router["🌅 Dawnline<br>на вашем роутере"]
router -- "если разрешено" --> home["🏠 Домашняя сеть"]
router -- "если разрешено" --> net["🌍 Интернет"]
```
1. **Вы добавляете человека** в LuCI и выбираете, что ему доступно, лимит
устройств, дату окончания или лимит трафика.
2. **Он открывает свою ссылку** на любом устройстве. Портал только его: там его
устройства и его доступ; доступ и лимиты меняете только вы.
3. **Он добавляет устройство.** Портал подсказывает приложение для его системы и
передаёт подключение; роутер выдаёт каждому устройству свои ключи.
4. **Устройство подключается** через сервер AmneziaWG на роутере, а Dawnline
пропускает только то, что доступно этому человеку, считает его трафик и
следит за лимитами.
## 📸 Как это выглядит
<p align="center">
<img src="docs/screenshots/overview.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
<br>
<sub><b>Обзор</b>: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.</sub>
</p>
<table>
<tr>
<td width="50%" valign="top">
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people.png">
<p align="center"><sub><b>Люди</b>: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.</sub></p>
</td>
<td width="50%" valign="top">
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person.png">
<p align="center"><sub><b>Человек</b>: его устройства, трафик, места и лимиты.</sub></p>
</td>
</tr>
</table>
## 📋 Требования
| | Что нужно Dawnline |
|---|---|
| **OpenWrt** | 24.10 (opkg, `.ipk`) или 25.12 (apk, `.apk`) |
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: если их нет, установщик поставит сборку для вашей прошивки |
| **Свободная флеш-память** | около 2 МБ |
## 📥 Установка
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
Установщик проверяет прошивку, часы, свободное место и DNS, даёт выбрать релиз
(по умолчанию последний), показывает план и спрашивает, прежде чем что-то
менять. Он скачивает пакет для вашего менеджера пакетов, сверяет его с
`sha256sums.txt`, ставит AmneziaWG для вашей прошивки, если его нет, затем
ставит Dawnline (с русским переводом, если LuCI на русском) и проверяет, что
LuCI его видит.
> [!NOTE]
> Прежде чем что-то менять, он сохраняет `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
> и состояние служб в `/etc/dawnline/installer-backups/` (хранятся три последние
> копии) и возвращает их, если какой-то шаг не удался. Пакеты не откатываются:
> чтобы вернуться к старому релизу, запустите установщик с `--tag`. Всё, что он
> делает, записывается в `/tmp/dawnline-install.log`.
<details>
<summary><b>Параметры установщика</b></summary>
<br>
С параметрами его нужно сначала скачать:
```sh
wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh
sh /tmp/dawnline-install.sh --dry-run # всё проверить, ничего не менять
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # конкретный релиз, без вопросов
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG от 2Grey
sh /tmp/dawnline-install.sh --lang ru # с русским переводом админки
```
| Параметр | |
|---|---|
| `-y`, `--yes` | Без вопросов: последний релиз (или `--tag`) и рекомендуемые варианты |
| `-n`, `--dry-run` | Проверить систему, найти, скачать и проверить релиз; ничего не менять |
| `-v`, `--verbose` / `-q`, `--quiet` | Подробнее / только предупреждения и ошибки |
| `--tag X.Y.Z` | Конкретный релиз (`sh install.sh 0.3.1` тоже работает) |
| `--awg auto\|slava\|grey\|skip` | Откуда брать AmneziaWG, если его нет: [Slava-Shchipunov], затем [2Grey] (`auto`, по умолчанию), только один из них или вообще не ставить (потом можно в **Dawnline → Компоненты**). То же самое делает `DAWNLINE_AWG` |
| `--no-awg` | То же, что `--awg skip` |
| `--lang auto\|ru\|none` | Перевод админки, `luci-i18n-dawnline-<язык>`: `auto` (по умолчанию) ставит его, если LuCI настроен на этот язык или в нём стоит перевод LuCI на него; `none` не ставит. Уже установленный перевод всегда обновляется вместе с Dawnline. Позже: **Dawnline → Компоненты → Перевод**. То же самое делает `DAWNLINE_LANG` |
</details>
<details>
<summary><b>Если GitHub медленный или заблокирован</b></summary>
<br>
Установщик сам повторяет загрузки через `ghfast.top` и `gh-proxy.com`. Чтобы
скачать сам установщик через зеркало:
```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
</details>
<details>
<summary><b>Установка вручную</b></summary>
<br>
Из [релиза](https://github.com/tickcount/luci-app-dawnline/releases):
```sh
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
```
Русский перевод: `luci-i18n-dawnline-ru-<версия>` из того же релиза, ставится
так же, после приложения (затем `/etc/init.d/uhttpd restart`).
</details>
**Обновление**: в <kbd>Dawnline</kbd> › <kbd>Компоненты</kbd> или повторным
запуском установщика. Настройки, ключи и история сохраняются, перед обновлением
делается резервная копия.
### Удаление
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
```
Деинсталлятор сохраняет конфигурацию в `/etc/dawnline/backups`, запускает
удаление средствами самого Dawnline (как <kbd>Настройки</kbd> › <kbd>Удалить
Dawnline с этого роутера</kbd>), удаляет пакет и подчищает остатки. После
повторной установки Dawnline восстановите копию в <kbd>Настройки</kbd> ›
<kbd>Резервные копии</kbd>.
> [!IMPORTANT]
> AmneziaWG остаётся установленным: его могут использовать другие туннели.
> Чтобы удалить и его, добавьте `--remove-awg`.
<details>
<summary><b>Параметры деинсталлятора</b></summary>
<br>
С параметрами его нужно сначала скачать:
```sh
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
sh /tmp/dawnline-uninstall.sh --dry-run
```
| Параметр | |
|---|---|
| `-y`, `--yes` | Не спрашивать подтверждения |
| `-p`, `--purge` | Удалить также конфигурацию, ключи, историю и все резервные копии (`/etc/config/dawnline`, `/etc/dawnline`); копия не делается |
| `--remove-awg` | Удалить также AmneziaWG, если его не использует другой интерфейс (`--keep-awg`, по умолчанию, оставляет его) |
| `-n`, `--dry-run` | Показать, что будет удалено; ничего не менять |
Вручную: <kbd>Настройки</kbd> › <kbd>Удалить Dawnline с этого роутера</kbd>
(резервная копия сохраняется), затем `opkg remove luci-app-dawnline` или
`apk del luci-app-dawnline`.
</details>
## ❓ Вопросы и ответы
<details>
<summary><b>Какими приложениями пользуются люди?</b></summary>
<br>
AmneziaVPN или AmneziaWG на телефонах и компьютерах, а обычный WireGuard, если
маскировка выключена. Портал показывает каждому приложение для его системы и
как добавить в нём подключение.
</details>
<details>
<summary><b>Что делать, если человек потерял ссылку?</b></summary>
<br>
Создайте новую на его странице. Старая ссылка сразу перестанет работать; его
устройства продолжат работать, если не отметить те, что нужно удалить вместе с
ней.
</details>
<details>
<summary><b>Затрагивает ли он остальной роутер?</b></summary>
<br>
Только то, что создал сам, и `dawnline teardown` убирает всё это. Полный список:
[Что Dawnline меняет на роутере](#-что-dawnline-меняет-на-роутере).
</details>
<details>
<summary><b>Как переехать на другой роутер?</b></summary>
<br>
<kbd>Экспорт JSON</kbd> в <kbd>Настройки</kbd> › <kbd>Резервные копии</kbd> на
старом роутере, установите Dawnline на новый и импортируйте там этот файл.
</details>
<details>
<summary><b>Откуда берутся места на карте?</b></summary>
<br>
Из адреса, с которого подключается устройство: город определяется по нему и
кешируется на роутере. Это можно выключить в <kbd>Настройках</kbd>.
</details>
## 🧾 Что Dawnline меняет на роутере
Только то, что создал сам: сетевые интерфейсы с меткой `_dawnline`, секции
межсетевого экрана `dawnline_*`, таблицу nft `inet dawnline`, `/tmp/hosts/dawnline`,
сетевое пространство имён `dawnline` с двумя veth-связями (`dlx0` и `dll0`,
вторая подключена к мосту LAN и требует `kmod-veth`), правила маршрутизации для
интерфейсов туннелей с одной таблицей маршрутизации, второй экземпляр dnsmasq на
порту 5354 (`/var/etc/dawnline-dns.conf`), строку cron для проверки пульса
агента и, пока портал включён, экземпляр uhttpd для него. `dawnline teardown`
убирает всё это.
Данные хранятся в `/etc/config/dawnline` (права 0600, там приватные ключи) и в
`/etc/dawnline/` (трафик, события, выданные конфигурации, резервные копии).
Текущие счётчики живут в `/var/run/dawnline` и записываются во флеш-память не
чаще раза в час. Изменения доступа доходят до туннеля через `awg syncconf`, без
перезапуска интерфейса; `dawnline log` на роутере показывает журнал служб.
## 🧰 Разработка
```
package/luci-app-dawnline/
root/usr/share/ucode/dawnline/ библиотека на ucode: модель (core), AmneziaWG (awg), apply, live,
ops, view, loop, portal
root/usr/share/rpcd/ucode/ объект RPC luci.dawnline
root/usr/libexec/dawnline/ агент (трафик, лимиты, присутствие) и апдейтер
root/usr/share/dawnline/portal/ CGI-обёртка портала и его (минифицированные) файлы
root/usr/bin/dawnline командная строка (`dawnline help`)
htdocs/ представления LuCI и сгенерированный модуль dawnline/app.js
po/ каталог строк админки (dawnline.pot, ru/dawnline.po)
web/ исходники админки и портала на TypeScript
web/i18n/ инструменты каталогов: сбор строк, слияние .po, сборка .lmo
build/Dockerfile сборка пакетов в OpenWrt SDK
scripts/ скрипты сборки, деплоя и проверок
```
```sh
cd web
npm ci
npm run format # Prettier
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/frame-screenshots.py # оформить их для README
```
Бандлы и каталоги лежат в репозитории: CI падает, если они устарели или строка
не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
собирает пакеты и переводы в OpenWrt SDK и публикует релиз с `sha256sums.txt`.
---
<div align="center">
<sub>Сделано для OpenWrt · <a href="LICENSE">лицензия MIT</a> · <a href="#readme">Наверх ↑</a></sub>
</div>
[AmneziaWG]: https://docs.amnezia.org/
[Liminal]: https://github.com/tickcount/openwrt-liminal
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
[2Grey]: https://github.com/2Grey/awg-openwrt
+6 -2
View File
@@ -9,13 +9,17 @@ COPY package/luci-app-dawnline /builder/package/feeds/luci/luci-app-dawnline
# The SDK's default config builds every kernel module and every package in the
# feeds; turn that off and select only this package (it ships scripts and web
# files, so nothing else needs building).
# files, so nothing else needs building) and its translations: luci.mk makes
# luci-i18n-dawnline-<lang> from po/<lang> when LuCI's language <lang> is selected.
RUN make defconfig && \
sed -i -e 's/^CONFIG_ALL_KMODS=y/# CONFIG_ALL_KMODS is not set/' \
-e 's/^CONFIG_ALL_NONSHARED=y/# CONFIG_ALL_NONSHARED is not set/' \
-e 's/^CONFIG_ALL=y/# CONFIG_ALL is not set/' .config && \
echo 'CONFIG_PACKAGE_luci-app-dawnline=m' >> .config && \
for l in $(ls /builder/package/feeds/luci/luci-app-dawnline/po | grep -v '^templates$'); do \
sed -i "/CONFIG_LUCI_LANG_$l[= ]/d" .config && echo "CONFIG_LUCI_LANG_$l=y" >> .config; done && \
make defconfig && \
make package/luci-app-dawnline/compile V=s -j4 && \
mkdir -p /builder/out && \
find /builder/bin/packages -name 'luci-app-dawnline*' \( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \;
find /builder/bin/packages \( -name 'luci-app-dawnline*' -o -name 'luci-i18n-dawnline-*' \) \
\( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \;
+144 -13
View File
@@ -9,7 +9,8 @@
# sh /tmp/dawnline-install.sh [options] [version]
#
# Installs AmneziaWG built for this firmware when it is missing, then the
# Dawnline package with its dependencies from the OpenWrt feeds. Settings and
# Dawnline package with its dependencies from the OpenWrt feeds, and the admin's
# translation when LuCI speaks that language (--lang). Settings and
# keys survive reinstalls and upgrades. A recovery snapshot of the configs it
# may touch is taken first and restored if anything fails. `--help` lists the
# options.
@@ -18,6 +19,8 @@ INSTALLER_VERSION="1.0.0"
REPO="${DAWNLINE_REPO:-tickcount/luci-app-dawnline}"
PKG_NAME="luci-app-dawnline"
AWG_PKGS="kmod-amneziawg amneziawg-tools luci-proto-amneziawg"
# The admin's translations a release has: luci-i18n-dawnline-<lang>.
I18N_LANGS="ru"
CONNECT_TIMEOUT=15
METADATA_TIMEOUT=60
@@ -43,6 +46,7 @@ VERBOSE=0
QUIET=0
TAG=""
AWG_SOURCE="${DAWNLINE_AWG:-auto}"
I18N_CHOICE="${DAWNLINE_LANG:-auto}"
LOG_READY=0
TMP_DIR=""
@@ -67,6 +71,11 @@ WAS_ENABLED=0
WAS_RUNNING=0
MODE="install"
I18N_LANG=""
I18N_PKG=""
I18N_ASSET=""
I18N_FILE=""
AWG_ACTION="keep"
AWG_CANDIDATES=""
AWG_REPO=""
@@ -175,12 +184,18 @@ Usage: sh install.sh [options] [version]
grey 2Grey/awg-openwrt
skip do not install it (add it later in Dawnline → Components)
--no-awg Same as --awg skip
--lang LANG The admin's translation (luci-i18n-dawnline-LANG):
auto when LuCI is set to that language or has its
LuCI translation installed (default)
ru Russian
none add none (an installed one is kept up to date)
--version Print the installer version
-h, --help Show this help
Environment:
DAWNLINE_REPO=owner/name GitHub repository with the releases ($REPO)
DAWNLINE_AWG=SOURCE Same as --awg (the option wins)
DAWNLINE_LANG=LANG Same as --lang (the option wins)
DAWNLINE_SNAPSHOT_KEEP=N Recovery snapshots to keep (default 3)
Log: $LOG_FILE
@@ -214,6 +229,17 @@ set_awg() {
esac
}
set_lang() {
for _l in auto none $I18N_LANGS; do
[ "$1" = "$_l" ] && {
I18N_CHOICE="$1"
return 0
}
done
err "Unknown language: $1 (auto, none or one of: $I18N_LANGS)"
return 1
}
parse_args() {
while [ "$#" -gt 0 ]; do
case "$1" in
@@ -240,6 +266,15 @@ parse_args() {
;;
--awg=*) set_awg "${1#*=}" || return 2 ;;
--no-awg) AWG_SOURCE="skip" ;;
--lang)
[ "$#" -gt 1 ] || {
err "--lang needs a language (auto, none or one of: $I18N_LANGS)"
return 2
}
shift
set_lang "$1" || return 2
;;
--lang=*) set_lang "${1#*=}" || return 2 ;;
--version)
printf 'dawnline-installer %s\n' "$INSTALLER_VERSION"
exit 0
@@ -268,6 +303,7 @@ parse_args() {
return 2
fi
set_awg "$AWG_SOURCE" || return 2
set_lang "$I18N_CHOICE" || return 2
return 0
}
@@ -895,6 +931,68 @@ resolve_release() {
fi
}
lang_name() {
case "$1" in
ru) printf 'Russian' ;;
*) printf '%s' "$1" ;;
esac
}
# LuCI's language, when Dawnline has a translation for it: its setting, or with
# "auto" (the browser's) a LuCI translation that is installed (base.<lang>.lmo).
luci_lang() {
_ll="$(uci -q get luci.main.lang)"
for _l in $I18N_LANGS; do
case "$_ll" in "$_l" | "$_l"[_-]*)
printf '%s' "$_l"
return 0
;;
esac
done
case "$_ll" in '' | auto) ;; *) return 0 ;; esac
for _l in $I18N_LANGS; do
[ -f "/usr/lib/lua/luci/i18n/base.$_l.lmo" ] && {
printf '%s' "$_l"
return 0
}
done
return 0
}
# The admin's translation: an installed one is kept (it must match the app's
# version), else --lang or LuCI's own language decides.
resolve_i18n() {
I18N_LANG=""
for _l in $I18N_LANGS; do
pkg_is_installed "luci-i18n-dawnline-$_l" && I18N_LANG="$_l"
done
if [ -z "$I18N_LANG" ]; then
case "$I18N_CHOICE" in
none) ;;
auto) I18N_LANG="$(luci_lang)" ;;
*) I18N_LANG="$I18N_CHOICE" ;;
esac
fi
[ -n "$I18N_LANG" ] || return 0
I18N_PKG="luci-i18n-dawnline-$I18N_LANG"
I18N_ASSET="$I18N_PKG-$VERSION.$EXT"
_rj="$TMP_DIR/release.json"
if [ -s "$_rj" ]; then
_size="$(jsonfilter -i "$_rj" -e "@.assets[@.name='$I18N_ASSET'].size" 2>/dev/null | head -n 1)"
if [ -z "$_size" ]; then
# Releases before the translations have none.
warn "Release $VERSION has no $(lang_name "$I18N_LANG") translation: Dawnline stays in English"
I18N_LANG=""
I18N_PKG=""
I18N_ASSET=""
return 0
fi
DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + _size))
else
DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + 262144))
fi
}
# AmneziaWG packages are built per firmware version and target by the
# awg-openwrt projects: <name>_v<release>_<arch>_<target>_<subtarget>.<ext>
awg_postfix() {
@@ -981,6 +1079,11 @@ print_plan() {
downgrade) msg " Dawnline: downgrade $WAS_VERSION → $VERSION (a backup is made first)" ;;
esac
msg " Package manager: $PKG_MANAGER ($ASSET)"
if [ -n "$I18N_PKG" ]; then
msg " Translation: $(lang_name "$I18N_LANG") ($I18N_PKG)"
else
msg " Translation: none (Russian: --lang ru)"
fi
case "$AWG_ACTION" in
keep) msg " AmneziaWG: keep the installed one" ;;
skip) msg " AmneziaWG: skip (install it later from Dawnline → Components)" ;;
@@ -1011,28 +1114,37 @@ confirm() {
# ---------- download phase ----------
download_dawnline() {
# download_release_file NAME: one file of the release into $TMP_DIR, verified.
download_release_file() {
_name="$1"
_sums="$TMP_DIR/sha256sums.txt"
ASSET_FILE="$TMP_DIR/$ASSET"
# The checksum: GitHub's own (API), else the release's sha256sums.txt straight from github.com.
_want="$(asset_digest "$TMP_DIR/release.json" "$ASSET")"
_want="$(asset_digest "$TMP_DIR/release.json" "$_name")"
if [ -z "$_want" ]; then
download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || {
[ -s "$_sums" ] || download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || {
err "Download failed: sha256sums.txt (does release $VERSION exist?)"
return 1
}
_want="$(awk -v f="$ASSET" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")"
_want="$(awk -v f="$_name" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")"
[ -n "$_want" ] || {
err "sha256sums.txt has no entry for $ASSET: not installing an unverified package"
err "sha256sums.txt has no entry for $_name: not installing an unverified package"
return 1
}
fi
download "$ASSET_BASE/$ASSET" "$ASSET_FILE" "$ASSET" "$_want" || {
err "Download failed: $ASSET"
download "$ASSET_BASE/$_name" "$TMP_DIR/$_name" "$_name" "$_want" || {
err "Download failed: $_name"
return 1
}
verify_archive "$ASSET_FILE" || return 1
ok "$ASSET verified (sha256, package format)"
verify_archive "$TMP_DIR/$_name" || return 1
ok "$_name verified (sha256, package format)"
}
download_dawnline() {
download_release_file "$ASSET" || return 1
ASSET_FILE="$TMP_DIR/$ASSET"
[ -n "$I18N_ASSET" ] || return 0
download_release_file "$I18N_ASSET" || return 1
I18N_FILE="$TMP_DIR/$I18N_ASSET"
}
download_awg() {
@@ -1156,11 +1268,16 @@ install_dawnline() {
_force=0
case "$MODE" in reinstall | downgrade) _force=1 ;; esac
if [ "$DRY_RUN" -eq 1 ]; then
dry "$MODE Dawnline $VERSION ($ASSET)"
dry "$MODE Dawnline $VERSION ($ASSET${I18N_ASSET:+, $I18N_ASSET})"
return 0
fi
msg "Installing Dawnline $VERSION"
pkg_install_files dawnline "$_force" "$ASSET_FILE"
# The translation in the same transaction: it depends on this very version.
if [ -n "$I18N_FILE" ]; then
pkg_install_files dawnline "$_force" "$ASSET_FILE" "$I18N_FILE"
else
pkg_install_files dawnline "$_force" "$ASSET_FILE"
fi
}
healthcheck() {
@@ -1201,6 +1318,9 @@ healthcheck() {
if [ "$_r" != true ]; then
warn "The Dawnline agent is not running yet (see Dawnline → Diagnostics)"
fi
if [ -n "$I18N_PKG" ] && [ "$(pkg_version "$I18N_PKG")" != "$VERSION" ]; then
warn "$I18N_PKG $VERSION is not installed: Dawnline shows in English"
fi
ok "Healthcheck passed: $PKG_NAME $VERSION, LuCI backend answers"
}
@@ -1215,6 +1335,15 @@ keep_service_intent() {
return 0
}
# LuCI reads a language's catalogs once per web server process: a new or
# replaced translation needs a fresh one.
reload_luci() {
[ "$DRY_RUN" -eq 0 ] && [ -n "$I18N_FILE" ] || return 0
msg "Restarting the web server so LuCI reads the translation"
/etc/init.d/uhttpd restart >/dev/null 2>&1 ||
warn "uhttpd did not restart: the translation shows after a reboot"
}
commit_transaction() {
TX_COMMITTED=1
TX_ACTIVE=0
@@ -1328,6 +1457,7 @@ main() {
select_release
resolve_release || fail "Could not resolve the Dawnline release"
resolve_i18n
resolve_awg || fail "AmneziaWG is not available for this firmware"
check_tmp_space || fail "Not enough free memory for the downloads"
print_plan
@@ -1348,6 +1478,7 @@ main() {
healthcheck || fail "The installed Dawnline did not pass the healthcheck"
keep_service_intent
commit_transaction
reload_luci
trap on_hup HUP
_took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS))
+4 -1
View File
@@ -6,9 +6,12 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.10.0
PKG_VERSION:=0.11.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
# with the app and at its version (luci.mk would take a git revision otherwise).
PKG_PO_VERSION:=$(PKG_VERSION)-r$(PKG_RELEASE)
LUCI_TITLE:=Dawnline - AmneziaWG access server
# AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not
@@ -5,25 +5,27 @@
'require poll';
'require rpc';
'require ui';
var vi=Object.create;var Po=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var wi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var ki=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var $i=(n,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of xi(e))!yi.call(n,a)&&a!==r&&Po(n,a,{get:()=>e[a],enumerable:!(o=bi(e,a))||o.enumerable});return n};var Ci=(n,e,r)=>(r=n!=null?vi(wi(n)):{},$i(e||!n||!n.__esModule?Po(r,"default",{value:n,enumerable:!0}):r,n));var Wo=ki((Uo,Go)=>{"use strict";var jo=(function(){var n=function(C,k){var y=236,w=17,b=C,H=r[k],f=null,g=0,M=null,T=[],z={},W=function(A,N){g=b*4+17,f=(function(S){for(var O=new Array(S),_=0;_<S;_+=1){O[_]=new Array(S);for(var j=0;j<S;j+=1)O[_][j]=null}return O})(g),q(0,0),q(g-7,0),q(0,g-7),V(),I(),de(A,N),b>=7&&Q(A),M==null&&(M=F(b,H,T)),ee(M,N)},q=function(A,N){for(var S=-1;S<=7;S+=1)if(!(A+S<=-1||g<=A+S))for(var O=-1;O<=7;O+=1)N+O<=-1||g<=N+O||(0<=S&&S<=6&&(O==0||O==6)||0<=O&&O<=6&&(S==0||S==6)||2<=S&&S<=4&&2<=O&&O<=4?f[A+S][N+O]=!0:f[A+S][N+O]=!1)},Z=function(){for(var A=0,N=0,S=0;S<8;S+=1){W(!0,S);var O=a.getLostPoint(z);(S==0||A>O)&&(A=O,N=S)}return N},I=function(){for(var A=8;A<g-8;A+=1)f[A][6]==null&&(f[A][6]=A%2==0);for(var N=8;N<g-8;N+=1)f[6][N]==null&&(f[6][N]=N%2==0)},V=function(){for(var A=a.getPatternPosition(b),N=0;N<A.length;N+=1)for(var S=0;S<A.length;S+=1){var O=A[N],_=A[S];if(f[O][_]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?f[O+j][_+Y]=!0:f[O+j][_+Y]=!1}},Q=function(A){for(var N=a.getBCHTypeNumber(b),S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[Math.floor(S/3)][S%3+g-8-3]=O}for(var S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[S%3+g-8-3][Math.floor(S/3)]=O}},de=function(A,N){for(var S=H<<3|N,O=a.getBCHTypeInfo(S),_=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<6?f[_][8]=j:_<8?f[_+1][8]=j:f[g-15+_][8]=j}for(var _=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<8?f[8][g-_-1]=j:_<9?f[8][15-_-1+1]=j:f[8][15-_-1]=j}f[g-8][8]=!A},ee=function(A,N){for(var S=-1,O=g-1,_=7,j=0,Y=a.getMaskFunction(N),J=g-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var ue=0;ue<2;ue+=1)if(f[O][J-ue]==null){var xe=!1;j<A.length&&(xe=(A[j]>>>_&1)==1);var te=Y(O,J-ue);te&&(xe=!xe),f[O][J-ue]=xe,_-=1,_==-1&&(j+=1,_=7)}if(O+=S,O<0||g<=O){O-=S,S=-S;break}}},B=function(A,N){for(var S=0,O=0,_=0,j=new Array(N.length),Y=new Array(N.length),J=0;J<N.length;J+=1){var ue=N[J].dataCount,xe=N[J].totalCount-ue;O=Math.max(O,ue),_=Math.max(_,xe),j[J]=new Array(ue);for(var te=0;te<j[J].length;te+=1)j[J][te]=255&A.getBuffer()[te+S];S+=ue;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[J],De.getLength()-1),So=Ae.mod(De);Y[J]=new Array(De.getLength()-1);for(var te=0;te<Y[J].length;te+=1){var To=te+So.getLength()-Y[J].length;Y[J][te]=To>=0?So.getAt(To):0}}for(var _o=0,te=0;te<N.length;te+=1)_o+=N[te].totalCount;for(var Gn=new Array(_o),Qt=0,te=0;te<O;te+=1)for(var J=0;J<N.length;J+=1)te<j[J].length&&(Gn[Qt]=j[J][te],Qt+=1);for(var te=0;te<_;te+=1)for(var J=0;J<N.length;J+=1)te<Y[J].length&&(Gn[Qt]=Y[J][te],Qt+=1);return Gn},F=function(A,N,S){for(var O=l.getRSBlocks(A,N),_=d(),j=0;j<S.length;j+=1){var Y=S[j];_.put(Y.getMode(),4),_.put(Y.getLength(),a.getLengthInBits(Y.getMode(),A)),Y.write(_)}for(var J=0,j=0;j<O.length;j+=1)J+=O[j].dataCount;if(_.getLengthInBits()>J*8)throw"code length overflow. ("+_.getLengthInBits()+">"+J*8+")";for(_.getLengthInBits()+4<=J*8&&_.put(0,4);_.getLengthInBits()%8!=0;)_.putBit(!1);for(;!(_.getLengthInBits()>=J*8||(_.put(y,8),_.getLengthInBits()>=J*8));)_.put(w,8);return B(_,O)};z.addData=function(A,N){N=N||"Byte";var S=null;switch(N){case"Numeric":S=c(A);break;case"Alphanumeric":S=p(A);break;case"Byte":S=u(A);break;case"Kanji":S=x(A);break;default:throw"mode:"+N}T.push(S),M=null},z.isDark=function(A,N){if(A<0||g<=A||N<0||g<=N)throw A+","+N;return f[A][N]},z.getModuleCount=function(){return g},z.make=function(){if(b<1){for(var A=1;A<40;A++){for(var N=l.getRSBlocks(A,H),S=d(),O=0;O<T.length;O++){var _=T[O];S.put(_.getMode(),4),S.put(_.getLength(),a.getLengthInBits(_.getMode(),A)),_.write(S)}for(var j=0,O=0;O<N.length;O++)j+=N[O].dataCount;if(S.getLengthInBits()<=j*8)break}b=A}W(!1,Z())},z.createTableTag=function(A,N){A=A||2,N=typeof N>"u"?A*4:N;var S="";S+='<table style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: "+N+"px;",S+='">',S+="<tbody>";for(var O=0;O<z.getModuleCount();O+=1){S+="<tr>";for(var _=0;_<z.getModuleCount();_+=1)S+='<td style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: 0px;",S+=" width: "+A+"px;",S+=" height: "+A+"px;",S+=" background-color: ",S+=z.isDark(O,_)?"#000000":"#ffffff",S+=";",S+='"/>';S+="</tr>"}return S+="</tbody>",S+="</table>",S},z.createSvgTag=function(A,N,S,O){var _={};typeof arguments[0]=="object"&&(_=arguments[0],A=_.cellSize,N=_.margin,S=_.alt,O=_.title),A=A||2,N=typeof N>"u"?A*4:N,S=typeof S=="string"?{text:S}:S||{},S.Line truncated
`}return S%2&&A>0?Ae.substring(0,Ae.length-S-1)+Array(S+1).join("▀"):Ae.substring(0,Ae.length-1)};return z.createASCII=function(A,N){if(A=A||1,A<2)return pe(N);A-=1,N=typeof N>"u"?A*2:N;var S=z.getModuleCount()*A+N*2,O=N,_=S-N,j,Y,J,ue,xe=Array(A+1).join("██"),te=Array(A+1).join(" "),De="",Ae="";for(j=0;j<S;j+=1){for(J=Math.floor((j-O)/A),Ae="",Y=0;Y<S;Y+=1)ue=1,O<=Y&&Y<_&&O<=j&&j<_&&z.isDark(J,Math.floor((Y-O)/A))&&(ue=0),Ae+=ue?xe:te;for(J=0;J<A;J+=1)De+=Ae+`
`}return De.substring(0,De.length-1)},z.renderTo2dContext=function(A,N){N=N||2;for(var S=z.getModuleCount(),O=0;O<S;O++)for(var _=0;_<S;_++)A.fillStyle=z.isDark(O,_)?"black":"white",A.fillRect(O*N,_*N,N,N)},z};n.stringToBytesFuncs={default:function(C){for(var k=[],y=0;y<C.length;y+=1){var w=C.charCodeAt(y);k.push(w&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(C,k){var y=(function(){for(var b=m(C),H=function(){var I=b.read();if(I==-1)throw"eof";return I},f=0,g={};;){var M=b.read();if(M==-1)break;var T=H(),z=H(),W=H(),q=String.fromCharCode(M<<8|T),Z=z<<8|W;g[q]=Z,f+=1}if(f!=k)throw f+" != "+k;return g})(),w=63;return function(b){for(var H=[],f=0;f<b.length;f+=1){var g=b.charCodeAt(f);if(g<128)H.push(g);else{var M=y[b.charAt(f)];typeof M=="number"?(M&255)==M?H.push(M):(H.push(M>>>8),H.push(M&255)):H.push(w)}}return H}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var C=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,y=7973,w=21522,b={},H=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return b.getBCHTypeInfo=function(f){for(var g=f<<10;H(g)-H(k)>=0;)g^=k<<H(g)-H(k);return(f<<10|g)^w},b.getBCHTypeNumber=function(f){for(var g=f<<12;H(g)-H(y)>=0;)g^=y<<H(g)-H(y);return f<<12|g},b.getPatternPosition=function(f){return C[f-1]},b.getMaskFunction=function(f){switch(f){case o.PATTERN000:return function(g,M){return(g+M)%2==0};case o.PATTERN001:return function(g,M){return g%2==0};case o.PATTERN010:return function(g,M){return M%3==0};case o.PATTERN011:return function(g,M){return(g+M)%3==0};case o.PATTERN100:return function(g,M){return(Math.floor(g/2)+Math.floor(M/3))%2==0};case o.PATTERN101:return function(g,M){return g*M%2+g*M%3==0};case o.PATTERN110:return function(g,M){return(g*M%2+g*M%3)%2==0};case o.PATTERN111:return function(g,M){return(g*M%3+(g+M)%2)%2==0};default:throw"bad maskPattern:"+f}},b.getErrorCorrectPolynomial=function(f){for(var g=s([1],0),M=0;M<f;M+=1)g=g.multiply(s([1,i.gexp(M)],0));return g},b.getLengthInBits=function(f,g){if(1<=g&&g<10)switch(f){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+f}else if(g<27)switch(f){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+f}else if(g<41)switch(f){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+f}else throw"type:"+g},b.getLostPoint=function(f){for(var g=f.getModuleCount(),M=0,T=0;T<g;T+=1)for(var z=0;z<g;z+=1){for(var W=0,q=f.isDark(T,z),Z=-1;Z<=1;Z+=1)if(!(T+Z<0||g<=T+Z))for(var I=-1;I<=1;I+=1)z+I<0||g<=z+I||Z==0&&I==0||q==f.isDark(T+Z,z+I)&&(W+=1);W>5&&(M+=3+W-5)}for(var T=0;T<g-1;T+=1)for(var z=0;z<g-1;z+=1){var V=0;f.isDark(T,z)&&(V+=1),f.isDark(T+1,z)&&(V+=1),f.isDark(T,z+1)&&(V+=1),f.isDark(T+1,z+1)&&(V+=1),(V==0||V==4)&&(M+=3)}for(var T=0;T<g;T+=1)for(var z=0;z<g-6;z+=1)f.isDark(T,z)&&!f.isDark(T,z+1)&&f.isDark(T,z+2)&&f.isDark(T,z+3)&&f.isDark(T,z+4)&&!f.isDark(T,z+5)&&f.isDark(T,z+6)&&(M+=40);for(var z=0;z<g;z+=1)for(var T=0;T<g-6;T+=1)f.isDark(T,z)&&!f.isDark(T+1,z)&&f.isDark(T+2,z)&&f.isDark(T+3,z)&&f.isDark(T+4,z)&&!f.isDark(T+5,z)&&f.isDark(T+6,z)&&(M+=40);for(var Q=0,z=0;z<g;z+=1)for(var T=0;T<g;T+=1)f.isDark(T,z)&&(Q+=1);var de=Math.abs(100*Q/g/g-50)/5;return M+=de*10,M},b})(),i=(function(){for(var C=new Array(256),k=new Array(256),y=0;y<8;y+=1)C[y]=1<<y;for(var y=8;y<256;y+=1)C[y]=C[y-4]^C[y-5]^C[y-6]^C[y-8];for(var y=0;y<255;y+=1)k[C[y]]=y;var w={};return w.glog=function(b){if(b<1)throw"glog("+b+")";return k[b]},w.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return C[b]},w})();function s(C,k){if(typeof C.length>"u")throw C.length+"/"+k;var y=(function(){for(var b=0;b<C.length&&C[b]==0;)b+=1;for(var H=new Array(C.length-b+k),f=0;f<C.length-b;f+=1)H[f]=C[f+b];return H})(),w={};return w.getAt=function(b){return y[b]},w.getLength=function(){return y.length},w.multiply=function(b){for(var H=new Array(w.getLength()+b.getLength()-1),f=0;f<w.getLength();f+=1)for(var g=0;g<b.getLength();g+=1)H[f+g]^=i.gexp(i.glog(w.getAt(f))+i.glog(b.getAt(g)));return s(H,0)},w.mod=function(b){if(w.getLength() Line truncated
`)}function qi(n){let e=new Map(n.people.map(o=>[o.id,o.name])),r=new Map(n.people.flatMap(o=>o.devices.map(a=>[a.id,a.name])));return{people:e,devices:r}}function Fe(n,e,r,o="",a=[]){let i=qi(n),s=[...e.map(p=>({ts:p.ts,category:It(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
${p.detail}`:""}`,where:Bt[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,dr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ki=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],cr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Lt.map(d=>t("option",{value:d,selected:d===a?"selected":null},ut[d])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ki.map(([d,c])=>t("option",{value:d},c)));oe(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await P.logsClear({...r,category:s.value,older_days:l.value})).removed}catch(c){U(be(c),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await P.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${cr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(cr(d),"success",3e3),o()},"negative")])}function Mt(n,e,r,o){let a=n==="device"?`Clears ${r}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${r}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${r}?`,[t("p",{class:"dl-muted"},a)],[ie()," ",D("Reset",async()=>{await G(()=>P.usageClear(n,e),"Traffic history reset")&&(ae(),o())},"negative")])}function ve(n,e,r){let o=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!o.classList.contains("on");eo(o,a),r?.(a)}},t("i"));return o}function eo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,r={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let o=t("div",{class:`dl-seg${r.cls?` ${r.cls}`:""}`,role:"radiogroup","aria-label":r.label??null,"data-value":e}),a=()=>o.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===o.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)o.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==o.dataset.value&&(r.optimistic!==!1&&(o.dataset.value=i,a()),r.onChange?.(i))}},s));return a(),o}function qe(n,e,r,o={}){return t("button",{type:"button",...o,class:`dl-chipbtn${e?" on":""}${o.class?` ${o.class}`:""}`,"aria-pressed":e?"true":"false",click:r},n)}function hn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function le(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Vi={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Ji={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Yi(n){let e={};for(let[r,o]of Object.entries(Ji))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Zi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Vi[d],i=r.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Yi(o),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Qi(n){let e="";for(let r=0;r<n.length;r+=32768)e+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Zi(n,e))),a=r?await Xi(o):null;return`vpn://${Qi(a??o)}`}var ur=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Ot=n=>ur.find(e=>e.id===n),fn=n=>n.v3?"max":n.v2?"balanced":"off",jt=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,es={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},ts={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function pr(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:r<n?"on":""})))])}function gn(n,e,r,o,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ur.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[pr(l.stealth,"Stealth"),pr(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},(a?es:ts)[l.needs])])])}));return s(),i}function mr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var hr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function ns(n){let e=c=>n[c]!=null&&n[c]!=="",r=hr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=hr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).join(`
`),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),me(l,"Parameters copied")}},"Copy as config")]),d])}function fr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function os(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
`).flatMap((s,l)=>l?[`
`,fr(s,e)]:[fr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[v(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[v("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes`)]),D([v("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),me(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function rs(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,n.server),o={qr:()=>t("div",{class:"dl-qr-pane"},[an(n.conf),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),D("Copy",()=>me(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>os(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function as(n,e,r,o){let a=Ot(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await se(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>P.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function is(n,e){let r=n.st,o=le(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=le(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=le(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Ot(e.preset)?e.preset:void 0,l=s??fn(r.awg),d=D("",()=>as(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[v("reset")," Generate new values"]:[`Switch to ${Ot(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=ge("UDP port",o,()=>Rt(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));P.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=ge("MTU",a,()=>Zo(a.value,e.mtus)),h=ge("Keep-alive",i,()=>Qo(i.value));return Nt("",[mr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[jt(e.preset)?ct("warn",[t("b",{},jt(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",gn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ns(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ce("Server public key",t("span",{c Line truncated
`),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let E=r??null,R=r?.id,C,k=0,y=f=>{R!==f.id&&(R=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await P.updatesStatus().catch(()=>null);C=f?.job?.id,k=f?.now??0;let g=await P.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==C&&(E=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let w=null,b=0;for(;;){if(await ia(1e3),w=await P.updatesStatus().catch(()=>null),!w){if(++b>60)break;continue}b=0;let f=w.job;if(!f||!aa(f,R,C,k)){if(Date.now()-i>15e3)break;continue}if(y(f),E=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.join(`
`),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=oa(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=na((f.finished??w.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(w),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},E.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([D("Copy log",()=>me($.join(`
`),"Log copied")),m(!0)]),U(`${Mn[o]??"Update"}: ${E.error??"failed"}`,"error"),e.onDone?.(w),E;if(d.className="dl-pill ok",d.textContent="Finished",a&&w){let f=ra(w,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[v(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(w),f.update&&e.onUpdate){let g=w;h([m(),D(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return E}if(o==="app"&&E.to){let f=E.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let M=()=>{ui.menu?.flushCache(),location.reload()};h([m(),D("Reload now",M,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await ia(1500),(await P.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(M,800),E;return g.textContent="Services restarted. Reload the page to use the new version.",E}let H=o==="pkgs"?`Updated ${[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${E.to?` ${E.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},H)])),h([m()]),U(H,"success"),e.onDone?.(w),E}var Ds={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function sa(n,e,r,o){return!await se(`Install ${e}?`,r,"Install")||(await Vt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Tn(n){return sa("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Jt(n,e,r){return n==="awg"?Tn(r):e.length?sa(`pkgs:${e.join(",")}`,Ds[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function la(n,e){if(n==="awg")return Tn(e);let r=await G(()=>P.updatesStatus());return r?Jt(n,r.needs?.[n]??[],e):!1}var As=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Hs={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function da(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=Xr(a,o,r),h=new Set,m="",E=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),R=()=>s.detected.lan||s.saved.lan||"",C=()=>(l?s.detected.wan||s.saved.wan:d)||"",k=()=>new Map(s.devices.map(I=>[I.name,I])),y=()=>{let I=k();return[...c&&R()?[R()]:[],...[...h].filter(Q=>Q!==R())].filter(Q=>Q!==C()).map(Q=>I.get(Q)??{name:Q,nets:[],missing:!0})},w=(I,V)=>{s=I,V&&(l=I.config.auto_wan,d=I.config.wan_device||I.detected.wan||I.saved.wan||"",c=I.config.auto_lan,p=I.config.lan_like,u=I.config.mesh??(I.config.device_mesh?"all":"off"),h=new Set(I.config.lan_devices),m=E()),q()},b=async I=>{let V=await P.interfaces(o).catch(Q=>(U(Q.message,"error"),null));V&&w(V,I)};function H(I){let V=c&&I.name===R(),Q=!!I.own||!!I.master||I.name===C()||V;return V||h.has(I.name)||!Q&&(I.nets.length>0||!!I.missing)}function f(I){let V=c&&I.name===R(),Q=I.name===C(),de=!V&&h.has(I.name),B=!(!!I.own||!!I.master||Q||V)&&(I.nets.length>0||de||!!I.missing),F=(de||V)&&!I.zone&&!I.missing,ne=I.missing?"Not present right now":I.own?"This server":I.master?`Port of ${I.master}`:Q?`Internet${I.zone?` · zone ${I.zone}`:""}`:I.nets.length?I.nets.join(", "):"No IPv4 network",pe=t("button",{type:"button",class:`dl-if${de?" sel":""}${V?" auto":""}${!B&&!de&&!V?" off":""}${F?" warn":""}`,"aria-pressed":de||V?"true":"false","aria-disabled":B?null:"true",click:()=>{B&&(h.has(I.name)?h.delete(I.name):h.add(I.name),q())}},[t("span",{class:"dl-if-ic"},v(Hs[I.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},I.name),t("span",{class:"dl-if-sub"},ne)]),V?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return he(pe,()=>[t("div",{class:"dl-tip-title"},I.name),t("div",{class:"dl-muted"},[I.logical?`Interface ${I.logical}`:"No netifd interface",I.zone?` · zone ${I.zone}`:" · no firewall zone"]),I.members.length?t("div",{class:"dl-muted"},`Ports: ${I.members.join(", ")}`):"",I.nets.length?t("div",{class:"dl-mono"},I.nets.join(", ")):"",F?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",I.master?t("div",{class:"dl-muted"},`Choose ${I.master} to include it.`):""]),pe}function g(){let I=s.like_home;return!p||!s.config.lan_li Line truncated
`)){let d=l.trimEnd();if(i){/^```/.test(d.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(s(),e.push(t("h5",{},r(c[2])))):p?(a.length&&s(),o||(o=t("ul",{}),e.push(o)),o.appendChild(t("li",{},r(p[1])))):d.trim()?(o&&(o=null),a.push(d.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function Ma(n){let e=[],r=!1;for(let o of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(o);if(a){if(r=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(o)&&(r=!1);r||e.push(o)}return e.join(`
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 Zt(n,e,r,o){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";oe(r,[i,a],[D([v("copy")," Copy"],()=>me(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await P.updatesNotes(n,e,o??"");s=Ma(l.body||"");let d=Ea(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(a,s.trim()?La(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var Sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Co=n=>n?Ue(n):"";function Js(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function _a(n,e){let r=n.st,o=r.policy,a=r.kept?.app,i=e?.update&&e.tag?e.tag:r.version,s=x=>()=>Zt("app",x,`What’s new in Dawnline ${x.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ys(n,e.tag,e.update?r.version:""):null,d=e?.tag??i,c=o.check&&r.auto?.check?r.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[o.interval]??24)*3600:0,p=(x,$)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},x),t("span",{class:"dl-comp-side-v"},$)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${r.repo}`,"_blank","noopener")},null,{label:`Reinstall ${r.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",r.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${r.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",r.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",r.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[r.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Co(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Co(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(x=>t("li",{},x))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",r.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Zs(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${r.repo}`,target:"_blank",rel:"noopener"},r.repo)]),p("Auto-update",[o.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},o.auto?o.mode==="immediate"?"as soon as found":`${Sa[o.interval]==="weekly"?"weekly":"daily"} at ${o.time}`:o.check?`checks ${Sa[o.interval]}`:"checks off")]),p("Last check",r.check?[re(r.check.time,r.now),c>r.now?t("span",{class:"dl-faint"},`· next in ${xt(c-r.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},o.keep?"Kept after the next update":"Off")])])])}function Ys(n,e,r){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let o=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(r,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Js(o(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Zs(n){let e=t("div",{class:"dl-params-body"}),r=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return r.addEventListener("toggle",()=>{n.versOpen=r.open,n.versOpen&&Nn(n,e)}),n.versOpen&&Nn(n,e),r}async function Nn(n,e){let r=le("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),o=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");Ta(n,p)};r.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),o(r.value))});let a=t("div",{class:"dl-comp-tag"},[r,D("Install",()=>o(r.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),Nn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),D("Try again",()=>Nn(n,e))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let c=n.st.version;dom.content(e,[a,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Co(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===c?Ee("ok","Installed"):D("Install",()=>Ta(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Ta(n,e){let r=e.replace(/^v/,"");r.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${r}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${r}`,n.st.version)}function Pa(n,e){let r=n.st,o=r.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,d=!!e?.ru,c=r.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",p)}),o&&u.push({label:`Roll back to ${o.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${o.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let x=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((f,g,M)=>f!==null||g>0&&M[g-1]!==null),$=r.tunnels??[],h=$.length?`Switching restarts ${$.length===1?"the tunnel":`${$.length} tunnels`} for a few seconds: ${$.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=$.length>1?`${$.slice(0,-1).join(", ")} and ${$[$.length-1]}`:$[0],E=$.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",R=async f=>{let g=a[f];await se(p?`Switch to AmneziaWG ${g.gen}?`:`Install AmneziaWG ${g.gen}?`,`The ${g.label} build, ${g.version}. ${h}${g.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${f}${d?":ru":""}`,p?`Switching to AmneziaWG ${g.gen}`:"Installing AmneziaWG",p??void 0)},C=f=>{let g=a[f],M=s===f&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},g.gen?`AmneziaWG ${g.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${g.label} · ${g.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},g.version??"none yet"),t("span",{class:"dl-comp-bact"},M?Ee("ok","Active"):g.version?D(p?"Switch":"Install",()=>R(f),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},k=i.map(f=>a[f]?.newer?`${a[f].label} moves to ${a[f].newer.gen} with OpenWrt ${a[f].newer.tag.replace( Line truncated
`)}a.push(p),l+=c-1}let s=D([v("more")],()=>Ce(s,[{label:"Export CSV",icon:v("download"),run:()=>Fe(r,o,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Fe(r,o,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},o.length>10?`latest 10 of ${o.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var In=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[r,o,a]=await Promise.all([P.status(30),e?P.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:r,ev:o?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let r=this.st.people.find(s=>s.id===this.id);if(!r)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=r;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let o=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&r.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>Ge(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>o.isConnected,apply:(s,l)=>this.apply(s,l)}),o}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,r){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o){r||(location.href=_t(this.p?.server));return}this.p=o,this.paint(r),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,r){var i;this.poller?.claim();let o=await G(()=>P.personUpdate(this.p.id,e),r);if(!o)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=o.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=o.person),this.p=o.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return St(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:_t(e.server)},this.st.servers.find(r=>r.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:_t(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Se(this.parts.crumbs,this.crumbs(),e),Se(this.parts.head,ja(this),e),Se(this.parts.traffic,Ua(this),e),Se(this.parts.devices,Ga(this),e),Se(this.parts.limits,Ya(this),e),this.paintPlaces(e),Se(this.parts.activity,Qa(this),e)}paintPlaces(e=!1){let r=Za(this);r&&Se(this.parts.places,r,e&&!this.mapOpen)}};var sl={ok:"check",warn:"alert",error:"x",skip:"pause"},Bn=class{constructor(e,r,o,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=r,this.events=o,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(r,o)}async run(e){let r=e?await An(e):await P.health().catch(()=>null);r&&(this.take(r),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let r=e.filter(s=>s.status==="error").length,o=e.filter(s=>s.status==="warn").length;dom.content(this.summary,r?ct("error",`${r} problem${r>1?"s":""} need attention.`):o?ct("warn",`${o} warnLine truncated
`);function fi(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=El,n}function ht(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async o=>{let a=await e.render(o),i=document.createElement("div");return i.className="dl-root",i.append(fi(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var C1=ht(Yt),E1=ht(mt),L1=ht(Yt),M1=ht(zn),S1=ht(In),T1=ht(Un),_1=ht(Rn);function gi(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var P1=gi(""),D1=gi("log");return baseclass.extend({ activity: D1, diagnostics: T1, health: P1, overview: C1, people: E1, person: S1, server: L1, settings: M1, updates: _1 });
`).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 });
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -13,6 +13,7 @@ import * as watchdog from 'dawnline.watchdog';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import { L_ } from 'dawnline.i18n';
import {
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util';
@@ -139,7 +140,7 @@ function ifup_failed(ifname, who) {
return out;
});
if (r)
slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start",
slog('awg', 'error', r.n > 1 ? sprintf(L_("couldn't start · %d failed attempts in %d min"), r.n, r.mins) : L_("couldn't start"),
watchdog.iface_errors(ifname), who);
}
@@ -308,16 +309,16 @@ try {
if (args[1] == 'ifup') {
ifup_ok(ifname);
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who);
slog('awg', 'up', port ? sprintf(L_('started · accepting connections on port %s'), port) : L_('started'), null, who);
}
else if (args[1] == 'ifdown') {
// Stops Dawnline made itself are explained by the admin's own line
// (changed, turned off, removed); only an AmneziaWG update gets one here.
if (it?.reason == 'update')
slog('awg', 'info', 'restarting for the AmneziaWG update', null, who);
slog('awg', 'info', L_('restarting for the AmneziaWG update'), null, who);
else if (!it)
slog('awg', 'down', 'stopped unexpectedly', join('\n', filter([
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
slog('awg', 'down', L_('stopped unexpectedly'), join('\n', filter([
L_("Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed."),
watchdog.iface_errors(ifname),
], (x) => x)), who);
}
@@ -26,6 +26,7 @@ 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 { L_ } from 'dawnline.i18n';
const TICK = 60 * 1000;
const WATCH = 1000;
@@ -423,7 +424,7 @@ function check_cert(m) {
let c = pc.portal_cert(m.settings);
let mt = stat(c.cert)?.mtime;
if (cert_mtime != null && mt != null && mt != cert_mtime) {
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal');
slog('portal', 'up', sprintf(L_('certificate renewed · valid until %s'), cert_end(c.cert) ?? '?'), null, L_('Personal portal'));
system('/etc/init.d/dawnline reload >/dev/null 2>&1 &');
}
cert_mtime = mt;
@@ -432,8 +433,9 @@ function check_cert(m) {
return;
last_cert_check = time();
if (notes.cert_warned != mt && system(`openssl x509 -checkend 604800 -noout -in ${q(c.cert)} >/dev/null 2>&1`) != 0) {
slog('portal', 'error', `certificate expires ${cert_end(c.cert) ?? 'within 7 days'}`,
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.', 'Personal portal');
let end = cert_end(c.cert);
slog('portal', 'error', end ? sprintf(L_('certificate expires %s'), end) : L_('certificate expires within 7 days'),
L_('Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.'), L_('Personal portal'));
note('cert_warned', mt);
}
}
@@ -454,10 +456,13 @@ function check_wan(m) {
return;
let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name);
if (length(stuck))
slog('dawnline', 'error', `public address changed · ${was} → ${ip}`,
`${join(', ', stuck)} still give${length(stuck) == 1 ? 's' : ''} devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.`, 'Router');
slog('dawnline', 'error', sprintf(L_('public address changed · %s → %s'), was, ip),
sprintf(length(stuck) == 1
? L_('%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.')
: L_('%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.'),
join(', ', stuck)), L_('Router'));
else
slog('dawnline', 'info', `public address changed · ${was} → ${ip}`, null, 'Router');
slog('dawnline', 'info', sprintf(L_('public address changed · %s → %s'), was, ip), null, L_('Router'));
}
let last_backup_day = null;
@@ -476,7 +481,7 @@ function nightly_backup() {
}
catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
slog('dawnline', 'error', `nightly backup failed: ${e.message}`, null, 'Backup');
slog('dawnline', 'error', sprintf(L_('nightly backup failed: %s'), e.message), null, L_('Backup'));
}
}
}
@@ -545,7 +550,7 @@ function check_network(t) {
return;
}
pending_net = null;
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
slog('dawnline', 'info', L_('network changed - Dawnline set itself up again'), null, L_('Router'));
apply.apply();
base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load());
}
@@ -561,33 +566,33 @@ const STEPS = [
t.m = core.load();
t.pol = live.policy(t.m.settings.retention);
} },
{ who: 'Traffic', run: (t) => {
{ who: L_('Traffic'), run: (t) => {
t.reset = check_usage_reset(t.m);
live.collect(t.m, usage, live.dump(t.m));
} },
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
{ who: 'People', run: (t) => {
{ who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) },
{ who: L_('People'), run: (t) => {
t.states = apply.states_for(t.m, usage);
check_people(t.m, t.states, t.events);
check_expiry(t.m, t.events);
} },
{ who: 'Access rules', run: (t) => {
{ who: L_('Access rules'), run: (t) => {
if (t.states)
sync_runtime(t);
} },
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
{ who: 'Activity', run: (t) => {
{ who: L_('Activity'), run: (t) => {
live.add_events(t.events, t.pol);
// Pauses and resumes on their own: the UI shows them without waiting for its next poll.
if (length(t.events))
save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person)));
} },
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
{ who: 'Router', run: check_network },
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
{ who: 'Personal portal', run: (t) => check_cert(t.m) },
{ who: 'Router', quiet: true, run: (t) => check_wan(t.m) },
{ who: 'Backup', run: (t) => nightly_backup() },
{ who: L_('Internet like a home device'), run: (t) => apply.sync_loop(t.m, usage) },
{ who: L_('Router'), run: check_network },
{ who: L_('Watchdog'), run: (t) => watchdog.run(core.load()) },
{ who: L_('Personal portal'), run: (t) => check_cert(t.m) },
{ who: L_('Router'), quiet: true, run: (t) => check_wan(t.m) },
{ who: L_('Backup'), run: (t) => nightly_backup() },
{ who: 'updates', quiet: true, run: (t) => check_updates(t.m) },
{ who: 'geo', quiet: true, run: (t) => check_geo(t.m) },
];
@@ -603,7 +608,7 @@ function step(i, s, fn) {
catch (e) {
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
if (!s.quiet && step_err[i] != e.message)
slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who);
slog('dawnline', 'error', sprintf(L_('failed: %s'), e.message), e.stacktrace?.[0]?.context, s.who);
step_err[i] = e.message;
}
}
@@ -625,7 +630,7 @@ function tick() {
step(i, s, () => s.run(t));
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
step('save', { who: 'Traffic' }, () => {
step('save', { who: L_('Traffic') }, () => {
live.save_usage(usage, persist);
if (persist) {
last_flush = time();
@@ -633,7 +638,7 @@ function tick() {
}
});
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
step('events', { who: 'Activity' }, () => {
step('events', { who: L_('Activity') }, () => {
let pol = t.pol ?? live.policy();
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
live.persist_events(pol);
@@ -667,20 +672,20 @@ slog_restore();
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
unlink(`${RUN_DIR}/update-rolled-back`);
if (rolled)
slog('dawnline', 'error', `update to ${rolled} failed its check — rolled back to ${VERSION}`,
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.', 'Dawnline');
slog('dawnline', 'error', sprintf(L_('update to %s failed its check - rolled back to %s'), rolled, VERSION),
L_('The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.'), 'Dawnline');
else if (was && was != VERSION)
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'up', sprintf(L_('updated · %s → %s'), was, VERSION), null, 'Dawnline');
else if (crashed)
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
slog('dawnline', 'repair', L_('stopped unexpectedly - started again'),
// Why, when syslog knows: procd, the kernel (out of memory, segfault), ucode errors.
sh_out('logread -l 400 2>/dev/null | grep -iE "kernel:.*(out of memory|killed process|oom-kill|segfault)|procd:.*dawnline|dawnline/agent" | tail -n 6'), 'Dawnline');
else if (stopped && time() - stopped < 300)
slog('dawnline', 'info', `restarted · version ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'info', sprintf(L_('restarted · version %s'), VERSION), null, 'Dawnline');
else if (live.uptime() < 600)
slog('dawnline', 'info', `started with the router · version ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
else
slog('dawnline', 'info', `started · version ${VERSION}`, null, 'Dawnline');
slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline');
uloop.init();
@@ -690,14 +695,14 @@ timer = uloop.timer(1000, function() {
tick();
}
catch (e) {
slog('dawnline', 'error', `background check failed: ${e.message}`, e.stacktrace?.[0]?.context, 'Dawnline');
slog('dawnline', 'error', sprintf(L_('background check failed: %s'), e.message), e.stacktrace?.[0]?.context, 'Dawnline');
}
timer.set(TICK);
});
let watcher;
watcher = uloop.timer(WATCH, function() {
step('watch', { who: 'Connections' }, watch);
step('watch', { who: L_('Connections') }, watch);
watcher.set(WATCH);
});
@@ -12,6 +12,9 @@ KEEP=/etc/dawnline/keep/app
to="${1:-?}"
sleep 2
# LuCI reads a language's catalogs once per web server: a replaced translation
# needs a fresh one, before the new version answers and the page reloads.
ls /usr/lib/lua/luci/i18n/dawnline.*.lmo >/dev/null 2>&1 && /etc/init.d/uhttpd restart >/dev/null 2>&1
/etc/init.d/rpcd reload >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
@@ -21,12 +21,18 @@ import * as upd from 'dawnline.updates';
import * as app from 'dawnline.upd_app';
import * as awg from 'dawnline.upd_awg';
import * as pkgs from 'dawnline.upd_pkgs';
import * as i18n from 'dawnline.i18n';
import { _, L_ } from 'dawnline.i18n';
// 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'));
const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0];
const POL = core.load().settings.updates;
const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check };
const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install };
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' };
// Names in the service log (English there, like the rest of it); the phases are checking() and updating().
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: L_('System packages'), packages: L_('System packages') };
let job = {
id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
@@ -82,6 +88,24 @@ const ctx = {
after: (what) => after[what] = true,
};
/** The phase of a component's check (app, amneziawg, packages). */
function checking(name) {
if (name == 'app')
return _('Checking Dawnline');
if (name == 'amneziawg')
return _('Checking AmneziaWG');
return _('Checking system packages');
}
/** The phase of a component's update (app, amneziawg, pkgs). */
function updating(name) {
if (name == 'app')
return _('Updating Dawnline');
if (name == 'amneziawg')
return _('Updating AmneziaWG');
return _('Updating system packages');
}
/* ---------- check results ---------- */
function checks_file() {
@@ -98,7 +122,10 @@ function save_check(res) {
write_json(upd.CHECK_FILE, c, 0o644);
}
/** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */
/**
* What a check found, as short names ("Dawnline 0.3.3", "2 system packages"):
* kept in the history and shown later, so English whatever the job's language.
*/
function found_in(res) {
let found = [];
if (res.app?.update)
@@ -106,19 +133,19 @@ function found_in(res) {
if (res.amneziawg?.update && res.amneziawg.installed)
push(found, `AmneziaWG ${res.amneziawg.latest}`);
if (res.packages?.updates)
push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`);
push(found, sprintf(res.packages.updates == 1 ? L_('%d system package') : L_('%d system packages'), res.packages.updates));
return found;
}
function run_checks(which) {
let res = {};
for (let name in which) {
phase(`Checking ${WHO[name]}`);
phase(checking(name));
try {
res[name] = CHECKS[name](ctx);
}
catch (e) {
log(`Error: ${e.message}`);
log(sprintf(_('Error: %s'), e.message));
res[name] = { error: e.message, status: '' };
}
}
@@ -132,7 +159,7 @@ function note_found(res, st, auto) {
let sig = join(', ', found);
if (length(found) && sig != st.announced) {
if (auto)
slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components');
slog('dawnline', 'info', sprintf(L_('updates available · %s'), sig), null, L_('Components'));
upd.history_add({ kind: 'found', items: found, auto });
}
st.announced = sig;
@@ -142,14 +169,14 @@ function note_found(res, st, auto) {
/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
function log_update(name, r) {
let how = job.auto ? ' automatically' : '';
if (name == 'amneziawg') {
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}`
: `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, 'AmneziaWG');
slog('awg', 'up', b && a && b != a ? sprintf(job.auto ? L_('updated automatically · %s → %s') : L_('updated · %s → %s'), b, a)
: a ? sprintf(L_('installed the %s build · %s'), r?.build ?? '', a) : sprintf(L_('installed the %s build'), r?.build ?? ''), null, 'AmneziaWG');
}
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
slog('dawnline', 'up', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
slog('dawnline', 'up', sprintf(job.auto ? L_('updated automatically · %s') : L_('updated · %s'),
join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])), null, L_('System packages'));
}
function split_target(w) {
@@ -172,9 +199,9 @@ function install(what) {
for (let w in what) {
let t = split_target(w), name = t[0], arg = t[1];
if (!INSTALLS[name])
die(`Unknown component ${name}`);
die(sprintf(_('Unknown component %s'), name));
job.current = name;
phase(`Updating ${WHO[name]}`);
phase(updating(name));
let r = INSTALLS[name](ctx, arg);
job.result[name] = r;
log_update(name, r);
@@ -228,7 +255,7 @@ function auto() {
if (a.current && !a.gen_change)
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
else
slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG');
slog('awg', 'info', a.latest ? sprintf(L_('%s needs a manual switch in Components'), a.latest) : L_('a new build needs a manual switch in Components'), null, 'AmneziaWG');
}
if (index(POL.targets, 'app') >= 0 && res.app?.update)
push(todo, 'app');
@@ -239,7 +266,7 @@ function auto() {
job.component = join(' ', todo);
job.auto = true;
job.log = [];
log(`Automatic update: ${join(', ', todo)}`);
log(sprintf(_('Automatic update: %s'), join(', ', todo)));
install(todo);
}
@@ -257,7 +284,8 @@ function restarts() {
let cmds = [];
if (after.apply)
push(cmds, '/usr/bin/dawnline apply');
if (after.uhttpd)
// LuCI's own web server reads a language's catalogs once: a new translation needs a fresh one.
if (after.uhttpd || after.luci)
push(cmds, '/etc/init.d/uhttpd restart');
if (after.apply || after.uhttpd)
push(cmds, '/etc/init.d/dawnline restart');
@@ -265,6 +293,46 @@ function restarts() {
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
}
/** The job the command line asks for, to its final state: done, or failed with the error in the log and the history. */
function main() {
try {
if (job.action == 'check') {
let which = job.component ? [ job.component ] : upd.TARGETS;
for (let w in which)
if (!CHECKS[w])
die(sprintf(_('Unknown component %s'), w));
job.result = run_checks(which);
let st = upd.auto_state();
note_found(job.result, st, false);
if (length(which) == length(upd.TARGETS))
st.check = time();
upd.auto_save(st);
}
else if (job.action == 'install')
install([ job.component ]);
else if (job.action == 'auto')
auto();
else
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done';
phase(_('Finished'));
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(sprintf(_('Error: %s'), e.message));
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
if (job.action != 'check') {
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', job.auto ? L_('automatic update failed') : L_('update failed'), e.message, WHO[name] ?? 'Dawnline');
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
took: time() - job.started });
}
else
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
}
}
/* ---------- main ---------- */
ensure_dir(RUN_DIR);
@@ -279,43 +347,7 @@ if (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save();
try {
if (job.action == 'check') {
let which = job.component ? [ job.component ] : upd.TARGETS;
for (let w in which)
if (!CHECKS[w])
die(`Unknown component ${w}`);
job.result = run_checks(which);
let st = upd.auto_state();
note_found(job.result, st, false);
if (length(which) == length(upd.TARGETS))
st.check = time();
upd.auto_save(st);
}
else if (job.action == 'install')
install([ job.component ]);
else if (job.action == 'auto')
auto();
else
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done';
phase('Finished');
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(`Error: ${e.message}`);
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
if (job.action != 'check') {
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', `${job.auto ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline');
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
took: time() - job.started });
}
else
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
}
main();
system(`rm -rf '${ctx.work}'`);
job.finished = time();
@@ -1 +1 @@
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{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
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var Oo=Object.create;var On=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var Ko=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var qo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of No(e))!Fo.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(r=Ro(e,o))||r.enumerable});return t};var Go=(t,e,n)=>(n=t!=null?Oo(Io(t)):{},qo(e||!t||!t.__esModule?On(n,"default",{value:t,enumerable:!0}):n,t));var gr=Ko((hr,mr)=>{"use strict";var fr=(function(){var t=function(d,m){var s=236,h=17,f=d,E=n[m],p=null,l=0,L=null,x=[],C={},R=function(w,k){l=f*4+17,p=(function(y){for(var T=new Array(y),S=0;S<y;S+=1){T[S]=new Array(y);for(var D=0;D<y;D+=1)T[S][D]=null}return T})(l),I(0,0),I(l-7,0),I(0,l-7),et(),Q(),it(w,k),f>=7&&ot(w),L==null&&(L=$t(f,E,x)),G(L,k)},I=function(w,k){for(var y=-1;y<=7;y+=1)if(!(w+y<=-1||l<=w+y))for(var T=-1;T<=7;T+=1)k+T<=-1||l<=k+T||(0<=y&&y<=6&&(T==0||T==6)||0<=T&&T<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=T&&T<=4?p[w+y][k+T]=!0:p[w+y][k+T]=!1)},z=function(){for(var w=0,k=0,y=0;y<8;y+=1){R(!0,y);var T=o.getLostPoint(C);(y==0||w>T)&&(w=T,k=y)}return k},Q=function(){for(var w=8;w<l-8;w+=1)p[w][6]==null&&(p[w][6]=w%2==0);for(var k=8;k<l-8;k+=1)p[6][k]==null&&(p[6][k]=k%2==0)},et=function(){for(var w=o.getPatternPosition(f),k=0;k<w.length;k+=1)for(var y=0;y<w.length;y+=1){var T=w[k],S=w[y];if(p[T][S]==null)for(var D=-2;D<=2;D+=1)for(var K=-2;K<=2;K+=1)D==-2||D==2||K==-2||K==2||D==0&&K==0?p[T+D][S+K]=!0:p[T+D][S+K]=!1}},ot=function(w){for(var k=o.getBCHTypeNumber(f),y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[Math.floor(y/3)][y%3+l-8-3]=T}for(var y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[y%3+l-8-3][Math.floor(y/3)]=T}},it=function(w,k){for(var y=E<<3|k,T=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<6?p[S][8]=D:S<8?p[S+1][8]=D:p[l-15+S][8]=D}for(var S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<8?p[8][l-S-1]=D:S<9?p[8][15-S-1+1]=D:p[8][15-S-1]=D}p[l-8][8]=!w},G=function(w,k){for(var y=-1,T=l-1,S=7,D=0,K=o.getMaskFunction(k),N=l-1;N>0;N-=2)for(N==6&&(N-=1);;){for(var X=0;X<2;X+=1)if(p[T][N-X]==null){var nt=!1;D<w.length&&(nt=(w[D]>>>S&1)==1);var q=K(T,N-X);q&&(nt=!nt),p[T][N-X]=nt,S-=1,S==-1&&(D+=1,S=7)}if(T+=y,T<0||l<=T){T-=y,y=-y;break}}},V=function(w,k){for(var y=0,T=0,S=0,D=new Array(k.length),K=new Array(k.length),N=0;N<k.length;N+=1){var X=k[N].dataCount,nt=k[N].totalCount-X;T=Math.max(T,X),S=Math.max(S,nt),D[N]=new Array(X);for(var q=0;q<D[N].length;q+=1)D[N][q]=255&w.getBuffer()[q+y];y+=X;var gt=o.getErrorCorrectPolynomial(nt),vt=c(D[N],gt.getLength()-1),Dn=vt.mod(gt);K[N]=new Array(gt.getLength()-1);for(var q=0;q<K[N].length;q+=1){var Bn=q+Dn.getLength()-K[N].length;K[N][q]=Bn>=0?Dn.getAt(Bn):0}}for(var Hn=0,q=0;q<k.length;q+=1)Hn+=k[q].totalCount;for(var on=new Array(Hn),Ae=0,q=0;q<T;q+=1)for(var N=0;N<k.length;N+=1)q<D[N].length&&(on[Ae]=D[N][q],Ae+=1);for(var q=0;q<S;q+=1)for(var N=0;N<k.length;N+=1)q<K[N].length&&(on[Ae]=K[N][q],Ae+=1);return on},$t=function(w,k,y){for(var T=g.getRSBlocks(w,k),S=v(),D=0;D<y.length;D+=1){var K=y[D];S.put(K.getMode(),4),S.put(K.getLength(),o.getLengthInBits(K.getMode(),w)),K.write(S)}for(var N=0,D=0;D<T.length;D+=1)N+=T[D].dataCount;if(S.getLengthInBits()>N*8)throw"code length overflow. ("+S.getLengthInBits()+">"+N*8+")";for(S.getLengthInBits()+4<=N*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=N*8||(S.put(s,8),S.getLengthInBits()>=N*8));)S.put(h,8);return V(S,T)};C.addData=function(w,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=u(w);break;case"Alphanumeric":y=M(w);break;case"Byte":y=b(w);break;case"Kanji":y=A(w);break;default:throw"mode:"+k}x.push(y),L=null},C.isDark=function(w,k){if(w<0||l<=w||k<0||l<=k)throw w+","+k;return p[w][k]},C.getModuleCount=function(){return l},C.make=function(){if(f<1){for(var w=1;w<40;w++){for(var k=g.getRSBlocks(w,E),y=v(),T=0;T<x.length;T++){var S=x[T];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),w)),S.write(y)}for(var D=0,T=0;T<k.length;T++)D+=k[T].dataCount;if(y.getLengthInBits()<=D*8)break}f=w}R(!1,z())},C.createTableTag=function(w,k){w=w||2,k=typeof k=="undefined"?w*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var T=0;T<C.getModuleCount();T+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+w+"px;",y+=" height: "+w+"px;",y+=" background-color: ",y+=C.isDark(T,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(w,k,y,T){var S={};typeof arguments[0]=="object"&&(S=arguments[0],w=S.cellSize,k=S.margin,y=S.alt,T=S.title),w=w||2,k=typeof k=="undefined"?w*4:k,y=typeof y=="string"?{text:y}:y||{Line truncated
`}return y%2&&w>0?vt.substring(0,vt.length-y-1)+Array(y+1).join("▀"):vt.substring(0,vt.length-1)};return C.createASCII=function(w,k){if(w=w||1,w<2)return rn(k);w-=1,k=typeof k=="undefined"?w*2:k;var y=C.getModuleCount()*w+k*2,T=k,S=y-k,D,K,N,X,nt=Array(w+1).join("██"),q=Array(w+1).join(" "),gt="",vt="";for(D=0;D<y;D+=1){for(N=Math.floor((D-T)/w),vt="",K=0;K<y;K+=1)X=1,T<=K&&K<S&&T<=D&&D<S&&C.isDark(N,Math.floor((K-T)/w))&&(X=0),vt+=X?nt:q;for(N=0;N<w;N+=1)gt+=vt+`
`}return gt.substring(0,gt.length-1)},C.renderTo2dContext=function(w,k){k=k||2;for(var y=C.getModuleCount(),T=0;T<y;T++)for(var S=0;S<y;S++)w.fillStyle=C.isDark(T,S)?"black":"white",w.fillRect(T*k,S*k,k,k)},C};t.stringToBytesFuncs={default:function(d){for(var m=[],s=0;s<d.length;s+=1){var h=d.charCodeAt(s);m.push(h&255)}return m}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(d,m){var s=(function(){for(var f=P(d),E=function(){var Q=f.read();if(Q==-1)throw"eof";return Q},p=0,l={};;){var L=f.read();if(L==-1)break;var x=E(),C=E(),R=E(),I=String.fromCharCode(L<<8|x),z=C<<8|R;l[I]=z,p+=1}if(p!=m)throw p+" != "+m;return l})(),h=63;return function(f){for(var E=[],p=0;p<f.length;p+=1){var l=f.charCodeAt(p);if(l<128)E.push(l);else{var L=s[f.charAt(p)];typeof L=="number"?(L&255)==L?E.push(L):(E.push(L>>>8),E.push(L&255)):E.push(h)}}return E}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],m=1335,s=7973,h=21522,f={},E=function(p){for(var l=0;p!=0;)l+=1,p>>>=1;return l};return f.getBCHTypeInfo=function(p){for(var l=p<<10;E(l)-E(m)>=0;)l^=m<<E(l)-E(m);return(p<<10|l)^h},f.getBCHTypeNumber=function(p){for(var l=p<<12;E(l)-E(s)>=0;)l^=s<<E(l)-E(s);return p<<12|l},f.getPatternPosition=function(p){return d[p-1]},f.getMaskFunction=function(p){switch(p){case r.PATTERN000:return function(l,L){return(l+L)%2==0};case r.PATTERN001:return function(l,L){return l%2==0};case r.PATTERN010:return function(l,L){return L%3==0};case r.PATTERN011:return function(l,L){return(l+L)%3==0};case r.PATTERN100:return function(l,L){return(Math.floor(l/2)+Math.floor(L/3))%2==0};case r.PATTERN101:return function(l,L){return l*L%2+l*L%3==0};case r.PATTERN110:return function(l,L){return(l*L%2+l*L%3)%2==0};case r.PATTERN111:return function(l,L){return(l*L%3+(l+L)%2)%2==0};default:throw"bad maskPattern:"+p}},f.getErrorCorrectPolynomial=function(p){for(var l=c([1],0),L=0;L<p;L+=1)l=l.multiply(c([1,a.gexp(L)],0));return l},f.getLengthInBits=function(p,l){if(1<=l&&l<10)switch(p){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+p}else if(l<27)switch(p){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+p}else if(l<41)switch(p){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+p}else throw"type:"+l},f.getLostPoint=function(p){for(var l=p.getModuleCount(),L=0,x=0;x<l;x+=1)for(var C=0;C<l;C+=1){for(var R=0,I=p.isDark(x,C),z=-1;z<=1;z+=1)if(!(x+z<0||l<=x+z))for(var Q=-1;Q<=1;Q+=1)C+Q<0||l<=C+Q||z==0&&Q==0||I==p.isDark(x+z,C+Q)&&(R+=1);R>5&&(L+=3+R-5)}for(var x=0;x<l-1;x+=1)for(var C=0;C<l-1;C+=1){var et=0;p.isDark(x,C)&&(et+=1),p.isDark(x+1,C)&&(et+=1),p.isDark(x,C+1)&&(et+=1),p.isDark(x+1,C+1)&&(et+=1),(et==0||et==4)&&(L+=3)}for(var x=0;x<l;x+=1)for(var C=0;C<l-6;C+=1)p.isDark(x,C)&&!p.isDark(x,C+1)&&p.isDark(x,C+2)&&p.isDark(x,C+3)&&p.isDark(x,C+4)&&!p.isDark(x,C+5)&&p.isDark(x,C+6)&&(L+=40);for(var C=0;C<l;C+=1)for(var x=0;x<l-6;x+=1)p.isDark(x,C)&&!p.isDark(x+1,C)&&p.isDark(x+2,C)&&p.isDark(x+3,C)&&p.isDark(x+4,C)&&!p.isDark(x+5,C)&&p.isDark(x+6,C)&&(L+=40);for(var ot=0,C=0;C<l;C+=1)for(var x=0;x<l;x+=1)p.isDark(x,C)&&(ot+=1);var it=Math.abs(100*ot/l/l-50)/5;return L+=it*10,L},f})(),a=(function(){for(var d=new Array(256),m=new Array(256),s=0;s<8;s+=1)d[s]=1<<s;for(var s=8;s<256;s+=1)d[s]=d[s-4]^d[s-5]^d[s-6]^d[s-8];for(var s=0;s<255;s+=1)m[d[s]]=s;var h={};return h.glog=function(f){if(f<1)throw"glog("+f+")";return m[f]},h.gexp=function(f){for(;f<0;)f+=255;for(;f>=256;)f-=255;return d[f]},h})();function c(d,m){if(typeof d.length=="undefined")throw d.length+"/"+m;var s=(function(){for(var f=0;f<d.length&&d[f]==0;)f+=1;for(var E=new Array(d.length-f+m),p=0;p<d.length-f;p+=1)E[p]=d[p+f];return E})(),h={};return h.getAt=function(f){return s[f]},h.getLength=function(){return s.length},h.multiply=function(f){for(var E=new Array(h.getLength()+f.getLength()-1),p=0;p<h.getLength();p+=1)for(var l=0;l<f.getLength();l+=1)E[p+l]^=a.gexp(a.glog(h.getAt(p))+a.glog(f.getAt(l)));return c(E,0)},h.mod=function( Line truncated
`),hostName:a,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},g={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(c),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return n.dns[0]&&(g.dns1=n.dns[0]),n.dns[1]&&(g.dns2=n.dns[1]),g}function bi(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wi(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let n=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,t.length,!1),o.set(r,4),o}catch{return null}}async function Ln(t,e,n=!0){let r=new TextEncoder().encode(JSON.stringify(xi(t,e))),o=n?await wi(r):null;return`vpn://${bi(o!=null?o:r)}`}var Zr=t=>t.replace(/^vpn:\/\//,"");var to=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function qt(t,e={}){let n=i("div",{class:`acc${e.inset?" inset":""}`}),r=t.map((u,M)=>{var $;let b=u.body.filter(d=>!!d),A=!b.length,O=[u.icon,i("span",{class:"acc-title"},i("span",{class:"t"},u.title),($=u.tag)!=null?$:null),u.val?i("span",{class:`acc-val${u.valHide?" hide-open":""}`},u.val):null],B=M===e.open&&!A,P=A?i("div",{class:"acc-head"},...O):i("button",{type:"button",class:"acc-head","aria-expanded":String(B),onclick:()=>v(H)},...O,F("chevron","i acc-chev")),H=i("div",{class:`acc-row${A?" still":""}${B?" open":""}`},P,i("div",{class:"acc-body"},...b));return n.appendChild(H),H}),o=u=>u.querySelector(".acc-body"),a=()=>r.forEach((u,M)=>{let b=u.classList.contains("open");u.classList.toggle("rt",M===0||b||r[M-1].classList.contains("open")),u.classList.toggle("rb",M===r.length-1||b||r[M+1].classList.contains("open"))}),c=u=>{let M=getComputedStyle(u),b={};for(let A of to)b[A]=A==="height"?`${u.getBoundingClientRect().height}px`:M[A];return b},g=()=>r.forEach(u=>{var M;return(M=u.querySelector("button.acc-head"))==null?void 0:M.setAttribute("aria-expanded",String(u.classList.contains("open")))});function v(u){var B;let M=r.map(c);r.forEach(P=>P.getAnimations().forEach(H=>H.cancel())),r.forEach(P=>o(P).getAnimations().forEach(H=>H.cancel()));let b=!u.classList.contains("open"),A=r.filter(P=>P.classList.contains("open")&&(P===u||b));r.forEach(P=>{P.classList.remove("closing"),P!==u&&P.classList.remove("open")}),u.classList.toggle("open",b),a();let O=ce();r.forEach((P,H)=>{let $=c(P);to.some(d=>M[H][d]!==$[d])&&(A.includes(P)&&P.classList.add("closing"),_(P,[M[H],$],{duration:Et.duration,easing:Et.easing}).onfinish=()=>P.classList.remove("closing"))}),A.forEach(P=>_(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:J,fill:"forwards"})),b&&_(o(u),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),de(O),g(),(B=e.onToggle)==null||B.call(e,r.indexOf(u),b,!1)}return a(),{el:n,openIndex:()=>r.findIndex(u=>u.classList.contains("open")),setOpen(u){r.forEach((M,b)=>M.classList.toggle("open",b===u&&!M.classList.contains("still"))),a(),g(),r.forEach((M,b)=>{var A;return(A=e.onToggle)==null?void 0:A.call(e,b,M.classList.contains("open"),!0)})}}}function eo(t,e,n){let r=i("span",{class:"seg-pill"}),o=i("div",{class:"seg appseg",role:"tablist"},r),a=t.map(A=>{let O=i("button",{type:"button",class:"seg-b",role:"tab","aria-label":A.label,title:A.label,onclick:()=>b(A.value)},F(A.icon),i("span",{class:"seg-l"},A.label));return O.dataset.v=A.value,o.appendChild(O),O}),c=A=>A.querySelector(".seg-l"),g=()=>a.forEach(A=>{let O=A.dataset.v===e;A.classList.toggle("on",O),A.setAttribute("aria-selected",String(O))}),v=()=>{let A=a.find(O=>O.dataset.v===e);return A&&A.offsetWidth?[A.offsetLeft,o.clientWidth-A.offsetLeft-A.offsetWidth]:null},u=()=>{let A=v();A&&(r.style.left=`${A[0]}px`,r.style.right=`${A[1]}px`)},M=0;function b(A){if(A===e)return;let O=a.findIndex(C=>C.dataset.v===e),B=a.findIndex(C=>C.dataset.v===A),P=getComputedStyle(r),H=parseFloat(P.left)||0,$=parseFloat(P.right)||0,d=a.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),m=c(a[O]),s=m.getBoundingClientRect().width;[...a,...a.map(c)].forEach(C=>C.getAnimations().forEach(R=>R.cancel())),e=A,g(),a.forEach((C,R)=>{let I=R===B?1:0;d[R]!==I&&_(C,[{flexGrow:d[R]},{flexGrow:I}],{duration:U.duration,easing:U.easing})}),_(m,[{opacity:1,maxWidth:`${s}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),_(c(a[B]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:Y,fill:"backwards"});let h=B>O,f=Lt()?U:Fn,E=performance.now(),p=Math.m Line truncated
`).flatMap((u,M)=>M?[`
`,ro(u,e)]:[ro(u,e)]));r();let o=!!Wt(t.filename,t.conf),a=i("button",{type:"button",class:"btn soft sm",onclick:()=>{e=!e,a.replaceChildren(F(e?"x":"key"),i("span",{},e?"Hide key":"Show key")),r(),n.querySelectorAll(".mask, .k").forEach(u=>_(u,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:Y}))}},F("key"),i("span",{},"Show key")),c=i("button",{type:"button",class:"btn soft sm",onclick:u=>pt(t.conf,"Configuration copied",u.currentTarget)},F("copy"),i("span",{class:"lbl"},"Copy")),g=i("div",{class:"filecard"},i("div",{class:"fc-row"},i("span",{class:"filecard-ic"},".conf"),i("span",{class:"t"},i("span",{class:"mono"},t.filename),i("span",{},"For computers and routers"))),i("button",{type:"button",class:"btn accent sm block",onclick:()=>ye(t.filename,t.conf)},F(o?"open":"download"),i("span",{},o?"Share file":"Download"))),v=qt([{icon:j("file"),title:"Configuration",body:[i("div",{class:"confbar"},a,c),n]}],{inset:!0});return i("div",{class:"step-box"},g,v.el)}function fo(t){let e=i("span",{class:"osm-p"},at[t]),n=Dr(me(t,"ios"),me(t,"android"));return{el:i("span",{class:"scanline"},i("span",{},"In ",e,":"),n.el),set(r){Z(e,at[r],void 0,{whole:!0}),n.set(me(r,"ios"),me(r,"android"))}}}function ho(t){let e=i("span",{class:"tt"}),n=i("span",{class:"tt-m"}),r=i("span",{class:"hp-tip","aria-hidden":"true"},e,n),o=i("button",{type:"button",class:"hp-b",onclick:()=>ye(t().file,t().text)},F("download")),a=i("button",{type:"button",class:"hp-b"},F("copy")),c=i("div",{class:"hpill",role:"group","aria-label":"The connection","data-key":"conn"},o,a,r),g=null,v=0,u=0,M=s=>{var h;return s===a&&a.classList.contains("done")?"Copied":(h=s.getAttribute("aria-label"))!=null?h:""},b=(s,h)=>{n.textContent=h;let f=n.offsetWidth+20;return Math.min(s.offsetLeft+s.offsetWidth/2,c.offsetWidth+46-f/2)},A=s=>`translateX(${s}px) translateX(-50%)`,O=s=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(f=>f.cancel()),r.style.transform=A(s),_(r,[{transform:h},{transform:A(s)}],{duration:U.duration,easing:U.easing})},B=s=>Z(e,s),P=s=>{if(clearTimeout(v),g===s&&r.classList.contains("on"))return;if(g=s,r.classList.contains("on")){let f=M(s);return O(b(s,f)),B(f)}let h=()=>{let f=M(s);bt(e,f);let E=b(s,f);r.getAnimations().forEach(p=>p.cancel()),r.style.transform=A(E),r.classList.add("on"),_(r,[{opacity:0,transform:`${A(E)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:A(E),filter:"blur(0px)"}],{duration:220,easing:Y})};performance.now()<u?h():v=window.setTimeout(h,420)},H=()=>{clearTimeout(v),g=null,r.classList.contains("on")&&(u=performance.now()+500,r.classList.remove("on"),_(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let s of[o,a])s.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(s)}),s.addEventListener("focus",()=>{s.matches(":focus-visible")&&P(s)}),s.addEventListener("blur",H);c.addEventListener("pointerleave",H);let $=s=>{let h=F(s);a.querySelector("svg").replaceWith(h),_(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:yt.duration,easing:yt.easing})},d=()=>{if(g!==a||!r.classList.contains("on"))return;let s=M(a);O(b(a,s)),B(s)},m=0;return a.addEventListener("click",()=>{let s=t();pt(s.text,s.msg),clearTimeout(m),a.classList.contains("done")||(a.classList.add("done"),$("check"),d()),m=window.setTimeout(()=>{a.classList.remove("done"),$("copy"),d()},1600)}),{el:c,sync(){let s=t().app;o.setAttribute("aria-label",`Download ${s} config`),a.setAttribute("aria-label",`Copy ${s} config`)}}}function go(t){let e=i("b",{},"Waiting for the connection"),n=i("span",{class:"ws",hidden:!0}),r=i("div",{class:"way",role:"status","aria-live":"polite"},i("div",{class:"way-row"},i("span",{class:"way-end"},F(t.kind)),i("span",{class:"way-track"},i("span",{class:"way-glow"},i("i")),i("span",{class:"way-fill"})),i("span",{class:"way-end home"},F("server"))),i("div",{class:"way-text"},i("span",{class:"t"},e,n)));return{el:r,connected(){r.classList.add("done"),Z(e,`${t.name} connected`)},gaveUp(){r.classList.add("stopped"),Z(e,"No connection yet"),n.textContent="Close this and open it again to keep checking.",n.hidden=!1,_(e.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:Y})}}}function vo(t,e=4){window.setTimeout(async()=>{var n;try{let r=await ut("state");xt(r),be()||Mt(),!((n=r.person.devices.find(o=>o.id===t))!=null&&n.online)&&e>1&&vo(t,e-1)}catch{}},1500)}function yo(t,e,n){let r=te(),o=0,a=0,c=!1,g=Date.now(),v=async()=>{if(o=0,!c){if(Date.now()-g>6e5){c=!0,n();return}if(document.hidden)return u();try{let b=await ut("state");xt(b);let A=b.person.devices.find(O=>O.id===t.id);if(A&&A.handshake>r){c=!0,e(),A.online||vo(t.id);return}}catch(b){if(Oe(b)){c=!0;return}}a++,u()}},u=()=>{!c&&!o&&(o=window.setTimeout(v,a<6?5e3:a<12?15e3:3e4))},M=()=>{!document.hidden&&!c&&!o&&v()};return document.addEventListener("visibilitychange",M),u(),()=>{c=!0,o Line truncated
"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_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
@@ -4,7 +4,9 @@
// servers, people (and their devices), settings, home (services, circles),
// maint (Diagnostics, backups, removal) and updates (Components). Each module
// exports `methods` as { name: { args, call } }; read-only users get the
// methods listed under "read" in acl.d/luci-app-dawnline.json.
// methods listed under "read" in acl.d/luci-app-dawnline.json. Every method
// also takes `lang`, the admin page's language, and answers in it (its
// errors and the texts the backend writes, through dawnline.i18n).
'use strict';
import * as status from 'dawnline.rpc.status';
@@ -14,9 +16,29 @@ import * as settings from 'dawnline.rpc.settings';
import * as home from 'dawnline.rpc.home';
import * as maint from 'dawnline.rpc.maint';
import * as updates from 'dawnline.rpc.updates';
import * as i18n from 'dawnline.i18n';
/** The methods with `lang` added: the language is set for the call, the method never sees it. */
function in_lang(methods) {
let out = {};
for (let name, m in methods) {
let call = m.call;
out[name] = {
...m,
args: { ...(m.args ?? {}), lang: '' },
call: function(req) {
i18n.use(req.args?.lang);
if (req.args)
delete req.args.lang;
return call(req);
},
};
}
return out;
}
return {
'luci.dawnline': {
'luci.dawnline': in_lang({
...status.methods,
...servers.methods,
...people.methods,
@@ -24,5 +46,5 @@ return {
...home.methods,
...maint.methods,
...updates.methods,
},
}),
};
@@ -1,5 +1,6 @@
// Dawnline: "Check access" — walks the same rules the nft table and the
// client configuration apply, and says in words where a connection stops.
// client configuration apply, and says in words where a connection stops
// (in the admin's language: each step is a whole sentence).
'use strict';
@@ -9,17 +10,68 @@ import * as net from 'dawnline.net';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg';
import { _ } from 'dawnline.i18n';
const STATE_TEXT = {
no_server: 'they have no server',
server_off: 'their server is turned off',
paused: 'they are paused',
expired: 'their access has ended',
quota: 'they used up their data',
hours: 'it is outside their allowed hours',
};
/** "Bob can't connect: they are paused", by the person's state (core.person_state). */
function cant_connect(name, st) {
if (st == 'no_server')
return sprintf(_("%s can't connect: they have no server"), name);
if (st == 'server_off')
return sprintf(_("%s can't connect: their server is turned off"), name);
if (st == 'paused')
return sprintf(_("%s can't connect: they are paused"), name);
if (st == 'expired')
return sprintf(_("%s can't connect: their access has ended"), name);
if (st == 'quota')
return sprintf(_("%s can't connect: they used up their data"), name);
if (st == 'hours')
return sprintf(_("%s can't connect: it is outside their allowed hours"), name);
return sprintf(_("%s can't connect: %s"), name, st);
}
const ACCESS_TEXT = { lan: 'Home only', internet: 'Internet only', both: 'Home and Internet' };
/** "Bob · Phone can't be reached: it is turned off", by the device and its person's state. */
function cant_reach(who, disabled, st) {
if (disabled)
return sprintf(_("%s can't be reached: it is turned off"), who);
if (st == 'no_server')
return sprintf(_("%s can't be reached: they have no server"), who);
if (st == 'server_off')
return sprintf(_("%s can't be reached: their server is turned off"), who);
if (st == 'paused')
return sprintf(_("%s can't be reached: they are paused"), who);
if (st == 'expired')
return sprintf(_("%s can't be reached: their access has ended"), who);
if (st == 'quota')
return sprintf(_("%s can't be reached: they used up their data"), who);
if (st == 'hours')
return sprintf(_("%s can't be reached: it is outside their allowed hours"), who);
return sprintf(_("%s can't be reached: %s"), who, st);
}
/** A person's access as the admin page names it. */
function access_text(a) {
if (a == 'lan')
return _('Home only');
if (a == 'internet')
return _('Internet only');
if (a == 'both')
return _('Home and Internet');
return a;
}
/** "Bob has Internet only": the step where access stops a connection. */
function has_access(name, a) {
if (a == 'lan')
return sprintf(_('%s has Home only'), name);
if (a == 'internet')
return sprintf(_('%s has Internet only'), name);
return sprintf(_('%s has Home and Internet'), name);
}
/** "Bob reaches lan, guest." (the person's home networks), or that there is none. */
function reaches(name, devs) {
return length(devs) ? sprintf(_('%s reaches %s.'), name, join(', ', devs)) : sprintf(_('%s reaches no home network.'), name);
}
function step(ok, title, detail) {
return { ok: !!ok, title, detail: detail ?? '' };
@@ -65,7 +117,7 @@ function peer_of(dmp, d) {
/** What the device sends to the router: its configuration's AllowedIPs. */
function routed(m, srv, p, d) {
return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null };
return awg.allowed_ips(m, srv, p);
}
/** The home network (interface) of a server that holds an address. */
@@ -87,19 +139,19 @@ function router_addrs(snap) {
function person_ok(m, p, d, states) {
let st = states[p.id] ?? 'active';
if (d.disabled)
return step(false, `${d.name} is turned off`, 'Turn the device on again on its page.');
return step(false, sprintf(_('%s is turned off'), d.name), _('Turn the device on again on its page.'));
if (st != 'active')
return step(false, `${p.name} can't connect: ${STATE_TEXT[st] ?? st}`, '');
return step(true, `${p.name} is active`, ACCESS_TEXT[p.access]);
return step(false, cant_connect(p.name, st), '');
return step(true, sprintf(_('%s is active'), p.name), access_text(p.access));
}
function connected(dmp, d, who) {
let peer = peer_of(dmp, d);
if (!peer || !(peer.handshake > 0))
return step(false, `${who} has never connected`, 'There is no session the router could reach.');
return step(false, sprintf(_('%s has never connected'), who), _('There is no session the router could reach.'));
if (!live.online(dmp, d.id, peer))
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
return step(true, `${who} is connected`, '');
return step(false, sprintf(_("%s isn't connected right now"), who), _('The router reaches it only while its VPN is on.'));
return step(true, sprintf(_('%s is connected'), who), '');
}
/** A device → somewhere: the router, home, another device or the internet. */
@@ -107,18 +159,18 @@ function from_device(m, d, t, states, dmp, snap) {
let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null;
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
return [ step(false, sprintf(_('%s has no server'), d.name), '') ];
let steps = [ person_ok(m, p, d, states) ];
if (!steps[0].ok)
return steps;
let r = routed(m, srv, p, d);
let allowed = r.nets;
let allowed = routed(m, srv, p, d);
let via = (ip) => {
let hit = in_nets(ip, allowed);
let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
// The configuration's own words: the option and its value.
let what = `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
return hit
? step(true, `${r.what} sends it to the router`, what)
: step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`);
? step(true, _('Its configuration sends it to the router'), what)
: step(false, _("Its configuration doesn't send it to the router"), sprintf(_("%s: the device's own network handles it."), what));
};
// Another device.
@@ -126,27 +178,27 @@ function from_device(m, d, t, states, dmp, snap) {
let q = m.people[t.dev.person];
let who = `${q?.name ?? '?'} · ${t.dev.name}`;
if (t.dev.id == d.id)
return [ step(false, 'That is the same device', '') ];
return [ step(false, _('That is the same device'), '') ];
if (!q || q.server != p.server)
return stop(steps, step(false, `${who} is on another server`, 'Devices of different servers never reach each other.'));
return stop(steps, step(false, sprintf(_('%s is on another server'), who), _('Devices of different servers never reach each other.')));
if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${ACCESS_TEXT[p.access]}`, 'Only people with home access reach other devices.'));
return stop(steps, step(false, has_access(p.name, p.access), _('Only people with home access reach other devices.')));
if (!home_access(q))
return stop(steps, step(false, `${q.name} has ${ACCESS_TEXT[q.access]}`, 'Only devices of people with home access can be reached.'));
return stop(steps, step(false, has_access(q.name, q.access), _('Only devices of people with home access can be reached.')));
if (srv.mesh == 'off')
return stop(steps, step(false, `"Devices reach each other" is off on ${srv.name}`, 'Server → Access → Home network.'));
return stop(steps, step(false, sprintf(_('"Devices reach each other" is off on %s'), srv.name), _('Server → Access → Home network.')));
if (srv.mesh == 'circles' && q.id != p.id) {
let a = core.person_circle(m, p), b = core.person_circle(m, q);
if (!a || !b || a.id != b.id)
return stop(steps, step(false, `${p.name} and ${q.name} are not in one circle`,
`${p.name}: ${a?.name ?? 'no circle'} · ${q.name}: ${b?.name ?? 'no circle'}`));
push(steps, step(true, `Both are in ${a.name}`, 'Devices in one circle reach each other.'));
return stop(steps, step(false, sprintf(_('%s and %s are not in one circle'), p.name, q.name),
`${p.name}: ${a?.name ?? _('no circle')} · ${q.name}: ${b?.name ?? _('no circle')}`));
push(steps, step(true, sprintf(_('Both are in %s'), a.name), _('Devices in one circle reach each other.')));
}
else
push(steps, step(true, q.id == p.id ? `Both are ${p.name}'s devices` : 'Devices reach each other on this server', ''));
push(steps, step(true, q.id == p.id ? sprintf(_("Both are %s's devices"), p.name) : _('Devices reach each other on this server'), ''));
let st = states[q.id] ?? 'active';
if (st != 'active' || t.dev.disabled)
return stop(steps, step(false, `${who} can't be reached: ${t.dev.disabled ? 'it is turned off' : STATE_TEXT[st] ?? st}`, ''));
return stop(steps, step(false, cant_reach(who, t.dev.disabled, st), ''));
push(steps, via(t.ip));
push(steps, connected(dmp, t.dev, who));
return steps;
@@ -156,17 +208,20 @@ function from_device(m, d, t, states, dmp, snap) {
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)));
if (t.port == 53)
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
push(steps, step(true, sprintf(_('%s is this router: DNS is open to everyone'), t.ip), ''));
else if (portal)
push(steps, step(true, `${t.ip} is this router: the personal portal is open to everyone`, ''));
push(steps, step(true, sprintf(_('%s is this router: the personal portal is open to everyone'), t.ip), ''));
else if (!home_access(p))
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS and the portal on the router.`));
return stop(steps, step(false, sprintf(_('%s is this router'), t.ip), sprintf(p.access == 'lan'
? _('%s has Home only: only DNS and the portal on the router.')
: _('%s has Internet only: only DNS and the portal on the router.'), p.name)));
else {
// Like any home address: only on the networks the person reaches.
let h = core.person_home(srv, p, snap);
if (!h.all && !in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is this router on a network ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is this router`, h.all ? 'Home access includes the router.' : `On one of the networks ${p.name} reaches.`));
return stop(steps, step(false, sprintf(_("%s is this router on a network %s doesn't reach"), t.ip, p.name), reaches(p.name, h.devs)));
push(steps, step(true, sprintf(_('%s is this router'), t.ip),
h.all ? _('Home access includes the router.') : sprintf(_('On one of the networks %s reaches.'), p.name)));
}
push(steps, via(t.ip));
return steps;
@@ -175,14 +230,14 @@ function from_device(m, d, t, states, dmp, snap) {
// A tunnel address no device has.
let tn = in_tunnels(m, t.ip);
if (tn)
return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${tn}.`));
return stop(steps, step(false, sprintf(_('No device uses %s'), t.ip), sprintf(_('It is in the tunnel network %s.'), tn)));
// Home.
let sn = net.server_net(srv, snap);
let hdev = home_dev_of(srv, t.ip, snap);
if (hdev) {
if (p.access == 'internet')
return stop(steps, step(false, `${t.ip} is at home (${hdev})`, `${p.name} has Internet only.`));
return stop(steps, step(false, sprintf(_('%s is at home (%s)'), t.ip, hdev), sprintf(_('%s has Internet only.'), p.name)));
if (p.access == 'lan' && length(p.services)) {
let hit = null;
for (let sid in p.services) {
@@ -192,28 +247,32 @@ function from_device(m, d, t, states, dmp, snap) {
}
let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name));
if (!hit)
return stop(steps, step(false, `${t.ip}${t.port ? `:${t.port}` : ''} is not one of ${p.name}'s home services`, `Allowed: ${names}`));
push(steps, step(true, `${t.ip} is ${hit.name}, one of ${p.name}'s home services`,
length(hit.ports) ? `Ports ${join(', ', hit.ports)}` : 'All ports'));
return stop(steps, step(false, sprintf(_("%s is not one of %s's home services"), t.port ? `${t.ip}:${t.port}` : t.ip, p.name),
sprintf(_('Allowed: %s'), names)));
push(steps, step(true, sprintf(_("%s is %s, one of %s's home services"), t.ip, hit.name, p.name),
length(hit.ports) ? sprintf(_('Ports %s'), join(', ', hit.ports)) : _('All ports')));
}
else {
let h = core.person_home(srv, p, snap);
if (!in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`));
return stop(steps, step(false, sprintf(_("%s is in %s, which %s doesn't reach"), t.ip, hdev, p.name), reaches(p.name, h.devs)));
push(steps, step(true, sprintf(_('%s is in home network %s'), t.ip, hdev),
h.all ? _('Home access reaches every home network.') : sprintf(_('One of the networks %s reaches.'), p.name)));
}
push(steps, via(t.ip));
push(steps, step(true, 'The firewall lets it through', `${srv.ifname} → ${join(', ', sn.zones) || 'home'}`));
push(steps, step(true, _('The firewall lets it through'), `${srv.ifname} → ${join(', ', sn.zones) || _('home')}`));
return steps;
}
// Another private address, or the internet.
if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.'));
return stop(steps, step(false, sprintf(_("%s isn't in %s's home network"), t.ip, srv.name), _('Private addresses outside the home network are blocked.')));
if (p.access == 'lan')
return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`));
return stop(steps, step(true, sprintf(_('%s is on the internet'), t.ip),
sprintf(_("%s has Home only: their device's own internet reaches it, not the tunnel."), p.name)));
push(steps, via(t.ip));
push(steps, step(true, `${t.ip} is on the internet`, srv.lan_like ? 'It leaves like a home device would.' : `It leaves through ${sn.wan.dev ?? 'the WAN'}.`));
push(steps, step(true, sprintf(_('%s is on the internet'), t.ip), srv.lan_like ? _('It leaves like a home device would.')
: sn.wan.dev != null ? sprintf(_('It leaves through %s.'), sn.wan.dev) : _('It leaves through the WAN.')));
return steps;
}
@@ -222,22 +281,22 @@ function to_device(m, ip, d, states, dmp, snap) {
let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null;
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
return [ step(false, sprintf(_('%s has no server'), d.name), '') ];
let who = `${p.name} · ${d.name}`;
let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap);
if (!hdev)
return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ];
let steps = [ step(true, `${ip} is at home (${hdev})`, '') ];
return [ step(false, sprintf(_("%s isn't in %s's home network"), ip, srv.name), _("Only home devices reach people's devices.")) ];
let steps = [ step(true, sprintf(_('%s is at home (%s)'), ip, hdev), '') ];
if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`,
'Home devices reach only people with home access.'));
return stop(steps, step(false, p.access == 'lan' ? sprintf(_('%s has only some home services'), p.name) : has_access(p.name, p.access),
_('Home devices reach only people with home access.')));
let h = core.person_home(srv, p, snap);
if (!in_nets(ip, h.nets))
return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.'));
return stop(steps, step(false, sprintf(_("%s doesn't reach %s"), p.name, hdev), _('Networks a person does not reach cannot reach them either.')));
push(steps, person_ok(m, p, d, states));
if (!steps[length(steps) - 1].ok)
return steps;
push(steps, step(true, 'The firewall lets it through', `${join(', ', net.server_net(srv, snap).zones) || 'home'} → ${srv.ifname}`));
push(steps, step(true, _('The firewall lets it through'), `${join(', ', net.server_net(srv, snap).zones) || _('home')} → ${srv.ifname}`));
push(steps, connected(dmp, d, who));
return steps;
}
@@ -246,9 +305,9 @@ function to_device(m, ip, d, states, dmp, snap) {
export function check(m, from, to) {
let a = parse_target(m, from), b = parse_target(m, to);
if (!a)
die(`"${from}" is not a device or an IPv4 address.`);
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
if (!b)
die(`"${to}" is not a device or an IPv4 address.`);
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);
@@ -259,7 +318,7 @@ export function check(m, from, to) {
else if (b.dev)
steps = to_device(m, a.ip, b.dev, states, dmp, snap);
else
die('Choose a device on at least one side.');
die(_('Choose a device on at least one side.'));
let ok = length(filter(steps, (s) => !s.ok)) == 0;
return { ok, steps };
};
@@ -22,6 +22,7 @@ import * as nft from 'dawnline.nft';
import * as fw from 'dawnline.fw';
import * as netifd from 'dawnline.netifd';
import * as migrate from 'dawnline.migrate';
import { _, L_ } from 'dawnline.i18n';
const HOSTS_FILE = '/tmp/hosts/dawnline';
/** The network signature the last apply() worked from (the agent compares against it). */
@@ -93,9 +94,9 @@ function nft_result(err, present) {
return null;
}
if (was != err) {
log('Access rules', present
? "couldn't be updated — the previous rules stay, and changes to access wait until they load"
: "couldn't load — no device is loaded into the tunnels until they do", 'error', err);
log(L_('Access rules'), present
? L_("couldn't be updated - the previous rules stay, and changes to access wait until they load")
: L_("couldn't load - no device is loaded into the tunnels until they do"), 'error', err);
ensure_dir(RUN_DIR);
writefile(NFT_ERR, err);
}
@@ -138,18 +139,19 @@ export function firewall_drift(m) {
/**
* What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices. Null when all went in.
* failed, or a server did not accept its devices (sentences in the caller's
* language, with what nft or awg said). Null when all went in.
*/
function sync_warning(m, table, peers) {
let out = [];
if (table != null)
push(out, nft.present()
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.`
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`);
? sprintf(_("Access rules couldn't be updated (%s): the previous rules stay, so this change isn't in effect yet."), table)
: sprintf(_("Access rules couldn't load (%s): no device is loaded into the tunnels until they do."), table));
for (let id, r in peers)
if (r != 'ok' && r != 'down')
push(out, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`);
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null;
push(out, sprintf(_("Couldn't load devices into %s: %s."), m.servers[id]?.name ?? id, r));
return length(out) ? join(' ', [ ...out, _('Open Diagnostics → Health.') ]) : null;
}
/*
@@ -242,7 +244,7 @@ export function apply(opts) {
return { network, firewall, lp, peers: s.peers, warning: s.warning };
});
loop.remember(r.lp);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning };
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: loop.error_text(r.lp.error) } : !r.lp.off, peers: r.peers, warning: r.warning };
};
/** Remove everything Dawnline created (used by the uninstaller). */
@@ -1,8 +1,8 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters and what the
// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the
// disguise off.
// 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 {
@@ -13,6 +13,7 @@ import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
import { _, L_ } from 'dawnline.i18n';
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
@@ -98,15 +99,15 @@ export function genpsk() {
export function new_keys(public_key) {
let psk = genpsk();
if (!valid_key(psk))
die('Key generation failed (no random data).');
die(_('Key generation failed (no random data).'));
if (public_key) {
if (!valid_key(public_key))
die('Invalid public key.');
die(_('Invalid public key.'));
return { public_key, preshared_key: psk };
}
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
die(_('Key generation failed (is amneziawg-tools installed?).'));
return { private_key: priv, public_key: pub, preshared_key: psk };
};
@@ -114,7 +115,7 @@ export function new_keys(public_key) {
export function server_keys() {
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
die(_('Key generation failed (is amneziawg-tools installed?).'));
return { private_key: priv, public_key: pub };
};
@@ -172,10 +173,11 @@ export function caps() {
};
/**
* Why this AmneziaWG cannot run a server's disguise values, or null: a 3.1
* preset after a rollback to a 2.0 build would come up without the header
* protection every device expects, so such a server is kept down instead
* (dawnline.netifd).
* Why this AmneziaWG cannot run a server's disguise values, as a reason to
* keep the server down (blocked_text): { code: 'disguise', need, installed }
* (installed null: none), or null when it can. A 3.1 preset after a rollback
* to a 2.0 build would come up without the header protection every device
* expects, so such a server is kept down instead (dawnline.netifd).
*/
export function obf_unsupported(o) {
let c = caps();
@@ -185,9 +187,9 @@ export function obf_unsupported(o) {
let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ];
let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0;
if (has(v3) && !c.v3)
return `its disguise needs AmneziaWG 3.1 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
return { code: 'disguise', need: '3.1', installed: c.kmod ?? c.tools };
if ((has(v2) || ranged) && !c.v2)
return `its disguise needs AmneziaWG 2.0 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
return { code: 'disguise', need: '2.0', installed: c.kmod ?? c.tools };
return null;
};
@@ -293,9 +295,9 @@ export function obf_errors(o) {
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, `${k} must be a number or range`);
push(errs, sprintf(_('%s must be a number or range'), k));
else if (hs[v])
push(errs, 'h1-h4 must be distinct');
push(errs, _('h1-h4 must be distinct'));
hs[v] = true;
}
return errs;
@@ -482,7 +484,7 @@ export function sync_peers(m, states) {
unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0)
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
slog('awg', 'error', L_("couldn't load devices into the tunnel"), trim(r.out), srv.name);
}
return res;
};
@@ -528,6 +530,56 @@ export function server_state(srv) {
return { up: !!st?.up, uptime: st?.uptime ?? 0 };
};
/* ---------- why a tunnel is kept down ---------- */
/*
* dawnline.netifd keeps a server's tunnel down for a reason, kept per server
* in core.BLOCKED and loaded as `srv.blocked`. apply writes it, at boot and
* from the agent with no language, so it holds a code and its values, made
* into text when read:
* { 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()
* Files written by older versions hold the English fragment ("has an invalid
* interface name …"), shown as it is.
*/
/** A reason as the service log says it after the server's name: English, like every log line. */
export function blocked_note(r) {
if (type(r) != 'object')
return `${r}`;
if (r.code == 'ifname')
return sprintf(L_('has an invalid interface name "%s"'), r.ifname);
if (r.code == 'taken')
return sprintf(L_("can't use the network interface %s: it exists and isn't Dawnline's"), r.ifname);
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);
return L_('is kept down');
};
/**
* 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
* is not kept down.
*/
export function blocked_text(srv) {
let r = srv?.blocked;
if (!r)
return null;
if (type(r) != 'object')
return `${srv.name} ${r}.`;
if (r.code == 'ifname')
return sprintf(_('%s has an invalid interface name "%s".'), srv.name, r.ifname);
if (r.code == 'taken')
return sprintf(_("%s can't use the network interface %s: it exists and isn't Dawnline's."), srv.name, r.ifname);
if (r.code == 'disguise')
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);
return sprintf(_('%s is kept down.'), srv.name);
};
/* ---------- watchdog ---------- */
/** Why a tunnel is down, from netifd and the last related syslog lines. */
@@ -553,19 +605,20 @@ export function probes(m, ctx) {
// AmneziaWG itself first: without it no tunnel can run (they come back on the next pass).
// Missing packages and an unknown protocol are reported once; only the module can be loaded here.
let st = state();
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' };
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: L_('is ready again') };
if (!st.tools || !st.kmod) {
push(out, { ...base, ok: false, repair: null,
problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`,
detail: () => `Missing: ${join(', ', st.missing)}.` });
problem: st.tools ? L_("kernel module isn't installed: no tunnel can run - install it in Dawnline → Components")
: L_("isn't installed: no tunnel can run - install it in Dawnline → Components"),
detail: () => sprintf(L_('Missing: %s.'), join(', ', st.missing)) });
return out;
}
push(out, { ...base, ok: st.loaded && st.handler,
problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot",
problem: !st.loaded ? L_("kernel module isn't loaded") : L_("isn't known to the network service - restart the network or reboot"),
detail: !st.loaded
? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4")
: () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
: () => L_('netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.'),
repair: !st.loaded ? { what: L_('loading it'), run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
});
// Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one.
if (st.loaded && !st.handler)
@@ -574,13 +627,13 @@ export function probes(m, ctx) {
// A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted:
// an interface of the same name that isn't Dawnline's may be your LAN.
let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null;
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"`
: own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null);
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? { code: 'ifname', ifname: srv.ifname }
: own != null && own != srv.id ? { code: 'taken', ifname: srv.ifname } : null);
if (why) {
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: why, back: 'AmneziaWG is running again',
detail: () => 'Choose another interface name in the server settings.',
problem: blocked_note(why), back: L_('AmneziaWG is running again'),
detail: () => L_('Choose another interface name in the server settings.'),
});
continue;
}
@@ -588,10 +641,11 @@ export function probes(m, ctx) {
let up = !!s?.up;
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port),
problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`,
back: `AmneziaWG is running again · accepting connections on port ${srv.port}`,
problem: !s ? L_('AmneziaWG is missing from the router') : !up ? L_("AmneziaWG isn't running")
: sprintf(L_("AmneziaWG isn't accepting connections on port %d"), srv.port),
back: sprintf(L_('AmneziaWG is running again · accepting connections on port %d'), srv.port),
detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply },
repair: s ? { what: L_('restarting it'), run: () => system(`ifup ${q(srv.ifname)}`) } : { what: L_('setting it up again'), run: ctx.reapply },
});
}
return out;
@@ -13,6 +13,7 @@ import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as health from 'dawnline.health';
import { _ } from 'dawnline.i18n';
const BACKUP_DIR = `${DATA_DIR}/backups`;
/**
@@ -51,17 +52,16 @@ export function config_errors(c) {
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
let who = `Server ${srv.name}`;
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
push(errs, `${who}: ${e}`);
push(errs, sprintf(_('Server %s: %s'), srv.name, e));
if (ifnames[srv.ifname])
push(errs, `${who}: interface ${srv.ifname} is also used by ${ifnames[srv.ifname]}.`);
push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
ifnames[srv.ifname] = srv.name;
let t = nc.get('network', srv.ifname);
if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null)))
push(errs, `${who}: ${srv.ifname} is one of the router's own network interfaces.`);
push(errs, sprintf(_("Server %s: %s is one of the router's own network interfaces."), srv.name, srv.ifname));
if (ports[srv.port])
push(errs, `${who}: UDP ${srv.port} is also used by ${ports[srv.port]}.`);
push(errs, sprintf(_('Server %s: UDP %s is also used by %s.'), srv.name, srv.port, ports[srv.port]));
ports[srv.port] = srv.name;
if (srv.subnet)
push(subnets, srv.subnet);
@@ -75,10 +75,10 @@ function check_config_dir(dir) {
// Its own delta directory: changes staged in LuCI must not leak into the check.
let c = cursor(dir, `${dir}/.delta`);
if (!c.load('dawnline'))
die('The configuration in this file cannot be read.');
die(_('The configuration in this file cannot be read.'));
let errs = config_errors(c);
if (length(errs))
die(`This configuration can't be used: ${join(' ', errs)}`);
die(sprintf(_("This configuration can't be used: %s"), join(' ', errs)));
}
/** A private scratch directory under RUN_DIR (the caller removes it). */
@@ -129,7 +129,8 @@ export function backup_create(reason, keep) {
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
unlink(tmp);
die(`Backup failed: ${trim(r.out) || 'the archive could not be written (is the flash full?)'}`);
let why = trim(r.out);
die(why ? sprintf(_('Backup failed: %s'), why) : _('Backup failed: the archive could not be written (is the flash full?)'));
}
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let by_kind = {};
@@ -144,10 +145,10 @@ export function backup_create(reason, keep) {
function backup_path(name) {
if (!match(name ?? '', NAME))
die('Invalid backup name.');
die(_('Invalid backup name.'));
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
die(_('Backup not found.'));
return p;
}
@@ -158,24 +159,24 @@ function backup_path(name) {
function check_archive(path) {
let r = sh(`tar -tvzf ${q(path)}`);
if (r.code != 0)
die('Not a valid backup archive.');
die(_('Not a valid backup archive.'));
let has_config = false, total = 0;
for (let line in split(trim(r.out), '\n')) {
let f = split(trim(line), /[ \t]+/);
let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, '');
// "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b".
if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0)
die(`Unexpected entry in backup: ${name}`);
die(sprintf(_('Unexpected entry in backup: %s'), name));
if (index(FILES, name) < 0)
die(`Unexpected file in backup: ${name}`);
die(sprintf(_('Unexpected file in backup: %s'), name));
total += +(f[2] ?? 0) || 0;
if (name == 'etc/config/dawnline')
has_config = true;
}
if (!has_config)
die('Backup does not contain /etc/config/dawnline.');
die(_('Backup does not contain /etc/config/dawnline.'));
if (total > MAX_UNPACKED)
die('Backup is too large.');
die(_('Backup is too large.'));
}
/**
@@ -190,7 +191,7 @@ function install_files(dir) {
for (let f in FILES) {
let data = readfile(`${dir}/${f}`);
if (data != null && !write_file(`/${f}`, data, 0o600))
die(`Couldn't write /${f}. Is the flash full?`);
die(sprintf(_("Couldn't write %s. Is the flash full?"), `/${f}`));
}
}
catch (e) {
@@ -208,7 +209,7 @@ export function backup_restore(name, path) {
try {
let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`);
if (r.code != 0)
die('Not a valid backup archive.');
die(_('Not a valid backup archive.'));
check_config_dir(`${dir}/etc/config`);
backup_create('pre-restore', name);
install_files(dir);
@@ -238,7 +239,7 @@ export function backup_read(name) {
export function backup_upload(data_b64) {
let data = b64dec(data_b64 ?? '');
if (!data || length(data) > 4 * 1024 * 1024)
die('Upload is empty or too large.');
die(_('Upload is empty or too large.'));
ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data);
@@ -273,23 +274,23 @@ export function export_json() {
/** An export as /etc/config/dawnline text; dies on anything that is not one. */
function export_to_uci(data) {
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
die('Not a Dawnline export.');
die(_('Not a Dawnline export.'));
let types = { settings: true, server: true, person: true, device: true, service: true, circle: true };
let esc = (x) => replace(`${x}`, "'", "'\\''");
let lines = [];
for (let s in data.sections) {
if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
die(`Invalid section ${s?.['.name']}.`);
die(sprintf(_('Invalid section %s.'), s?.['.name']));
push(lines, `config ${s['.type']} '${s['.name']}'`);
for (let k, v in s) {
if (substr(k, 0, 1) == '.')
continue;
if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))
die(`Invalid option ${k}.`);
die(sprintf(_('Invalid option %s.'), k));
if (type(v) == 'array')
for (let x in v) {
if (type(x) != 'string')
die(`Invalid option ${k}.`);
die(sprintf(_('Invalid option %s.'), k));
push(lines, `\tlist ${k} '${esc(x)}'`);
}
else
@@ -317,6 +318,6 @@ export function import_json(data) {
let ok = write_file('/etc/config/dawnline', text, 0o600);
unlock(l);
if (!ok)
die("Couldn't write /etc/config/dawnline. Is the flash full?");
die(sprintf(_("Couldn't write %s. Is the flash full?"), '/etc/config/dawnline'));
return apply.apply();
};
@@ -4,9 +4,10 @@
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_key, valid_host, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import { _, N_ } from 'dawnline.i18n';
import * as net from 'dawnline.net';
import * as schema from 'dawnline.schema';
import { policy as updates_policy } from 'dawnline.updates';
@@ -481,35 +482,35 @@ export function new_code() {
export function create_person(c, m, a) {
if (!valid_name(a.name))
fail(NAME_RULE);
fail(name_rule());
// The id is a UCI section name: letters, digits and underscores only (a dash
// makes uci drop the section). Repeated names get _2, _3, …
let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
if (!match(base, /^[a-z0-9_]{1,32}$/))
fail('The id may use lowercase letters, digits and underscores.');
fail(_('The id may use lowercase letters, digits and underscores.'));
// Any kind of section (store.id_taken, which imports this module).
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] ||
index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0;
let slug = base;
for (let n = 2; taken(slug); n++) {
if (n > 99)
fail(`"${base}" is already taken.`);
fail(sprintf(_('"%s" is already taken.'), base));
slug = `${substr(base, 0, 28)}_${n}`;
}
let srv_id = a.server ?? keys(m.servers)[0];
if (!m.servers[srv_id])
fail('Set up a server first.');
fail(_('Set up a server first.'));
let access = a.access ?? 'internet';
if (index(ACCESS, access) < 0)
fail('Access must be lan, internet or both.');
fail(_('Access must be lan, internet or both.'));
let limit = toint(a.device_limit, m.settings.default_device_limit);
if (limit < 1 || limit > 32)
fail('Device limit must be between 1 and 32.');
fail(_('Device limit must be between 1 and 32.'));
if (a.expires && !valid_date(a.expires))
fail('End date must be YYYY-MM-DD.');
fail(_('End date must be YYYY-MM-DD.'));
let quota = num(a.quota_gb, 0);
if (quota < 0 || quota > 100000)
fail('Monthly data must be a positive number of GB.');
fail(_('Monthly data must be a positive number of GB.'));
c.set(CONFIG, slug, 'person');
c.set(CONFIG, slug, 'server', srv_id);
@@ -535,52 +536,53 @@ export function create_person(c, m, a) {
export function update_person(c, m, id, a) {
let p = m.people[id];
if (!p)
fail('Unknown person.');
fail(_('Unknown person.'));
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
if (a.name != null) {
if (!valid_name(a.name))
fail(NAME_RULE);
fail(name_rule());
set('name', trim(a.name));
}
if (a.access != null) {
if (index(ACCESS, a.access) < 0)
fail('Access must be lan, internet or both.');
fail(_('Access must be lan, internet or both.'));
set('access', a.access);
}
if (a.device_limit != null) {
let n = toint(a.device_limit, 0);
if (n < 1 || n > 32)
fail('Device limit must be between 1 and 32.');
fail(_('Device limit must be between 1 and 32.'));
let have = length(p.devices);
if (n < have)
fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`);
fail(sprintf(N_(have, '%s already has %d device. Remove one first to lower the limit to %d.',
'%s already has %d devices. Remove one first to lower the limit to %d.'), p.name, have, n));
set('device_limit', n);
}
if (a.expires != null) {
if (a.expires != '' && !valid_date(a.expires))
fail('End date must be YYYY-MM-DD.');
fail(_('End date must be YYYY-MM-DD.'));
set('expires', a.expires);
}
if (a.expire_action != null) {
if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0)
fail('Unknown end action.');
fail(_('Unknown end action.'));
set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action);
}
if (a.dns_mode != null) {
if (index([ 'device', 'home' ], a.dns_mode) < 0)
fail('Unknown DNS choice.');
fail(_('Unknown DNS choice.'));
set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode);
}
if (a.expire_warn != null) {
let n = toint(a.expire_warn, -1);
if (n < 0 || n > 60)
fail('Warning must be 0-60 days.');
fail(_('Warning must be 0-60 days.'));
set('expire_warn', n == 3 ? '' : n);
}
if (a.quota_gb != null) {
let q = num(a.quota_gb, -1);
if (a.quota_gb != '' && (q < 0 || q > 100000))
fail('Data limit must be a positive number of GB.');
fail(_('Data limit must be a positive number of GB.'));
set('quota_gb', q > 0 ? q : '');
}
if (a.quota_period != null)
@@ -588,13 +590,13 @@ export function update_person(c, m, id, a) {
if (a.bonus_gb != null) {
let b = num(a.bonus_gb, -1);
if (b < 0 || b > 100000)
fail('Extra data must be a positive number of GB.');
fail(_('Extra data must be a positive number of GB.'));
set('bonus_gb', b > 0 ? b : '');
set('bonus_month', b > 0 ? month_key() : '');
}
if (a.hours != null) {
if (a.hours != '' && !parse_hours(a.hours))
fail('Hours must look like 07:00-23:00.');
fail(_('Hours must look like 07:00-23:00.'));
set('hours', a.hours);
}
if (a.note != null)
@@ -602,7 +604,7 @@ export function update_person(c, m, id, a) {
if (type(a.services) == 'array') {
for (let sid in a.services)
if (!m.services[sid])
fail(`Unknown service ${sid}.`);
fail(sprintf(_('Unknown service %s.'), sid));
if (length(a.services))
c.set(CONFIG, id, 'service', a.services);
else
@@ -611,7 +613,7 @@ export function update_person(c, m, id, a) {
if (a.circle != null) {
let ci = m.circles[a.circle];
if (a.circle != '' && (!ci || ci.server != p.server))
fail('Unknown circle.');
fail(_('Unknown circle.'));
set('circle', a.circle);
}
// Another server: every device gets an address in its tunnel (so each
@@ -619,13 +621,13 @@ export function update_person(c, m, id, a) {
// server's and go.
if (a.server != null && a.server != '' && a.server != p.server) {
if (!m.servers[a.server])
fail('Unknown server.');
fail(_('Unknown server.'));
set('server', a.server);
p.server = a.server;
for (let did in p.devices) {
let addr = alloc_address(m, m.servers[a.server]);
if (!addr)
fail(`No free address left on ${m.servers[a.server].name}.`);
fail(sprintf(_('No free address left on %s.'), m.servers[a.server].name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
@@ -652,29 +654,29 @@ export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {};
let p = m.people[person_id];
if (!p)
fail('Unknown person.');
fail(_('Unknown person.'));
let srv = m.servers[p.server];
if (!srv)
fail('The person has no server.');
fail(_('The person has no server.'));
name = trim(name ?? '');
if (!valid_name(name))
fail('Enter a device name (up to 48 characters).');
fail(_('Enter a device name (up to 48 characters).'));
if (index(KINDS, kind) < 0)
kind = 'other';
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
fail(`Device limit reached (${p.device_limit}).`);
fail(sprintf(_('Device limit reached (%d).'), p.device_limit));
for (let id in p.devices)
if (lc(m.devices[id].name) == lc(name))
fail(`"${name}" already exists.`);
fail(sprintf(_('"%s" already exists.'), name));
let addr = alloc_address(m, srv);
if (!addr)
fail('No free addresses left in the server subnet.');
fail(_('No free addresses left in the server subnet.'));
let k = opts.keys ?? {};
if (!valid_key(k.public_key))
fail('Key generation failed (is amneziawg-tools installed?).');
fail(_('Key generation failed (is amneziawg-tools installed?).'));
for (let o, d in m.devices)
if (d.public_key == k.public_key)
fail('This key is already in use.');
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 ?? '',
@@ -699,13 +701,13 @@ export function create_device(c, m, person_id, name, kind, opts) {
export function rename_device(c, m, id, name) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
fail(_('Unknown device.'));
name = trim(name ?? '');
if (!valid_name(name))
fail('Enter a device name (up to 48 characters).');
fail(_('Enter a device name (up to 48 characters).'));
for (let o in m.people[d.person]?.devices ?? [])
if (o != id && lc(m.devices[o].name) == lc(name))
fail(`"${name}" already exists.`);
fail(sprintf(_('"%s" already exists.'), name));
c.set(CONFIG, id, 'name', name);
d.name = name;
};
@@ -713,7 +715,7 @@ export function rename_device(c, m, id, name) {
export function delete_device(c, m, id) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
fail(_('Unknown device.'));
c.delete(CONFIG, id);
let p = m.people[d.person];
if (p)
@@ -725,9 +727,9 @@ export function delete_device(c, m, id) {
export function rotate_device(c, m, id, keys) {
let d = m.devices[id];
if (!d)
fail('Unknown device.');
fail(_('Unknown device.'));
if (!valid_key(keys?.public_key) || !keys?.private_key)
fail('Key generation failed.');
fail(_('Key generation failed.'));
c.set(CONFIG, id, 'private_key', keys.private_key);
c.set(CONFIG, id, 'public_key', keys.public_key);
if (keys.preshared_key)
@@ -737,7 +739,7 @@ export function rotate_device(c, m, id, keys) {
export function delete_person(c, m, id) {
let p = m.people[id];
if (!p)
fail('Unknown person.');
fail(_('Unknown person.'));
for (let d in p.devices)
c.delete(CONFIG, d);
c.delete(CONFIG, id);
@@ -757,20 +759,20 @@ export function private_cidr(c) {
export function server_errors(m, srv, others_subnets) {
let errs = [];
if (!valid_ifname(srv.ifname))
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
push(errs, _('Interface name: 1-12 lowercase letters, digits or _.'));
if (srv.port < 1 || srv.port > 65535)
push(errs, 'Port must be 1-65535.');
push(errs, _('Port must be 1-65535.'));
let c = parse_cidr(srv.subnet);
if (!c)
push(errs, 'Subnet must look like 10.77.0.0/24.');
push(errs, _('Subnet must look like 10.77.0.0/24.'));
else
for (let o in others_subnets ?? []) {
let oc = parse_cidr(o);
if (oc && cidr_overlaps(c, oc))
push(errs, `Subnet overlaps ${o}.`);
push(errs, sprintf(_('Subnet overlaps %s.'), o));
}
if (srv.endpoint != '' && !valid_host(srv.endpoint))
push(errs, 'Endpoint must be a hostname or IP address.');
push(errs, _('Endpoint must be a hostname or IP address.'));
return errs;
};
@@ -788,52 +790,55 @@ export function model_errors(m) {
let errs = [];
let codes = {}, addrs = {};
for (let id, p in m.people) {
let who = `Person ${p.name}`;
if (p.server != '' && !m.servers[p.server])
push(errs, `${who}: server ${p.server} does not exist.`);
push(errs, sprintf(_('Person %s: server %s does not exist.'), p.name, p.server));
if (p.circle != '' && !m.circles[p.circle])
push(errs, `${who}: circle ${p.circle} does not exist.`);
push(errs, sprintf(_('Person %s: circle %s does not exist.'), p.name, p.circle));
for (let sid in p.services)
if (!m.services[sid])
push(errs, `${who}: home service ${sid} does not exist.`);
push(errs, sprintf(_('Person %s: home service %s does not exist.'), p.name, sid));
if (p.code != '') {
if (codes[p.code])
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`);
push(errs, sprintf(_('Person %s: has the same personal link as %s.'), p.name, codes[p.code]));
codes[p.code] = p.name;
}
}
for (let id, d in m.devices) {
let p = m.people[d.person];
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
if (!p) {
push(errs, `${who}: person ${d.person} does not exist.`);
push(errs, sprintf(_('Device %s: person %s does not exist.'), d.name, d.person));
continue;
}
let say = (msg, ...args) => push(errs, sprintf(msg, d.name, p.name, ...args));
if (!valid_key(d.public_key))
push(errs, `${who}: the public key is not a key.`);
say(_('Device %s of %s: the public key is not a key.'));
if (d.private_key != '' && !valid_key(d.private_key))
push(errs, `${who}: the private key is not a key.`);
say(_('Device %s of %s: the private key is not a key.'));
if (d.preshared_key != '' && !valid_key(d.preshared_key))
push(errs, `${who}: the preshared key is not a key.`);
say(_('Device %s of %s: the preshared key is not a key.'));
let n = ip2int(d.address);
if (n == null) {
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`);
if (d.address)
say(_('Device %s of %s: address %s is not a plain IPv4 address.'), d.address);
else
say(_('Device %s of %s: address (none) is not a plain IPv4 address.'));
continue;
}
let srv = m.servers[p.server];
let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last))
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`);
say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
else if (t && n == t.first)
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`);
say(_("Device %s of %s: address %s is the router's own address on %s."), d.address, srv.name);
let key = `${p.server} ${d.address}`;
if (addrs[key])
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`);
addrs[key] = who;
let o = addrs[key];
if (o)
say(_('Device %s of %s: address %s is also used by device %s of %s.'), d.address, o.device, o.person);
addrs[key] = { device: d.name, person: p.name };
}
for (let id, ci in m.circles)
if (!m.servers[ci.server])
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`);
push(errs, sprintf(_('Circle %s: server %s does not exist.'), ci.name, ci.server));
return errs;
};
@@ -854,7 +859,7 @@ export function renumber_server(c, m, srv, subnet) {
for (let did in p.devices) {
let addr = alloc_address(m, srv);
if (!addr)
fail(`${subnet} has no room for every device on ${srv.name}.`);
fail(sprintf(_('%s has no room for every device on %s.'), subnet, srv.name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
@@ -13,6 +13,7 @@ import * as awg from 'dawnline.awg';
import * as apply from 'dawnline.apply';
import * as live from 'dawnline.live';
import * as store from 'dawnline.store';
import { _ } from 'dawnline.i18n';
/** AmneziaWG is on the router, so device keys can be made and loaded. */
export function ready() {
@@ -23,7 +24,8 @@ export function ready() {
export function need_awg() {
if (!awg.installed()) {
let miss = awg.state().missing ?? [];
die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`);
die(length(miss) ? sprintf(_('AmneziaWG is not installed (%s): install it in Dawnline → Components.'), join(', ', miss))
: _('AmneziaWG is not installed: install it in Dawnline → Components.'));
}
};
@@ -31,9 +33,9 @@ export function need_awg() {
function own(m, id, opts) {
let d = m.devices[id];
if (!d || (opts.person != null && d.person != opts.person))
die(opts.person != null ? 'Device not found.' : 'Unknown device.');
die(opts.person != null ? _('Device not found.') : _('Unknown device.'));
if (opts.by == 'portal' && d.disabled)
die('The admin has turned this device off.');
die(_('The admin has turned this device off.'));
return d;
}
@@ -57,7 +59,7 @@ 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.');
die(_('Only the admin can turn devices off.'));
let d0 = store.transact((c, m) => {
let d = own(m, id, opts);
let was = { ...d };
@@ -8,6 +8,7 @@
import { stat, popen, access } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
/** Prefixes that fetch github.com files when GitHub itself is unreachable. */
export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ];
@@ -54,11 +55,11 @@ function api_json(url) {
return null;
}
if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i)))
die('GitHub API rate limit reached: try again in an hour.');
die(_('GitHub API rate limit reached: try again in an hour.'));
if (r.status == 404)
return null;
if (r.status >= 400)
die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`);
die(sprintf(_('GitHub: %s'), j?.message ?? `HTTP ${r.status}`));
return j;
}
@@ -209,18 +210,18 @@ export function download(url, dest, o) {
for (let i, u in tries) {
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (i > 0)
o.log?.(`Trying mirror ${host}`);
o.log?.(sprintf(_('Trying mirror %s'), host));
let r = have_curl()
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
if (!want || sha256(dest) == want)
return u;
o.log?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`);
o.log?.(sprintf(_("Warning: %s sent a file that does not match GitHub's sha256, discarded"), host));
}
system(`rm -f ${q(dest)}`);
if (i == 0 && length(tries) > 1)
o.log?.('GitHub did not answer, trying mirrors');
o.log?.(_('GitHub did not answer, trying mirrors'));
}
return null;
};
@@ -1,8 +1,10 @@
// Dawnline — Health: what the router has and lacks (packages, listeners,
// networks), the checks shown on Diagnostics → Health, and their fixes.
// The checks' texts are in the language of the call (dawnline.i18n).
import { readfile, stat, lsdir } from 'fs';
import { cursor } from 'uci';
import { _, N_ } from 'dawnline.i18n';
import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -174,43 +176,12 @@ export function foreign_subnets() {
/*
* Checks are named for the healthy state ("Clock is set"); a failed one also
* gets the problem in words for notices ("Clock isn't set"). Longest names
* first; a server's name after the check name is kept.
* gets the problem in words for notices ("Clock isn't set"), passed with it.
* A server's checks carry its name after both (` (Home)`, with several servers).
*/
const PROBLEM = [
[ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ],
[ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ],
[ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ],
[ 'AmneziaWG port is free', 'AmneziaWG port is taken' ],
[ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ],
[ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ],
[ 'AmneziaWG running', 'AmneziaWG is down' ],
[ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ],
[ 'Portal address points here', 'Portal address doesn’t point here' ],
[ 'Portal address', 'Portal address isn’t set' ],
[ 'Portal certificate', 'Portal certificate needs attention' ],
[ 'Personal portal', 'Personal portal isn’t working' ],
[ 'Plain HTTP links', 'Portal links use plain HTTP' ],
[ 'Internet like a home device', 'Internet like a home device isn’t working' ],
[ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ],
[ 'Background agent running', 'Background agent isn’t running' ],
[ 'Access rules loaded', 'Access rules aren’t loaded' ],
[ 'Server configured', 'No server yet' ],
[ 'Public address', 'Public address needs attention' ],
[ 'Clock is set', 'Clock isn’t set' ],
];
function problem_of(title) {
for (let p in PROBLEM)
if (substr(title, 0, length(p[0])) == p[0])
return p[1] + substr(title, length(p[0]));
return title;
}
/** problem: the failed check in words, when the table's wording does not fit the case. */
function check(id, title, status, detail, fix, problem) {
let bad = status == 'warn' || status == 'error';
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null };
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? title) : null };
}
/**
@@ -222,13 +193,14 @@ function replies(m) {
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
}
function reply_check(id, title, proto, port, r) {
function reply_check(id, title, problem, proto, port, r) {
let via = join(', ', r.diverts);
let from = `${uc(proto)} ${port}`;
return check(id, title, r.ok ? 'ok' : 'error',
!r.ok ? `Answers from ${uc(proto)} ${port} are swallowed by a proxy on the router (${via}): clients get no reply.`
: length(r.diverts) ? `Answers from ${uc(proto)} ${port} go straight out. A proxy on the router diverts its own traffic (${via}); these answers skip it.`
: `Answers from ${uc(proto)} ${port} go straight out.`,
r.ok ? null : 'apply');
!r.ok ? sprintf(_('Answers from %s are swallowed by a proxy on the router (%s): clients get no reply.'), from, via)
: length(r.diverts) ? sprintf(_('Answers from %s go straight out. A proxy on the router diverts its own traffic (%s); these answers skip it.'), from, via)
: sprintf(_('Answers from %s go straight out.'), from),
r.ok ? null : 'apply', problem);
}
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
@@ -260,29 +232,36 @@ export function endpoint_facts(srv, host) {
};
};
/** The facts in words: { status: ok|warn|error, text }. `proto_note` names what must get through ("UDP 4500"). */
/**
* 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").
*/
export function endpoint_words(f, proto_note) {
if (!f.host)
return { status: 'error', text: 'No public address: devices will not know where to connect.' };
return { status: 'error', text: _('No public address: devices will not know where to connect.') };
if (!length(f.ips))
return { status: 'error', text: `${f.host} does not resolve.` };
return { status: 'error', text: sprintf(_('%s does not resolve.'), f.host) };
if (f.cloudflare)
return { status: 'error', text: `${f.host} → ${join(', ', f.ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.` };
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)
return { status: f.kind == 'public' ? 'warn' : 'ok', text: `${f.host} → ${join(', ', f.ips6)}: IPv6 only, so only devices with IPv6 connect${f.kind == 'public' ? ` (the router's IPv4 ${f.wan} has no name)` : ''}.` };
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)) };
if (f.kind == 'cgnat' || f.kind == 'private')
return { status: 'warn', text: f.kind == 'cgnat'
? `The WAN address ${f.wan} is CGNAT (shared by the ISP): ${proto_note} cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.`
: `The WAN address ${f.wan} is private: this router is behind another one. Forward ${proto_note} on it, or devices cannot connect.` };
? 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: `${f.host} points at ${join(', ', f.ips4)}, not this router (WAN ${f.wan}). Check your DNS / DDNS.` };
return { status: 'ok', text: f.here ? `${f.host} points at this router (${f.wan}).` : `${f.host} → ${join(', ', f.ips)}` };
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) };
// 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)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
function endpoint_check(id, title, srv, host, proto_note) {
function endpoint_check(id, title, problem, srv, host, proto_note) {
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
return check(id, title, w.status, w.text);
return check(id, title, w.status, w.text, null, problem);
}
/**
@@ -306,7 +285,9 @@ function policy_routing() {
return out;
}
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
function no_proto() {
return _("netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).");
}
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
@@ -318,27 +299,29 @@ function overlay_free_kb() {
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.load();
let title = 'AmneziaWG installed';
if (length(st.missing ?? [])) {
let title = _('AmneziaWG installed');
let missing = st.missing ?? [];
if (length(missing)) {
// The module was built for the kernel of the firmware it was installed on.
let kc = builds.kernel_changed();
if (kc && index(st.missing, 'kmod-amneziawg') >= 0)
if (kc && index(missing, 'kmod-amneziawg') >= 0)
return check('awg', title, 'error',
`The firmware changed (kernel ${kc.was} → ${kc.now}): the AmneziaWG build installed for it is gone. Install the build for this firmware.`,
'install:awg', 'AmneziaWG needs a build for the new firmware');
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
sprintf(_('The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware.'), kc.was, kc.now),
'install:awg', _('AmneziaWG needs a build for the new firmware'));
return check('awg', title, 'error', sprintf(N_(length(missing), '%s is missing.', '%s are missing.'), join(', ', missing)), 'install:awg',
_('AmneziaWG isn’t installed'));
}
if (!st.loaded) {
// load() tried it: the second modprobe only repeats why.
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
return check('awg', title, 'error',
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
'AmneziaWG’s kernel module doesn’t load');
why ? sprintf(_("The kernel module doesn't load: %s Reinstall a build for this kernel in Components."), why)
: _("The kernel module doesn't load. Reinstall a build for this kernel in Components."),
'updates', _('AmneziaWG’s kernel module doesn’t load'));
}
if (!st.handler)
return check('awg', title, 'error', NO_PROTO, 'netrestart', 'The network doesn’t know AmneziaWG yet');
return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.');
return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
}
/** Checks of a server's AmneziaWG tunnel. */
@@ -347,13 +330,15 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let st = live.iface_status(srv.ifname);
let up = !!st?.up;
let codes = map(st?.errors ?? [], (e) => e.code);
let running = _('AmneziaWG running') + label, down = _('AmneziaWG is down') + label;
if (!up && index(codes, 'INVALID_PROTO') >= 0)
push(out, check(`up_${id}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart'));
push(out, check(`up_${id}`, running, 'error', no_proto(), 'netrestart', down));
else
push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
push(out, check(`up_${id}`, running, up ? 'ok' : 'error',
up ? sprintf(_('%s is up, listening on UDP %d.'), srv.ifname, srv.port) :
!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.
@@ -375,17 +360,20 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
let same = !missing && !extra;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, same ? 'ok' : 'warn',
same ? `${actual} device${actual == 1 ? ' is' : 's are'} loaded in the tunnel.` :
`${missing} of ${expected} device${expected == 1 ? '' : 's'} missing${extra ? `, ${extra} loaded that should not be` : ''}.`,
same ? null : 'sync'));
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) :
extra ? sprintf(N_(expected, '%d of %d device missing, %d loaded that should not be.', '%d of %d devices missing, %d loaded that should not be.'),
missing, expected, extra)
: sprintf(N_(expected, '%d of %d device missing.', '%d of %d devices missing.'), missing, expected),
same ? null : 'sync', _('Not every device is loaded into AmneziaWG') + label));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error',
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
rule && zone ? null : 'apply'));
push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, rep));
push(out, check(`fw_${id}`, _('AmneziaWG firewall') + label, rule && zone ? 'ok' : 'error',
rule && zone ? sprintf(_('Zone %s and the WAN rule for UDP %d exist.'), srv.ifname, srv.port) : _('Firewall zone or WAN rule is missing.'),
rule && zone ? null : 'apply', _('AmneziaWG firewall rules are missing') + label));
push(out, reply_check(`reply_${id}`, _('AmneziaWG answers reach devices') + label, _('AmneziaWG answers may not reach devices') + label,
'udp', srv.port, rep));
// Port collisions with other tunnels.
let clash = [];
let nc = cursor();
@@ -395,7 +383,8 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
push(clash, s['.name']);
});
if (length(clash))
push(out, check(`port_${id}`, `AmneziaWG port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
push(out, check(`port_${id}`, _('AmneziaWG port is free') + label, 'error', sprintf(_('UDP %d is also used by %s.'), srv.port, join(', ', clash)),
null, _('AmneziaWG port is taken') + label));
let overlaps = [];
let sc = parse_cidr(srv.subnet);
for (let o in other_subnets(id)) {
@@ -403,8 +392,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
if (sc && oc && cidr_overlaps(sc, oc))
push(overlaps, `${o.iface} (${o.cidr})`);
}
push(out, check(`subnet_${id}`, `AmneziaWG subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
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));
return out;
}
@@ -412,50 +402,59 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
function portal_checks(m, need, rep) {
let out = [];
let s = m.settings;
let portal = _('Personal portal'), portal_bad = _('Personal portal isn’t working');
if (length(need.https))
return [ check('portal', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https') ];
return [ check('portal', portal, 'error', sprintf(_("HTTPS isn't available on this router: install %s."), join(', ', need.https)), 'install:https', portal_bad) ];
let owners = tcp_port_owners(s.portal_port);
let listening = tcp_listening(s.portal_port);
if (length(owners))
push(out, check('portal', 'Personal portal', 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
push(out, check('portal', portal, 'error',
sprintf(_('TCP %d is already used by %s. Choose another port in Settings.'), s.portal_port, join(', ', owners)), null, portal_bad));
else
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
push(out, check('portal', portal, listening ? 'ok' : 'error',
listening ? sprintf(_('Listening on TCP %d.'), s.portal_port) : sprintf(_('Nothing listens on TCP %d.'), s.portal_port),
listening ? null : 'restart', portal_bad));
if (!s.portal_host)
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
push(out, check('portal_host', _('Portal address'), 'error', _('Set the public hostname in Settings so links can be generated.'),
null, _('Portal address isn’t set')));
else {
let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m);
let cf = filter(ips, (x) => cloudflare_ip(x));
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
!length(ips) ? `${s.portal_host} does not resolve.` :
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
let h = s.portal_host;
push(out, check('portal_dns', _('Portal address points here'), !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
!length(ips) ? sprintf(_('%s does not resolve.'), h) :
length(cf) ? sprintf(_('%s goes through Cloudflare; in Russia such connections often stall after ~16 KB.'), h) :
wan && index(ips, wan) < 0 ? sprintf(_('%s points at %s, not this router (%s).'), h, join(', ', ips), wan) :
wan ? sprintf(_('%s → %s (this router).'), h, join(', ', ips)) : `${h} → ${join(', ', ips)}.`,
null, _('Portal address doesn’t point here')));
}
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, rep));
push(out, reply_check('portal_reply', _('Portal answers reach visitors'), _('Portal answers may not reach visitors'), 'tcp', s.portal_port, rep));
if (core.portal_http(m)) {
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
push(out, check('portal_http', 'Plain HTTP links', 'warn',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
push(out, check('portal_http', _('Plain HTTP links'), 'warn',
sprintf(_('Links on %s use plain HTTP: the link and the VPN keys in configurations travel unencrypted.'), join(', ', ipl)),
null, _('Portal links use plain HTTP')));
}
if (ip2int(s.portal_host) != null) {
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
push(out, check('cert', _('Portal certificate'), 'skip', _('The main address is an IP: its links use plain HTTP.')));
return out;
}
let cert = pc.portal_cert(s);
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
let sans = cert.self_signed ? [] : pc.cert_names(cert.cert);
let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0;
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
push(out, check('cert', _('Portal certificate'), cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? (length(need.acme) ? _('Using a self-signed certificate: browsers will show a warning. ACME can get a free Let’s Encrypt one.')
: _('Using a self-signed certificate: browsers will show a warning.')) :
!covers ? sprintf(_('%s does not cover %s (it has %s): browsers will warn.'), cert.cert, s.portal_host, join(', ', sans)) :
ok ? sprintf(_('%s covers %s and is valid for more than 14 days.'), cert.cert, s.portal_host) : sprintf(_('%s expires within 14 days.'), cert.cert),
null, _('Portal certificate needs attention')));
return out;
}
/**
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix,
* problem (a failed check in words, else null) }, the texts in the language of the call.
* `fix` names an action accepted by fix(), or one the UI handles itself
* (install:<feature>, updates).
*/
@@ -469,46 +468,50 @@ export function health(m) {
if (length(m.servers))
push(out, awg_check());
let y = localtime().year;
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
push(out, check('clock', _('Clock is set'), y >= 2025 ? 'ok' : 'error',
y >= 2025 ? _('End dates and quotas use the router clock.') : _('The router clock looks wrong; end dates will misbehave. Check NTP.'),
null, _('Clock isn’t set')));
let agent = service_running('dawnline', 'agent');
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart'));
push(out, check('agent', _('Background agent running'), agent ? 'ok' : 'error',
_('Counts traffic and enforces end dates and quotas.'), agent ? null : 'restart', _('Background agent isn’t running')));
// A full overlay fails every config write on the router, Dawnline's and
// OpenWrt's own; backups and history are what Dawnline adds to it.
let free = overlay_free_kb();
if (free != null)
push(out, check('flash', 'Free space on the router', free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
free < 2048 ? `${int(free / 1024 * 10) / 10} MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.`
: `${int(free / 1024)} MB free on the overlay.`,
null, 'The router is running out of flash'));
push(out, check('flash', _('Free space on the router'), free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
free < 2048 ? sprintf(_('%s MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.'), int(free / 1024 * 10) / 10)
: sprintf(_('%d MB free on the overlay.'), int(free / 1024)),
null, _('The router is running out of flash')));
if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
push(out, check('server', _('Server configured'), 'warn', _('Run the setup wizard on the Server tab.'), null, _('No server yet')));
return out;
}
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.'
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.',
nft_ok ? null : 'apply'));
push(out, check('nft', _('Access rules loaded'), nft_ok ? 'ok' : 'error',
nft_ok ? _('Table inet dawnline enforces who may reach LAN and the internet.')
: _('Table inet dawnline is missing: no device is loaded into the tunnels until it is back.'),
nft_ok ? null : 'apply', _('Access rules aren’t loaded')));
if (length(filter(values(m.servers), (s) => s.lan_like && s.enabled))) {
let pr = policy_routing();
push(out, check('policy', 'Internet like a home device not bypassed', length(pr) ? 'warn' : 'ok',
length(pr) ? `Policy routing on the router (${join('; ', pr)}) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters.`
: 'No other policy routing ahead of the tunnel rules.',
null, 'Other policy routing bypasses the home-device path'));
push(out, check('policy', _('Internet like a home device not bypassed'), length(pr) ? 'warn' : 'ok',
length(pr) ? sprintf(_("Policy routing on the router (%s) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters."), join('; ', pr))
: _('No other policy routing ahead of the tunnel rules.'),
null, _('Other policy routing bypasses the home-device path')));
}
// A device the sync has to leave out (a merged import, a hand-edited config).
// Its sentences (core.model_errors), how many more, then what it means.
let data = core.model_errors(m);
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok',
length(data) ? `${join(' ', slice(data, 0, 4))}${length(data) > 4 ? ` (${length(data) - 4} more)` : ''} Such devices are left out of the tunnels: fix or remove them.`
: 'Every device has a key and an address of its own inside its server.'));
push(out, check('data', _('People and devices consistent'), length(data) ? 'error' : 'ok',
length(data) ? join(' ', filter([ join(' ', slice(data, 0, 4)), length(data) > 4 ? sprintf(_('(%d more)'), length(data) - 4) : null,
_('Such devices are left out of the tunnels: fix or remove them.') ], (x) => x))
: _('Every device has a key and an address of its own inside its server.'),
null, _('People and devices are inconsistent')));
let fwc = cursor();
fwc.load('firewall');
@@ -516,21 +519,23 @@ export function health(m) {
for (let id, srv in m.servers) {
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
if (!srv.enabled) {
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
push(out, check(`srv_${id}`, _('Server') + label, 'skip', _('Server is disabled.')));
continue;
}
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep));
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
push(out, endpoint_check(`ep_${id}`, _('Public address') + label, _('Public address needs attention') + label,
srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
if (srv.lan_like) {
let ls = loop.status();
let nh = need.home;
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
ls.active ? `The link is up but not attached to ${ls.dev}.` :
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
push(out, check(`home_${id}`, _('Internet like a home device') + label, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? sprintf(_('Traffic enters %s as %s, so it is handled like any device on your LAN.'), ls.dev, ls.address) :
length(nh) ? sprintf(_('Needs %s. Internet traffic leaves through WAN directly until then.'), join(', ', nh)) :
ls.active ? sprintf(_('The link is up but not attached to %s.'), ls.dev) :
// loop.status()'s own sentence, then what it means.
`${ls.error ?? _('Not set up.')} ${_('Internet traffic leaves through WAN directly.')}`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply', _('Internet like a home device isn’t working') + label));
}
}
@@ -542,10 +547,11 @@ export function health(m) {
// A new config (a server turned on, the home link up) restarts it: give it a few seconds.
let restarting = !running && conf != null && time() - conf.mtime < 10;
let ok = running || restarting;
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
restarting ? 'Restarting with the new settings.' :
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
push(out, check('resolver', _('DNS for Home-only devices'), ok ? 'ok' : 'warn',
restarting ? _('Restarting with the new settings.') :
ok ? (rt.mode == 'ns' ? sprintf(_('Plain resolver running next to the LAN (%s).'), rt.address) : sprintf(_('Plain resolver on port %d.'), rt.port))
: _('The resolver is not running; Home-only devices cannot resolve names.'),
ok ? null : 'apply', _('DNS for Home-only devices isn’t working')));
}
if (m.settings.portal_enabled)
@@ -572,9 +578,9 @@ export function fix(id) {
// Only Dawnline's own tunnels: never another interface of the router.
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
if (!length(mine))
die(`${m[1]} is not one of Dawnline's tunnels.`);
die(sprintf(_("%s is not one of Dawnline's tunnels."), m[1]));
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
die(_('Unknown fix.'));
};
@@ -0,0 +1,71 @@
// Dawnline — the backend's messages in the admin's language: what die()
// reports, the health checks, the updater's phases. Text is English in the
// code, wrapped in _() and N_() (web/i18n/extract.ts collects them into the
// luci-i18n-dawnline-<lang> catalog with the admin UI's strings), with
// placeholders filled by sprintf() after the lookup:
//
// die(sprintf(_('Download failed: %s'), asset));
//
// Translated through LuCI's own catalog reader (luci.core, as LuCI's pages
// are) in the language use() set: the admin page's, sent with every RPC call
// (rpcd/ucode/luci.dawnline) and handed to the updater. With no language,
// no Dawnline translation installed for it, or no luci-base (the unit tests'
// rootfs), the English as written. The portal sets none: its page translates
// the messages it gets with its own catalog.
import { stat } from 'fs';
const DIR = '/usr/lib/lua/luci/i18n';
// A C module, loaded at run time: luci-base may be missing, and a static import would not compile then.
let lmo = null;
try {
lmo = require('luci.core');
}
catch (e) {
lmo = null;
}
let active = null;
/**
* Speak `lang` from now on ("ru"; null or "en" for English). Only a language
* with a Dawnline catalog: LuCI's others alone would translate a few words.
*/
export function use(lang) {
active = null;
if (!lmo || type(lang) != 'string' || lang == 'en' || !match(lang, /^[a-z][a-z][a-z]?([_-][A-Za-z][A-Za-z][A-Za-z]?[A-Za-z]?)?$/))
return;
lang = lc(replace(lang, '_', '-'));
if (!stat(`${DIR}/dawnline.${lang}.lmo`))
return;
if (lmo.load_catalog(lang, DIR) && lmo.change_catalog(lang))
active = lang;
};
/** The language use() set, when its catalog is in use; null for English. */
export function current() {
return active;
};
/** `msg` in the language use() set (the English when the catalog has no translation). */
export function _(msg) {
return (active ? lmo.translate(msg) : null) ?? msg;
};
/** `one` or `many` for n, by the language's plural rules (Russian has three forms). */
export function N_(n, one, many) {
return (active ? lmo.ntranslate(n, one, many) : null) ?? (n == 1 ? one : many);
};
/**
* A service log line's words, as written: the log is kept in English (the
* agent that writes most of it has no language) and read later in any.
* Marking them collects them into the catalog and into the admin page's list
* of log templates, which puts each line into the reader's language when it
* is shown (web/src/admin/events/logwords.ts): sprintf(L_('updated · %s → %s'), a, b).
* Keep a line's English as it was: old lines match it too.
*/
export function L_(s) {
return s;
};
@@ -22,7 +22,8 @@
//
// Everything is derived from the router at run time; nothing assumes a
// particular subnet or tool. If the LAN is not a bridge or setup fails, the
// direct path stays and status() says why.
// direct path stays and status() says why (kept as a code in loop.json, which
// apply and the agent write with no language; error_text() makes the words).
import { readfile, writefile, readlink, stat, unlink } from 'fs';
import { cursor } from 'uci';
@@ -33,6 +34,7 @@ import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
import * as resolver from 'dawnline.resolver';
import { _, L_ } from 'dawnline.i18n';
export const NS = 'dawnline';
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
@@ -40,7 +42,7 @@ const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
export const RESOLVER_CONF = resolver.CONF;
const STATE = `${RUN_DIR}/loop.json`;
const WHO = 'Internet like a home device';
const WHO = L_('Internet like a home device');
function log(msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, WHO);
@@ -180,6 +182,57 @@ function pick_table(saved) {
return null;
}
/* ---------- why it is off ---------- */
/*
* The reasons plan() and ensure() give, kept in loop.json:
* { code: 'no_lan' } no LAN detected
* { code: 'not_bridge', dev } the LAN is not a bridge
* { code: 'no_ipv4', dev } the LAN has no IPv4 address
* { code: 'no_address', net } no free address on the LAN's network
* { code: 'no_transit' } no free link-local range for the internal link
* { code: 'no_table' } no free routing table
* { code: 'setup', detail } a command failed (detail: it and what it said)
*/
/** A reason from plan() for the service log: English, like every log line. */
function error_note(e) {
if (e.code == 'no_lan')
return L_('No LAN detected.');
if (e.code == 'not_bridge')
return sprintf(L_('%s is not a bridge, so Dawnline cannot join the LAN as a device.'), e.dev);
if (e.code == 'no_ipv4')
return sprintf(L_('%s has no IPv4 address.'), e.dev);
if (e.code == 'no_address')
return sprintf(L_('No free address on %s.'), e.net);
if (e.code == 'no_transit')
return L_('No free link-local range for the internal link.');
return L_('No free routing table.');
}
/**
* Why "like a home device" is off (a reason above), as a sentence in the
* reader's language. Null for none; the English of a loop.json written by an
* older version as it is.
*/
export function error_text(e) {
if (type(e) != 'object')
return e ?? null;
if (e.code == 'no_lan')
return _('No LAN detected.');
if (e.code == 'not_bridge')
return sprintf(_('%s is not a bridge, so Dawnline cannot join the LAN as a device.'), e.dev);
if (e.code == 'no_ipv4')
return sprintf(_('%s has no IPv4 address.'), e.dev);
if (e.code == 'no_address')
return sprintf(_('No free address on %s.'), e.net);
if (e.code == 'no_transit')
return _('No free link-local range for the internal link.');
if (e.code == 'no_table')
return _('No free routing table.');
return sprintf(_('Setup failed: %s'), e.detail);
};
/* ---------- plan ---------- */
function settings() {
@@ -199,8 +252,8 @@ function all_ifnames(m) {
}
/**
* What should exist, or { error } when it cannot. Pure apart from reading
* router state (and one ping per candidate address).
* What should exist, or { error } (a reason, see error_text) when it cannot.
* Pure apart from reading router state (and one ping per candidate address).
*/
export function plan(m) {
let srvs = wanted(m);
@@ -210,24 +263,24 @@ export function plan(m) {
let dev = snap.lan;
let d = snap.devices[dev];
if (!dev || !d)
return { error: 'No LAN detected.' };
return { error: { code: 'no_lan' } };
if (d.kind != 'bridge')
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` };
return { error: { code: 'not_bridge', dev } };
let lan = parse_cidr(d.addrs[0]);
if (!lan)
return { error: `${dev} has no IPv4 address.` };
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);
if (!addr)
return { error: `No free address on ${int2ip(lan.net)}/${lan.prefix}.` };
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
let last = read_json(STATE, {});
let tx = pick_transit(last?.transit);
if (tx == null)
return { error: 'No free link-local range for the internal link.' };
return { error: { code: 'no_transit' } };
let table = pick_table(last?.plan?.table);
if (table == null)
return { error: 'No free routing table.' };
return { error: { code: 'no_table' } };
let servers = [];
for (let srv in srvs) {
let sn = net.server_net(srv, snap);
@@ -362,8 +415,8 @@ export function ensure(m, force) {
remove(ifnames);
ensure_dir(RUN_DIR);
write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
if (p.error && p.error != was.error)
log('is off', 'error', p.error);
if (p.error && sprintf('%J', p.error) != sprintf('%J', was.error))
log(L_('is off'), 'error', error_note(p.error));
return p;
}
let last = read_json(STATE, {});
@@ -411,18 +464,19 @@ export function ensure(m, force) {
push(errs, ...run(sync_rules(p, ifnames)));
if (length(errs)) {
if (read_json(STATE, {}).error != `Setup failed: ${errs[0]}`)
log('failed — internet goes out directly for now', 'error', errs[0]);
let why = { code: 'setup', detail: errs[0] };
if (sprintf('%J', read_json(STATE, {}).error) != sprintf('%J', why))
log(L_('failed - internet goes out directly for now'), 'error', errs[0]);
remove(ifnames);
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
return { error: errs[0] };
write_json(STATE, { error: why }, 0o644);
return { error: why };
}
ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
log(`is on · traffic enters ${p.dev} as ${p.address}`, 'up');
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
else if (!healthy)
log(`was broken — set up again (${p.dev} as ${p.address})`, 'repair');
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
return p;
};
@@ -440,7 +494,7 @@ export function remember(p) {
});
};
/** Last applied state for views and health checks. */
/** Last applied state for views and health checks; `error` says why it is off (error_text). */
export function status() {
let s = read_json(STATE, {});
if (s.plan)
@@ -449,7 +503,7 @@ export function status() {
dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns,
bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev,
};
return { active: false, off: !!s.off, error: s.error };
return { active: false, off: !!s.off, error: error_text(s.error) };
};
/** The DNS address tunnel clients should use while the loop is up. */
@@ -8,6 +8,7 @@ import { stat, unlink } from 'fs';
import { q, slog } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
import { L_ } from 'dawnline.i18n';
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
@@ -32,7 +33,7 @@ function word_codes() {
}
});
});
slog('dawnline', 'info', 'moved to word codes', null, 'Personal links');
slog('dawnline', 'info', L_('moved to word codes'), null, L_('Personal links'));
}
/*
@@ -101,7 +102,7 @@ function auto_mtu() {
mark_migrated(w, 'auto_mtu');
});
if (any)
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers');
slog('dawnline', 'info', L_('MTU is now automatic'), null, L_('Servers'));
}
/** All of them, in order. */
@@ -2,13 +2,15 @@
// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created
// are changed or removed: a name already used by another interface (`lan`, a
// tunnel of your own, one from an imported config) is left alone and the
// server is reported instead.
// 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).
import { cursor } from 'uci';
import { stat, unlink, writefile } from 'fs';
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import { L_ } from 'dawnline.i18n';
// Set while AmneziaWG is missing and that was logged (once until it is back).
const NO_AWG = `${RUN_DIR}/netifd-no-awg`;
@@ -35,12 +37,12 @@ export function sync(m) {
let changed = false, touched = [], want = {};
// Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts.
let was = read_json(core.BLOCKED, {}), blocked = {};
let block = (srv, msg, detail) => {
blocked[srv.id] = msg;
let block = (srv, why, detail) => {
blocked[srv.id] = why;
// The rest of this apply works from the same model: no tunnel for it there either.
srv.blocked = msg;
if (was[srv.id] != msg)
log(srv.name, msg, 'error', detail);
srv.blocked = why;
if (sprintf('%J', was[srv.id]) != sprintf('%J', why))
log(srv.name, awg.blocked_note(why), 'error', detail);
};
// Without amneziawg-tools there is no protocol script: changing or bringing
@@ -49,7 +51,7 @@ export function sync(m) {
if (tools && stat(NO_AWG))
unlink(NO_AWG);
else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) {
log('AmneziaWG', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.');
log('AmneziaWG', L_("isn't installed: tunnels were left as they are"), 'error', L_('Install it in Dawnline → Components.'));
ensure_dir(RUN_DIR);
writefile(NO_AWG, `${time()}`);
}
@@ -59,12 +61,12 @@ export function sync(m) {
continue;
let ifn = srv.ifname;
if (!core.valid_ifname(ifn)) {
block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.');
block(srv, { code: 'ifname', ifname: ifn }, 'Interface name: 1-12 lowercase letters, digits or _.');
continue;
}
let own = owner(ifn, c);
if (own != null && own != id) {
block(srv, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`,
block(srv, { code: 'taken', ifname: ifn },
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue;
}
@@ -74,7 +76,7 @@ export function sync(m) {
// disguise is changed.
let why = tools ? awg.obf_unsupported(srv.obf) : null;
if (why) {
block(srv, `is kept down: ${why}`, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
continue;
}
delete srv.blocked;
@@ -4,6 +4,7 @@
import { access, popen, stat } from 'fs';
import { q } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
function run(cmd) {
let p = popen(cmd + ' 2>&1', 'r');
@@ -99,8 +100,9 @@ function preflight(files, need_kb, log) {
for (let f in files ?? [])
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
if (free < need)
die(`Not enough free space on the router: ${int(free / 1024)} MB free, about ${int(need / 1024) + 1} MB needed. Remove old backups or packages first`);
log?.(` ${int(free / 1024)} MB free on the overlay`);
die(sprintf(_('Not enough free space on the router: %d MB free, about %d MB needed. Remove old backups or packages first'),
int(free / 1024), int(need / 1024) + 1));
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. */
@@ -115,8 +117,8 @@ export function install_files(files, force, log) {
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");
log?.(' ' + _('apk did not reinstall the version that is already installed'));
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
}
return ok;
};
@@ -24,6 +24,10 @@
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
// shows the page, but gets them from its HTTPS twin.
//
// Messages go out in the page's language (Accept-Language: the portal's
// fetch sends the visitor's choice) when a Dawnline translation for it is
// installed; else in English, and the page translates the ones it knows.
//
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
// that answers anything not shaped like a link (its not_found() twin).
@@ -36,6 +40,8 @@ import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as schema from 'dawnline.schema';
import * as devices from 'dawnline.devices';
import * as i18n from 'dawnline.i18n';
import { _ } from 'dawnline.i18n';
const RATE = `${RUN_DIR}/portal-rate.json`;
const ASSETS = '/usr/share/dawnline/portal/assets';
@@ -60,13 +66,22 @@ const SECURITY_HEADERS = {
'Cache-Control': 'no-store',
};
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
// States the admin stopped the person in: the portal only shows, it changes nothing.
const LOCKED = {
paused: 'Your access is paused.',
expired: 'Your access has ended.',
};
const LOCKED = [ 'paused', 'expired' ];
/** Why a stopped person (a LOCKED state) can't change anything, in the visitor's language; null for other states. */
function locked_reason(st) {
if (st == 'paused')
return _('Your access is paused.');
if (st == 'expired')
return _('Your access has ended.');
return null;
}
/** Why a new device or a new set-up is refused while the router has no AmneziaWG. */
function not_ready() {
return _("Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.");
}
function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
@@ -124,7 +139,7 @@ function body(r) {
if (len <= 0)
return {};
if (len > BODY_MAX)
fail(r, '413 Payload Too Large', 'Request too large.');
fail(r, '413 Payload Too Large', _('Request too large.'));
let raw = '';
while (length(raw) < len) {
let chunk = r.io.read(len - length(raw));
@@ -137,7 +152,7 @@ function body(r) {
return type(j) == 'object' ? j : {};
}
catch (e) {
fail(r, '400 Bad Request', 'Invalid JSON.');
fail(r, '400 Bad Request', _('Invalid JSON.'));
}
}
@@ -236,7 +251,7 @@ function rate_action(r) {
write_json(RATE, st, 0o600);
unlock(l);
if (v.count > ACTION_LIMIT)
fail(r, '429 Too Many Requests', 'Too many changes in a short time. Try again in a few minutes.');
fail(r, '429 Too Many Requests', _('Too many changes in a short time. Try again in a few minutes.'));
}
/* ---------- pages ---------- */
@@ -305,7 +320,7 @@ function person_state(m, p, usage) {
let st = core.person_state(m, p, usage);
if (st == 'server_off') {
let own = core.own_state(m, p, usage);
if (LOCKED[own])
if (index(LOCKED, own) >= 0)
return own;
}
return st;
@@ -313,7 +328,7 @@ function person_state(m, p, usage) {
/** Why the person can't change anything right now, or null. */
function locked(r) {
return LOCKED[person_state(r.m, r.person, core.load_usage())] ?? null;
return locked_reason(person_state(r.m, r.person, core.load_usage()));
}
/** Refuses a change (or a config) while the person is stopped. */
@@ -340,7 +355,7 @@ function https_url(r) {
function need_https(r) {
let u = https_url(r);
if (u)
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u });
send_json(r, '403 Forbidden', { error: _('Open this link over HTTPS to get the connection settings.'), https_url: u });
}
/** The router's offset from UTC in minutes: the admin sets hours in its time, the page shows the visitor's. */
@@ -371,7 +386,7 @@ function state(r) {
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
},
can_add: length(person.devices) < person.device_limit,
locked: LOCKED[v.state] != null,
locked: index(LOCKED, v.state) >= 0,
// Over plain HTTP: where the configurations are (keys only travel encrypted).
https_url: https_url(r),
kinds: core.KINDS,
@@ -389,7 +404,7 @@ function state(r) {
function own_device(r, id) {
let d = r.m.devices[id];
if (!d || d.person != r.person.id)
fail(r, '404 Not Found', 'Device not found.');
fail(r, '404 Not Found', _('Device not found.'));
return d;
}
@@ -402,7 +417,7 @@ function api_add(r) {
need_https(r);
let b = body(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
fail(r, '503 Service Unavailable', not_ready());
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
reload(r);
@@ -427,7 +442,7 @@ const ACTIONS = {
reconnect: (r, d, b) => {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
fail(r, '503 Service Unavailable', not_ready());
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config };
},
@@ -443,7 +458,7 @@ function api_device(r, id) {
let b = body(r);
let act = ACTIONS[b.action];
if (!act)
fail(r, '400 Bad Request', 'Unknown action.');
fail(r, '400 Bad Request', _('Unknown action.'));
rate_action(r);
let res = act(r, d, b);
reload(r);
@@ -542,21 +557,23 @@ export function handle(io) {
let origin = header('origin');
if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) ||
(origin != null && origin != `${https ? 'https' : 'http'}://${host}`))
fail(r, '403 Forbidden', 'Cross-site request refused.');
fail(r, '403 Forbidden', _('Cross-site request refused.'));
}
else if (r.method != 'GET')
fail(r, '405 Method Not Allowed', 'Method not allowed.');
fail(r, '405 Method Not Allowed', _('Method not allowed.'));
let rt = route(API, r.method, slice(rest, 1));
if (!rt)
fail(r, '404 Not Found', 'Not found.');
fail(r, '404 Not Found', _('Not found.'));
rt.run(r, rt.args[0]);
fail(r, '404 Not Found', 'Not found.');
fail(r, '404 Not Found', _('Not found.'));
};
/** Run handle() and swallow its early end. */
export function serve(io) {
try {
// "ru-RU,ru;q=0.9" → ru (i18n.use takes plain language codes only).
i18n.use((match(io.env.HTTP_ACCEPT_LANGUAGE ?? '', /^[ \t]*([A-Za-z][A-Za-z][A-Za-z]?)/) ?? [])[1]);
handle(io);
}
catch (e) {
@@ -6,6 +6,7 @@ import * as awg from 'dawnline.awg';
import * as health from 'dawnline.health';
import * as schema from 'dawnline.schema';
import { uniq } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
/**
* An rpcd handler from fn(args): an object result is passed on, anything else
@@ -45,16 +46,16 @@ export function default_method() {
/** A disguise method the installed AmneziaWG can run. */
export function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
die(_('Unknown disguise method.'));
let c = awg.caps();
if (name == 'max' && !c.v3)
die(awg.installed()
? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.');
? _('Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.')
: _('AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.'));
if (name == 'balanced' && !c.v2)
die(awg.installed()
? 'Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.');
? _('Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.')
: _('AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.'));
return name;
};
@@ -75,6 +76,7 @@ function tcp_forwards(m) {
/**
* TCP ports the portal can't take, and who holds them: [{ from, to, who }].
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
* `who` is shown in the admin's language ("Used by %s.").
*/
export function tcp_taken(m) {
let out = [];
@@ -86,11 +88,11 @@ export function tcp_taken(m) {
}
};
for (let p in schema.RESERVED_PORTS)
hold(p, 'the router itself');
hold(p, _('the router itself'));
for (let p, name in health.tcp_port_programs())
hold(+p, `${name} on this router`);
hold(+p, sprintf(_('%s on this router'), name));
for (let f in tcp_forwards(m))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out;
};
@@ -100,12 +102,12 @@ export function check_portal(m, was) {
return;
let port = s.portal_port;
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).');
die(_('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'));
let ports = [ port ];
if (core.portal_http(m)) {
let hp = core.portal_http_port(m);
if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0)
die(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`);
die(sprintf(_('Links on IP addresses use plain HTTP on the next port (%d), which the portal cannot take. Choose another portal port.'), hp));
push(ports, hp);
}
// Only ports the portal does not hold already: our own uhttpd is not an owner anyway.
@@ -120,11 +122,13 @@ export function check_portal(m, was) {
continue;
let owners = health.tcp_port_owners(p);
if (length(owners))
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`);
die(sprintf(p != port
? _("TCP %d is already used by %s. Links on IP addresses use plain HTTP on the port after the portal's. Choose another portal port.")
: _('TCP %d is already used by %s. Choose another portal port.'), p, join(', ', owners)));
}
// A forwarded port never reaches the router: the portal would be unreachable.
for (let p in ports)
for (let f in tcp_forwards(m))
if (f.from <= p && p <= f.to)
die(`TCP ${p} is sent on by port forward “${f.name}”. Choose another portal port.`);
die(sprintf(_('TCP %d is sent on by port forward “%s”. Choose another portal port.'), p, f.name));
};
@@ -4,7 +4,7 @@
import { readfile } from 'fs';
import { cursor } from 'uci';
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength, NAME_RULE } from 'dawnline.util';
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
@@ -12,6 +12,7 @@ import * as access from 'dawnline.access';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import { wrap, str } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
/* ---------- services ---------- */
@@ -22,29 +23,29 @@ function new_id(m, make) {
if (!store.id_taken(m, id))
return id;
}
die('Could not find a free id, try again.');
die(_('Could not find a free id, try again.'));
}
function service_set(a) {
let name = str(a.name);
if (!valid_name(name))
die(`Service: ${NAME_RULE}`);
die(_('Service: Enter a name: up to 48 characters, without < > " or \\.'));
let address = str(a.address);
if (!schema.ipv4(address))
die('Address must be an IPv4 address.');
die(_('Address must be an IPv4 address.'));
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != '');
for (let pt in ports)
if (!schema.valid_port(pt))
die(`Invalid port ${pt}.`);
die(sprintf(_('Invalid port %s.'), pt));
let id = store.transact((c, m) => {
let id = str(a.id);
if (id == '')
id = new_id(m, () => `svc_${rand_int(100000, 999999)}`);
else if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
die('Invalid service id.');
die(_('Invalid service id.'));
// Never turn a person, device, server, circle or the settings into a service.
else if (!m.services[id] && store.id_taken(m, id))
die('That id is taken.');
die(_('That id is taken.'));
c.set(core.CONFIG, id, 'service');
c.set(core.CONFIG, id, 'name', name);
c.set(core.CONFIG, id, 'address', address);
@@ -61,7 +62,7 @@ function service_set(a) {
function service_delete(a) {
store.transact((c, m) => {
if (!m.services[a.id])
die('Unknown service.');
die(_('Unknown service.'));
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (index(p.services, a.id) >= 0) {
@@ -82,17 +83,17 @@ function service_delete(a) {
function circle_set(a) {
let name = str(a.name);
if (!valid_name(name) || ulength(name) > 32)
die('Enter a circle name: up to 32 characters, without < > " or \\.');
die(_('Enter a circle name: up to 32 characters, without < > " or \\.'));
let res = store.transact((c, m) => {
let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci)
die('Unknown circle.');
die(_('Unknown circle.'));
let server = ci?.server ?? a.server;
if (!m.servers[server])
die('Unknown server.');
die(_('Unknown server.'));
for (let id, o in m.circles)
if (id != a.id && o.server == server && lc(o.name) == lc(name))
die(`${name} already exists.`);
die(sprintf(_('%s already exists.'), name));
let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`);
let n = core.CIRCLE_COLORS;
c.set(core.CONFIG, id, 'circle');
@@ -121,7 +122,7 @@ function circle_delete(a) {
let res = store.transact((c, m) => {
let ci = m.circles[a.id];
if (!ci)
die('Unknown circle.');
die(_('Unknown circle.'));
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (p.circle == a.id)
@@ -173,7 +174,7 @@ function home_hosts(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
die(_('No server yet.'));
let nets = [];
for (let cidr in net.server_net(srv).nets) {
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
@@ -1,6 +1,7 @@
// Dawnline rpcd methods: Diagnostics (Health, the service log), backups,
// export / import, and removing Dawnline.
import { _ } from 'dawnline.i18n';
import { slog_clear, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
@@ -49,10 +50,10 @@ function import_all(a) {
/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */
function uninstall(a) {
if (a.confirm != 'remove')
die('Type "remove" to confirm.');
die(_('Type "remove" to confirm.'));
// Not in the middle of an update (opkg/apk may be installing Dawnline itself).
if (upd.busy())
die('An update is running: wait for it to finish, then remove Dawnline.');
die(_('An update is running: wait for it to finish, then remove Dawnline.'));
backup.backup_create('pre-remove');
// Stop first: the agent would put back what teardown removes, and could start an automatic update.
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
@@ -9,6 +9,7 @@ import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
@@ -61,7 +62,7 @@ function person_update(a) {
function person_pause(a) {
store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
die(_('Unknown person.'));
if (a.paused)
c.set(core.CONFIG, a.id, 'paused', '1');
else
@@ -79,7 +80,7 @@ function person_pause(a) {
function person_regen(a) {
let gone = store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
die(_('Unknown person.'));
c.set(core.CONFIG, a.id, 'code', core.new_code());
c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
let gone = [];
@@ -106,7 +107,7 @@ function person_links(a) {
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
die(_('Unknown person.'));
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
}
@@ -125,7 +126,7 @@ function person_usage(a) {
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
die(_('Unknown person.'));
let days = clamp_days(a.days);
let devs = {};
for (let d in p.devices)
@@ -144,7 +145,7 @@ function device_config(a) {
let m = core.load();
let d = m.devices[a.id];
if (!d)
die('Unknown device.');
die(_('Unknown device.'));
awg.mark_issued(m, d.id);
return awg.client_config(m, d);
}
@@ -2,7 +2,7 @@
// Interfaces settings, its disguise, and removing it.
import { cursor } from 'uci';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, NAME_RULE, rand_int, uniq, admin_log } from 'dawnline.util';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, rand_int, uniq, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
@@ -15,6 +15,7 @@ import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices';
import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
/** Server ids that would shadow a portal path. */
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
@@ -27,6 +28,7 @@ const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other',
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
* Other servers, tunnel interfaces, programs on the router and port forwards
* from its WAN zone. `srv` is the server being edited: its own port isn't counted.
* `who` is shown in the admin's language ("Used by %s.").
*/
function udp_taken(m, srv, wan_zone) {
let out = [];
@@ -39,26 +41,26 @@ function udp_taken(m, srv, wan_zone) {
};
for (let id, o in m.servers)
if (id != srv?.id)
hold(o.port, `server “${o.name}”`);
hold(o.port, sprintf(_('server “%s”'), o.name));
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s.listen_port && s['.name'] != srv?.ifname)
hold(+s.listen_port, `interface ${s['.name']}`);
hold(+s.listen_port, sprintf(_('interface %s'), s['.name']));
});
let progs = health.udp_port_programs();
for (let p in health.udp_bound())
if (p != srv?.port)
hold(p, progs[`${p}`] ? `${progs[`${p}`]} on this router` : 'another program on this router');
hold(p, progs[`${p}`] ? sprintf(_('%s on this router'), progs[`${p}`]) : _('another program on this router'));
for (let f in core.wan_forwards(wan_zone, 'udp'))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out;
}
function check_udp_port(port, taken) {
for (let t in taken)
if (t.from <= port && port <= t.to)
die(`UDP ${port} is used by ${t.who}. Choose another port.`);
die(sprintf(_('UDP %d is used by %s. Choose another port.'), port, t.who));
}
/** The usual AmneziaWG port when free, otherwise a random high one. */
@@ -197,7 +199,8 @@ function setup_defaults(a) {
let port = free_port(udp);
return {
id: free_server_id(m),
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
// A name to start from, in the admin's language (it is theirs once saved).
name: length(m.servers) ? sprintf(_('Server %d'), length(m.servers) + 1) : _('Home'),
ifname: free_ifname(m),
port,
subnet: free_subnet(map(networks, (n) => n.cidr)),
@@ -229,7 +232,7 @@ function setup_defaults(a) {
function endpoint_probe(a) {
let host = str(a.host);
if (host != '' && !valid_host(host))
die('Public address must be a hostname or IP address.');
die(_('Public address must be a hostname or IP address.'));
let m = core.load();
let srv = m.servers[str(a.id)] ?? null;
let f = health.endpoint_facts(srv, host);
@@ -241,14 +244,14 @@ function endpoint_probe(a) {
function need_awg_loaded() {
devices.need_awg();
if (!awg.load().loaded)
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components.");
die(_("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components."));
}
/** An MTU as typed: '' (automatic) or 1280-1500. */
function check_mtu(v) {
let s = str(v);
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
die('MTU must be 1280-1500.');
die(_('MTU must be 1280-1500.'));
return s;
}
@@ -260,19 +263,19 @@ function server_create(a) {
let id = str(a.id) || 'home';
// A UCI section name: a dash would make uci drop it silently.
if (!match(id, /^[a-z][a-z0-9_]{0,23}$/))
die('Server ID may use lowercase letters, digits and underscores.');
die(_('Server ID may use lowercase letters, digits and underscores.'));
if (!id_free(m, id))
die(`"${id}" is already taken.`);
die(sprintf(_('"%s" is already taken.'), id));
let nc = cursor();
nc.load('network');
let ifname = str(a.ifname) || free_ifname(m);
if (!ifname_free(m, nc, ifname))
die(`Network interface ${ifname} already exists.`);
die(sprintf(_('Network interface %s already exists.'), ifname));
let udp = udp_taken(m, null, str(a.wan_zone) || 'wan');
let port = free_port(udp);
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
if (!schema.valid_port(a.port))
die('UDP port must be 1-65535.');
die(_('UDP port must be 1-65535.'));
port = +str(a.port);
}
check_udp_port(port, udp);
@@ -285,7 +288,7 @@ function server_create(a) {
// Public addresses inside the tunnel would hide the real hosts behind them.
// New servers only: a restored backup keeps what it had.
if (pc && !core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
let taken = [ ...router_subnets ];
for (let sid, o in m.servers)
push(taken, o.subnet);
@@ -298,7 +301,7 @@ function server_create(a) {
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server');
if (!valid_name(str(a.name) || 'Home'))
die(`Server: ${NAME_RULE}`);
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(a.name) || 'Home');
set('ifname', ifname);
set('port', `${port}`);
@@ -329,7 +332,7 @@ function server_create(a) {
c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0');
if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') {
if (!schema.valid_port(a.portal_port))
die('Portal port must be 1-65535.');
die(_('Portal port must be 1-65535.'));
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
}
}
@@ -394,7 +397,7 @@ function interfaces_get(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
die(_('No server yet.'));
return interfaces_view(m, srv, net.snapshot(true));
}
@@ -406,12 +409,12 @@ function server_interfaces(a) {
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
die(_('Unknown server.'));
if (!auto_wan) {
if (!snap.devices[wan_dev])
die('Choose the interface that leads to the internet.');
die(_('Choose the interface that leads to the internet.'));
if (!snap.devices[wan_dev].zone)
die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`);
die(sprintf(_('%s is not in a firewall zone, so the server port cannot be opened on it.'), wan_dev));
}
let lans = [];
for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) {
@@ -420,9 +423,9 @@ function server_interfaces(a) {
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
continue;
if (snap.devices[d]?.master)
die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`);
die(sprintf(_('%s is part of %s; choose %s instead.'), d, snap.devices[d].master, snap.devices[d].master));
if (d == (auto_wan ? snap.wan : wan_dev))
die(`${d} is the WAN.`);
die(sprintf(_('%s is the WAN.'), d));
push(lans, d);
}
lans = uniq(lans);
@@ -485,7 +488,7 @@ function dns_list(v) {
let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != '');
for (let d in list)
if (!schema.ip(d))
die(`${d} is not an IP address.`);
die(sprintf(_('%s is not an IP address.'), d));
return list;
}
@@ -497,22 +500,22 @@ function server_update(a) {
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
die(_('Unknown server.'));
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
if (v.name != null) {
if (!valid_name(str(v.name)))
die(`Server: ${NAME_RULE}`);
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(v.name));
}
// Empty = the portal's address (core.endpoint_host), as at creation.
if (v.endpoint != null) {
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
die('Public address must be a hostname or IP address.');
die(_('Public address must be a hostname or IP address.'));
set('endpoint', str(v.endpoint));
}
if (v.port != null) {
if (!schema.valid_port(v.port))
die('UDP port must be 1-65535.');
die(_('UDP port must be 1-65535.'));
let n = +str(v.port);
if (n != srv.port)
check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
@@ -522,7 +525,7 @@ function server_update(a) {
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
if (v.mesh != null) {
if (index(core.MESH, v.mesh) < 0)
die('Unknown choice for devices reaching each other.');
die(_('Unknown choice for devices reaching each other.'));
set('mesh', v.mesh);
set('device_mesh', null);
}
@@ -530,7 +533,7 @@ function server_update(a) {
set('mtu', check_mtu(v.mtu));
if (v.keepalive != null) {
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600))
die('Keep-alive must be 0-600 seconds.');
die(_('Keep-alive must be 0-600 seconds.'));
set('keepalive', str(v.keepalive));
}
if (v.dns != null) {
@@ -544,13 +547,13 @@ function server_update(a) {
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
let pc = parse_cidr(str(v.subnet));
if (!pc)
die('Subnet must look like 10.77.0.0/24.');
die(_('Subnet must look like 10.77.0.0/24.'));
if (!core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
for (let t in taken)
if (cidr_overlaps(pc, parse_cidr(t)))
die(`Subnet overlaps ${t}.`);
die(sprintf(_('Subnet overlaps %s.'), t));
core.renumber_server(c, m, srv, cidr_str(pc));
}
return srv;
@@ -583,7 +586,7 @@ function server_ports(a) {
let m = core.load();
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
die(_('Unknown server.'));
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
@@ -595,7 +598,7 @@ function server_obfuscation(a) {
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
die(_('Unknown server.'));
for (let k in core.OBF_KEYS)
c.delete(core.CONFIG, srv.id, k);
for (let k, v in o)
@@ -611,12 +614,12 @@ function server_obfuscation(a) {
/** Remove a server with its people, their devices and its circles (a backup is made first). */
function server_delete(a) {
if (!core.load().servers[a.id])
die('Unknown server.');
die(_('Unknown server.'));
backup.backup_create('pre-delete');
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
die(_('Unknown server.'));
let gone = 0;
for (let pid, p in m.people)
if (p.server == srv.id) {
@@ -12,6 +12,7 @@ import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as pc from 'dawnline.portalcert';
import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
/** The portal's own checks from Health, shown next to its settings. */
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
@@ -92,7 +93,7 @@ function same(a, b) {
function settings_update(a) {
let v = a.values ?? {};
if (type(v) != 'object')
die('Nothing to save.');
die(_('Nothing to save.'));
let res = store.transact((c, m) => {
let restart = false;
c.set(core.CONFIG, 'settings', 'settings');
@@ -2,6 +2,7 @@
// people, totals, map, recent activity), the activity log and traffic history.
import { readfile } from 'fs';
import { _ } from 'dawnline.i18n';
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -122,7 +123,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
blocked: srv.blocked ?? null,
// Why it can't start, as a whole sentence in the admin's language (stored as a code).
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,
@@ -221,19 +223,19 @@ function logs_clear(a) {
let f = {};
if (a.person) {
if (!m.people[a.person])
die('Unknown person.');
die(_('Unknown person.'));
f.person = a.person;
}
if (a.device)
f.device = a.device;
if (a.category) {
if (index(live.CATEGORIES, a.category) < 0)
die('Unknown category.');
die(_('Unknown category.'));
f.category = a.category;
}
if (a.older_days) {
if (!match(a.older_days, /^[1-9][0-9]{0,3}$/))
die('Older than must be a number of days.');
die(_('Older than must be a number of days.'));
f.before = time() - +a.older_days * 86400;
}
let removed = live.clear_events(f);
@@ -252,11 +254,11 @@ function logs_clear(a) {
function usage_clear(a) {
let m = core.load();
if (index([ 'all', 'person', 'device' ], a.scope) < 0)
die('Unknown scope.');
die(_('Unknown scope.'));
if (a.scope == 'person' && !m.people[a.id])
die('Unknown person.');
die(_('Unknown person.'));
if (a.scope == 'device' && !m.devices[a.id])
die('Unknown device.');
die(_('Unknown device.'));
let req = { scope: a.scope, id: a.id, ts: time() };
ensure_dir(RUN_DIR);
let l = lock('usage-reset');
@@ -11,11 +11,14 @@ import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as builds from 'dawnline.awg_builds';
import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs';
import { langs } from 'dawnline.upd_app';
import * as i18n from 'dawnline.i18n';
import { _ } from 'dawnline.i18n';
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback]
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback|:lang:<code>|:nolang]
// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages)
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback|:lang:[a-z]{2,3}(_[A-Za-z]{2,4})?|:nolang)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
function wrap(fn) {
return function(req) {
@@ -62,6 +65,8 @@ function status(a) {
policy: m.settings.updates,
auto: upd.auto_state(),
kept: upd.kept_all(builds.firmware()?.postfix),
// The admin's translations installed (luci-i18n-dawnline-<lang>).
translations: langs(),
history: slice(upd.history(), 0, 12),
tunnels: awg_tunnels(),
};
@@ -71,7 +76,7 @@ function status(a) {
function releases(a) {
let page = +(a.page ?? 1);
if (page != int(page) || page < 1 || page > 50)
die('Unknown page.');
die(_('Unknown page.'));
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
}
@@ -80,12 +85,12 @@ function notes(a) {
let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO;
let tag = a.tag ?? '';
if (!rp || !match(tag, TAG))
die('Unknown release.');
die(_('Unknown release.'));
let r = gh.release(rp, tag);
if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v')
r = gh.release(rp, `v${tag}`);
if (!r)
die(`No release ${tag} in ${rp}.`);
die(sprintf(_('No release %s in %s.'), tag, rp));
return { ...r, digests: null, repo: rp };
}
@@ -93,7 +98,7 @@ function notes(a) {
function changes(a) {
let to = a.to ?? '', from = a.from ?? '';
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
die('Unknown release.');
die(_('Unknown release.'));
// The installed version as a tag when it was released (a build ahead of the releases has none).
let base = null;
for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : []))
@@ -109,18 +114,20 @@ function changes(a) {
function run(a) {
let what = a.what ?? 'check';
if (length(what) > 400 || !match(what, TARGET))
die('Unknown update target.');
die(_('Unknown update target.'));
// Checked here too, so a wrong name never becomes a failed job in the history.
if (substr(what, 0, 5) == 'pkgs:')
for (let n in split(substr(what, 5), ','))
if (index(PKG_NAMES, n) < 0)
die(n == '' ? 'Unknown update target.' : `${n} is not a package Dawnline manages.`);
die(n == '' ? _('Unknown update target.') : sprintf(_('%s is not a package Dawnline manages'), n));
if (upd.busy())
die('Another component action is already running.');
die(_('Another component action is already running'));
ensure_dir(RUN_DIR);
let t0 = time();
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
// The job speaks the admin's language (use() let only a plain language code through).
let lang = i18n.current();
system(`${lang ? `DAWNLINE_LANG=${lang} ` : ''}start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
for (let i = 0; i < 20; i++) {
let j = read_json(upd.JOB_FILE, null);
if (j?.state == 'running' && j.started >= t0)
@@ -8,6 +8,7 @@
import { stat } from 'fs';
import { ip2int, valid_host, ulength } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates';
import { _ } from 'dawnline.i18n';
/* ---------- addresses ---------- */
@@ -109,37 +110,36 @@ export function to_int(v, dflt, lo, hi) {
/*
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | targets
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
* min/max: ints; values: enums; msg: the error for a bad value.
* min/max: ints; values: enums. The error for a bad value is in messages().
*/
export const SETTINGS = {
portal_enabled: { type: 'bool', dflt: false, restart: true },
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
portal_alt: { type: 'hosts', dflt: [], restart: true, msg: 'Other addresses must be hostnames or IP addresses.' },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
portal_host: { type: 'host', dflt: '', restart: true },
portal_alt: { type: 'hosts', dflt: [], restart: true },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true },
portal_redirect: { type: 'url', dflt: '' },
portal_cert: { type: 'file', dflt: '', restart: true },
portal_key: { type: 'file', dflt: '', restart: true },
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' },
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32 },
hostnames: { type: 'bool', dflt: true },
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
domain: { type: 'domain', dflt: 'lan' },
// Off until the admin turns it on: lookups send people's addresses to a third party.
geo_enabled: { type: 'bool', dflt: false },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ] },
log_connections: { type: 'bool', dflt: true },
watchdog: { type: 'bool', dflt: true },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, msg: 'Keep activity for 0 (no age limit) to 9999 days.' },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' },
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' },
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' },
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999 },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000 },
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ] },
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830 },
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120 },
// Empty means "no fallback" (stored as 'none'); unset means the default.
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' },
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1' },
update_check: { type: 'bool', dflt: true },
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS), msg: 'Check every 6h, 12h, 1d or 7d.' },
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS) },
update_auto: { type: 'bool', dflt: true },
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' },
update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' },
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ] },
update_time: { type: 'time', dflt: '04:00' },
update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] },
update_keep: { type: 'bool', dflt: false },
update_mirrors: { type: 'bool', dflt: true },
@@ -148,8 +148,30 @@ export const SETTINGS = {
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */
export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
function bad(spec, key) {
die(spec.msg ?? `Invalid value for ${key}.`);
/** What the admin is told about a bad value, by setting (made per call: the language changes between calls). */
function messages() {
return {
portal_host: _('Public address must be a hostname or IP address.'),
portal_alt: _('Other addresses must be hostnames or IP addresses.'),
portal_port: _('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'),
portal_redirect: _('Redirect must be a full http:// or https:// address.'),
default_device_limit: _('Default device limit must be 1-32.'),
domain: _('Domain may use lowercase letters, digits, dashes and dots.'),
geo_provider: _('Unknown location service.'),
log_keep_days: _('Keep activity for 0 (no age limit) to 9999 days.'),
log_max: _('Log size must be 100-20000 events.'),
log_persist: _('Save the log every 10min, hourly or off.'),
usage_keep_days: _('Daily traffic history must be 7-1830 days.'),
usage_keep_months: _('Monthly traffic history must be 1-120 months.'),
home_dns_fallback: _('Fallback DNS must be an IPv4 address (or empty for none).'),
update_interval: _('Check every 6h, 12h, 1d or 7d.'),
update_mode: _('Install updates immediately or scheduled.'),
update_time: _('Enter a time as HH:MM, 00:00 to 23:59.'),
};
}
function bad(key) {
die(messages()[key] ?? sprintf(_('Invalid value for %s.'), key));
}
/**
@@ -160,14 +182,14 @@ function bad(spec, key) {
export function validate(key, val) {
let spec = SETTINGS[key];
if (!spec)
die(`Unknown setting ${key}.`);
die(sprintf(_('Unknown setting %s.'), key));
let t = spec.type;
if (t == 'hosts') {
let lst = [];
for (let x in (type(val) == 'array' ? val : [])) {
// A typo must not vanish on Save: refused, like the main address.
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
bad(spec, key);
bad(key);
if (trim(x) != '' && index(lst, trim(x)) < 0)
push(lst, trim(x));
}
@@ -190,40 +212,40 @@ export function validate(key, val) {
return null;
if (t == 'bool') {
if (val != '0' && val != '1')
die(`${key} is 0 or 1.`);
die(sprintf(_('%s is 0 or 1.'), key));
}
else if (t == 'int') {
if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max)
bad(spec, key);
bad(key);
val = `${+val}`;
}
else if (t == 'enum') {
if (index(spec.values, val) < 0)
bad(spec, key);
bad(key);
}
else if (t == 'host') {
if (!valid_host(val))
bad(spec, key);
bad(key);
}
else if (t == 'url') {
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
bad(spec, key);
bad(key);
}
else if (t == 'file') {
if (substr(val, 0, 1) != '/' || !stat(val))
die(`${val} does not exist.`);
die(sprintf(_('File %s does not exist.'), val));
}
else if (t == 'domain') {
if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
bad(spec, key);
bad(key);
}
else if (t == 'ipv4') {
if (!ipv4(val))
bad(spec, key);
bad(key);
}
else if (t == 'time') {
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
bad(spec, key);
bad(key);
}
return val;
};
@@ -5,6 +5,7 @@
import { lock, unlock } from 'dawnline.util';
import * as core from 'dawnline.core';
import { _ } from 'dawnline.i18n';
/** Section names that are never ids of people, devices, servers, services or circles. */
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
@@ -15,8 +16,11 @@ export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
* caller's change never happened, and nothing downstream may act on it.
*/
export function commit(c) {
if (!c.commit(core.CONFIG))
die(`Couldn't save /etc/config/dawnline: ${c.error() ?? 'the write failed'}. Is the flash full?`);
if (!c.commit(core.CONFIG)) {
let why = c.error();
die(why != null ? sprintf(_("Couldn't save /etc/config/dawnline: %s. Is the flash full?"), why)
: _("Couldn't save /etc/config/dawnline: the write failed. Is the flash full?"));
}
system('chmod 600 /etc/config/dawnline');
};
@@ -1,12 +1,15 @@
// Dawnline updater: Dawnline itself — check the latest release, install a
// release (latest, a tag, the same one again) or the kept previous version.
// The admin's translations installed on the router (luci-i18n-dawnline-<lang>)
// come from the same release and go in with it, in one transaction.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { readfile } from 'fs';
import { readfile, lsdir } from 'fs';
import { VERSION, REPO } from 'dawnline.util';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg';
import { _ } from 'dawnline.i18n';
function status(installed, latest) {
let c = upd.version_cmp(installed, latest);
@@ -16,12 +19,12 @@ function status(installed, latest) {
export function check(ctx) {
let r = gh.latest(REPO);
if (!r)
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` };
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: sprintf(_('Cannot reach github.com/%s'), REPO) };
let latest = replace(r.tag, /^v/, '');
let st = status(VERSION, latest);
ctx.log(st == 'outdated' ? `Dawnline update is available: ${VERSION} → ${latest}`
: st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}`
: `Dawnline is up to date (${VERSION})`);
ctx.log(st == 'outdated' ? sprintf(_('Dawnline update is available: %s → %s'), VERSION, latest)
: st == 'dev' ? sprintf(_('Installed Dawnline %s is newer than the release %s'), VERSION, latest)
: sprintf(_('Dawnline is up to date (%s)'), VERSION));
return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st };
};
@@ -44,21 +47,51 @@ function want_sha(ctx, tag, asset, dir) {
return null;
}
/** Download a release's package, verified against its sha256. */
function fetch(ctx, tag, dir) {
let ver = replace(tag, /^v/, '');
let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`;
ctx.phase(`Downloading ${asset}`);
/** The languages of the translations installed here, by their catalogs (dawnline.<lang>.lmo). */
export function langs() {
let out = [];
for (let f in lsdir('/usr/lib/lua/luci/i18n') ?? []) {
let m = match(f, /^dawnline\.([A-Za-z_-]+)\.lmo$/);
if (m)
push(out, m[1]);
}
return sort(out);
};
const i18n_pkg = (lang) => `luci-i18n-dawnline-${lang}`;
/**
* Download one file of a release, verified against its sha256. `optional`: a
* release without it (one from before the translations) gives null.
*/
function fetch_file(ctx, tag, asset, dir, optional) {
ctx.phase(sprintf(_('Downloading %s'), asset));
let want = want_sha(ctx, tag, asset, dir);
if (!want && optional) {
ctx.log(sprintf(_('Release %s has no %s: it stays as it is'), tag, asset));
return null;
}
if (!want)
die(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`);
die(sprintf(_('Release %s publishes no checksum for %s: not installing an unverified package'), tag, asset));
let f = `${dir}/${asset}`;
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }))
die(`Download failed: ${asset}`);
ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`);
die(sprintf(_('Download failed: %s'), asset));
ctx.log(sprintf(_('sha256 matches the release (%s…)'), substr(want, 0, 12)));
return f;
}
/** A release's package and the translations installed here, verified. */
function fetch(ctx, tag, dir) {
let ver = replace(tag, /^v/, '');
let files = [ fetch_file(ctx, tag, `luci-app-dawnline-${ver}.${pkg.ext()}`, dir) ];
for (let l in langs()) {
let f = fetch_file(ctx, tag, `${i18n_pkg(l)}-${ver}.${pkg.ext()}`, dir, true);
if (f)
push(files, f);
}
return files;
}
/** The release tag of a version: tags may or may not carry the v. */
function tag_of(ver) {
for (let t in [ `v${ver}`, ver ]) {
@@ -72,23 +105,54 @@ function tag_of(ver) {
}
function backup(ctx) {
ctx.phase('Backing up configuration');
ctx.phase(_('Backing up configuration'));
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
}
/** arg: null (latest) | @<tag> | reinstall | rollback */
/**
* Add the translation `lang` of the installed version from its release, or
* (lang null) remove the installed ones. LuCI reads its catalogs once per web
* server process: it restarts after the job.
*/
function set_lang(ctx, lang) {
if (lang == null) {
let have = map(langs(), i18n_pkg);
if (length(have)) {
ctx.phase(_('Removing the translation'));
if (!pkg.remove(have, ctx.log))
die(_('The translation could not be removed'));
}
}
else {
let tag = tag_of(VERSION);
let f = fetch_file(ctx, tag, `${i18n_pkg(lang)}-${VERSION}.${pkg.ext()}`, ctx.work, true);
if (!f)
die(sprintf(_('Release %s has no translation into %s: install a release that has one'), tag, lang));
ctx.phase(_('Installing the translation'));
if (!pkg.install_files([ f ], false, ctx.log))
die(_('Installation failed'));
}
ctx.after('luci');
return { from: VERSION, to: VERSION, lang };
}
/** arg: null (latest) | @<tag> | reinstall | rollback | lang:<code> | nolang */
export function install(ctx, arg) {
if (arg == 'nolang')
return set_lang(ctx, null);
if (substr(arg ?? '', 0, 5) == 'lang:')
return set_lang(ctx, substr(arg, 5));
let out = { from: VERSION, to: null };
if (arg == 'rollback') {
let k = upd.kept('app');
if (!k)
die('No previous Dawnline version is kept on the router');
die(_('No previous Dawnline version is kept on the router'));
out.to = k.version;
ctx.versions(VERSION, k.version);
backup(ctx);
ctx.phase(`Rolling back to ${k.version}`);
ctx.phase(sprintf(_('Rolling back to %s'), k.version));
if (!pkg.install_files(k.files, true, ctx.log))
die('Installation failed');
die(_('Installation failed'));
upd.forget('app');
ctx.after('app');
return out;
@@ -114,25 +178,25 @@ export function install(ctx, arg) {
}
out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work);
let files = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps
// no package files). Always for an automatic run: nobody is there to
// recover a router whose new version does not come up (postupdate rolls
// back to it on its own).
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
ctx.phase(sprintf(_('Keeping Dawnline %s for rollback'), VERSION));
try {
system(`mkdir -p '${ctx.work}/keep'`);
upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]);
upd.keep('app', VERSION, fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`));
}
catch (e) {
ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`);
ctx.log(sprintf(_('Warning: could not keep %s: %s'), VERSION, e.message));
}
}
backup(ctx);
ctx.phase('Installing package');
if (!pkg.install_files([ f ], force, ctx.log))
die('Installation failed');
ctx.phase(_('Installing package'));
if (!pkg.install_files(files, force, ctx.log))
die(_('Installation failed'));
ctx.after('app');
return out;
};
@@ -10,6 +10,7 @@ import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
import { _, N_ } from 'dawnline.i18n';
function sh(cmd) {
return system(`${cmd} >/dev/null 2>&1`);
@@ -51,16 +52,16 @@ export function check(ctx) {
let fw = builds.firmware();
if (!fw)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'Cannot detect the firmware target' };
note: _('Cannot detect the firmware target') };
if (fw.snapshot)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only' };
note: _('This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only') };
let dir = `${ctx.work}/check`;
system(`mkdir -p '${dir}'`);
let sources = {};
for (let id in builds.ORDER) {
let src = builds.SOURCES[id];
ctx.log(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`);
ctx.log(sprintf(_('Looking for the %s build for OpenWrt %s'), src.label, substr(fw.tag, 1)));
let f = fetch(ctx, fw, 'amneziawg-tools', id, dir);
let v = f ? pkg.file_version(f) : null;
let date = null;
@@ -89,16 +90,16 @@ export function check(ctx) {
let mine = current ? sources[current] : null;
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
ctx.log(cur == null ? 'AmneziaWG is not installed'
: !current ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more`
: st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}`
: `AmneziaWG is up to date (${cur})`);
ctx.log(cur == null ? _('AmneziaWG is not installed')
: !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
: st == 'outdated' ? sprintf(_('AmneziaWG update is available: %s → %s'), cur, mine.version)
: sprintf(_('AmneziaWG is up to date (%s)'), cur));
return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources,
latest: mine?.version ?? null, status: st,
update: cur == null || st == 'outdated',
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null };
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null };
};
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
@@ -112,7 +113,8 @@ function reload_module(ctx, before, after) {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']);
});
ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
let n = length(ifaces);
ctx.phase(sprintf(N_(n, 'Reloading the kernel module (%d tunnel restarts)', 'Reloading the kernel module (%d tunnels restart)'), n));
for (let i in ifaces) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`);
@@ -121,10 +123,10 @@ function reload_module(ctx, before, after) {
// 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');
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)");
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}'`);
}
@@ -132,15 +134,15 @@ function reload_module(ctx, before, after) {
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
ctx.phase('Loading the kernel module');
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");
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.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
ctx.run('/etc/init.d/network restart');
}
ctx.after('apply');
@@ -166,19 +168,19 @@ export function install(ctx, arg) {
let out = { from: before['amneziawg-tools'], to: null, before };
let fw = builds.firmware();
if (!fw)
die('Cannot detect the firmware target');
die(_('Cannot detect the firmware target'));
if (arg == 'rollback') {
let k = upd.kept('amneziawg');
if (!k)
die('No previous AmneziaWG build is kept on the router');
die(_('No previous AmneziaWG build is kept on the router'));
if (k.firmware && k.firmware != fw.postfix)
die('The kept AmneziaWG build was made for another firmware: it would not load on this one');
die(_('The kept AmneziaWG build was made for another firmware: it would not load on this one'));
out.to = k.version;
out.build = k.build;
ctx.versions(out.from, out.to);
ctx.phase(`Rolling back to ${k.version}`);
ctx.phase(sprintf(_('Rolling back to %s'), k.version));
if (!pkg.install_files(k.files, true, ctx.log))
die('Package installation failed');
die(_('Package installation failed'));
upd.forget('amneziawg');
out.after = builds.installed();
settle(ctx, before, out.after);
@@ -190,18 +192,18 @@ export function install(ctx, arg) {
if (id == 'auto') {
id = pick(fw);
if (!id)
die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`);
die(sprintf(_('No AmneziaWG build for OpenWrt %s (%s) yet'), substr(fw.tag, 1), fw.postfix));
}
let src = builds.SOURCES[id];
if (!src)
die(`Unknown AmneziaWG build ${id}`);
die(sprintf(_('Unknown AmneziaWG build %s'), id));
out.build = id;
let files = [];
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
ctx.phase(`Downloading ${p} from ${src.repo}`);
ctx.phase(sprintf(_('Downloading %s from %s'), p, src.repo));
let f = fetch(ctx, fw, p, id, ctx.work);
if (!f)
die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`);
die(sprintf(_('No %s build for OpenWrt %s in %s, or it could not be verified'), p, substr(fw.tag, 1), src.repo));
push(files, f);
}
out.to = pkg.file_version(files[1]);
@@ -219,19 +221,19 @@ export function install(ctx, arg) {
kept = sid;
}
if (kept) {
ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`);
ctx.phase(sprintf(_('Keeping AmneziaWG %s for rollback'), out.from));
let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x);
if (length(keepf) == length(builds.PKGS))
upd.keep('amneziawg', out.from, keepf, kept, fw.postfix);
}
else
ctx.log('Warning: the installed build is no longer published, nothing to keep for rollback');
ctx.log(_('Warning: the installed build is no longer published, nothing to keep for rollback'));
}
ctx.phase('Refreshing package lists');
ctx.phase(_('Refreshing package lists'));
pkg.refresh(ctx.log);
ctx.phase(`Installing the ${src.label} build`);
ctx.phase(sprintf(_('Installing the %s build'), src.label));
if (!pkg.install_files(files, true, ctx.log))
die('Package installation failed');
die(_('Package installation failed'));
if (!want_ru && pkg.version(builds.RU))
pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed();
@@ -4,6 +4,7 @@
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import * as pkg from 'dawnline.pkg';
import { _, N_ } from 'dawnline.i18n';
/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */
export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
@@ -41,7 +42,7 @@ function with_family(names, up) {
/** refresh: update the package lists first (a check by hand or on schedule). */
export function check(ctx, refresh) {
if (refresh ?? true) {
ctx.phase('Refreshing package lists');
ctx.phase(_('Refreshing package lists'));
pkg.refresh();
}
let up = pkg.upgradable();
@@ -54,7 +55,8 @@ export function check(ctx, refresh) {
all[x] = true;
}
let n = length(keys(all));
ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date');
ctx.log(n ? sprintf(N_(n, '%d package update in the feeds: %s', '%d package updates in the feeds: %s'), n, join(', ', sort(keys(all))))
: _('System packages are up to date'));
return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' };
};
@@ -63,22 +65,22 @@ export function install(ctx, arg) {
let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names)
if (index(NAMES, n) < 0)
die(`${n} is not a package Dawnline manages`);
die(sprintf(_('%s is not a package Dawnline manages'), n));
if (!length(names))
die('Nothing to install');
ctx.phase('Refreshing package lists');
die(_('Nothing to install'));
ctx.phase(_('Refreshing package lists'));
pkg.refresh(ctx.log);
let missing = filter(names, (n) => pkg.version(n) == null);
let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable());
if (length(have)) {
ctx.phase(`Updating ${join(', ', have)}`);
ctx.phase(sprintf(_('Updating %s'), join(', ', have)));
if (!pkg.upgrade(have, ctx.log))
die('Update failed');
die(_('Update failed'));
}
if (length(missing)) {
ctx.phase(`Installing ${join(', ', missing)}`);
ctx.phase(sprintf(_('Installing %s'), join(', ', missing)));
if (!pkg.add(missing, ctx.log))
die('Installation failed');
die(_('Installation failed'));
}
// The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start.
let touched = [ ...missing, ...have ];
@@ -6,6 +6,7 @@
import { open, stat } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
export const JOB_FILE = `${RUN_DIR}/update-job.json`;
export const CHECK_FILE = `${RUN_DIR}/update-check.json`;
@@ -126,12 +127,16 @@ export function busy() {
return false;
};
/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */
/**
* The last job; a "running" one whose worker is gone (the lock is free) reads
* as failed. Its phases, log and error are in the language of whoever started
* it (English for automatic runs); only the stopped-job error is made here.
*/
export function job() {
let j = read_json(JOB_FILE, null);
if (j?.state == 'running' && !busy()) {
j.state = 'failed';
j.error = 'The update stopped unexpectedly.';
j.error = _('The update stopped unexpectedly.');
j.finished = j.finished ?? time();
}
return j;
@@ -3,8 +3,9 @@
// helpers work on a cursor the caller owns).
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
import { _ } from 'dawnline.i18n';
export const VERSION = '0.10.0';
export const VERSION = '0.11.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -543,8 +544,10 @@ export function valid_name(s) {
return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
};
/** What valid_name wants, for the admin. */
export const NAME_RULE = 'Enter a name: up to 48 characters, without < > " or \\.';
/** What valid_name wants, for the admin (in the admin's language). */
export function name_rule() {
return _('Enter a name: up to 48 characters, without < > " or \\.');
};
export function valid_key(s) {
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
@@ -1,10 +1,12 @@
// Dawnline — watchdog. The agent runs it every minute: it checks what keeps
// people connected and repairs what it can, waiting longer after each repair
// that did not help. What it finds goes to the service log; its state to
// RUN_DIR for the Health page. A cron job (libexec/dawnline/heartbeat) looks
// after the agent itself.
// that did not help. What it finds goes to the service log (English, as
// logged); its state to RUN_DIR for the Health page, whose chip names are put
// in the admin's language when they are read (view()). A cron job
// (libexec/dawnline/heartbeat) looks after the agent itself.
import { stat } from 'fs';
import { _, L_ } from 'dawnline.i18n';
import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util';
import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop';
@@ -34,8 +36,10 @@ function restart_services() {
}
/**
* What to look at: { id (= the Health check id), src, name (chip), who (the log's subject), ok,
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> — <what>".
* What to look at: { id (= the Health check id), src, name (chip, stored in English: view()
* shows names() by id), who (the log's subject), ok,
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> - <what>"; its
* words are L_(): English in the log, translated where it is shown.
*/
function probes(m) {
let out = [];
@@ -43,48 +47,48 @@ function probes(m) {
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
if (length(m.servers))
push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: nft.present(),
problem: 'are missing', back: 'are loaded again',
repair: { what: 'loading them again', run: () => apply.apply() },
id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
problem: L_('are missing'), back: L_('are loaded again'),
repair: { what: L_('loading them again'), run: () => apply.apply() },
});
if (length(filter(values(m.servers), (x) => x.private_key))) {
let fw = apply.firewall_drift(m);
push(out, {
id: 'fw', src: 'dawnline', name: 'Firewall', who: 'Firewall', ok: fw == null,
problem: fw == 'off' ? "isn't running on this router (fw4): tunnels and the portal are closed"
: fw == 'changed' ? "rules for Dawnline were changed or removed" : "rules for Dawnline aren't loaded",
back: 'rules for Dawnline are in place again',
id: 'fw', src: 'dawnline', name: 'Firewall', who: L_('Firewall'), ok: fw == null,
problem: fw == 'off' ? L_("isn't running on this router (fw4): tunnels and the portal are closed")
: fw == 'changed' ? L_("rules for Dawnline were changed or removed") : L_("rules for Dawnline aren't loaded"),
back: L_('rules for Dawnline are in place again'),
// fw4 stopped on purpose is the admin's call: report it, do not start it.
repair: fw == 'off' ? null : { what: 'restoring them', run: () => { apply.apply(); system('fw4 -q reload'); } },
repair: fw == 'off' ? null : { what: L_('restoring them'), run: () => { apply.apply(); system('fw4 -q reload'); } },
});
}
let s = m.settings;
if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port)))
push(out, {
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: health.tcp_listening(s.portal_port),
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again',
id: 'portal', src: 'portal', name: 'Portal', who: L_('Personal portal'), ok: health.tcp_listening(s.portal_port),
problem: sprintf(L_("isn't answering on port %d"), s.portal_port), back: L_('answers again'),
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
repair: { what: 'restarting it', run: restart_services },
repair: { what: L_('restarting it'), run: restart_services },
});
// Only while a server is on: with all of them off it idles on loopback.
if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key)))
push(out, {
id: 'resolver', src: 'dawnline', name: 'Resolver', who: 'DNS for Home-only devices', ok: loop.resolver_running(),
problem: "isn't running", back: 'runs again',
repair: { what: 'restarting it', run: restart_services },
id: 'resolver', src: 'dawnline', name: 'Resolver', who: L_('DNS for Home-only devices'), ok: loop.resolver_running(),
problem: L_("isn't running"), back: L_('runs again'),
repair: { what: L_('restarting it'), run: restart_services },
});
push(out, {
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
problem: L_("can't reach Dawnline (luci.dawnline is missing in rpcd)"), back: L_('reaches Dawnline again'),
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
// A reload keeps LuCI logins; a restart (second try) signs everyone out —
// and after three it stops: restarting rpcd every hour for good would
// sign every admin out for good.
repair: { what: 'reloading rpcd', max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
repair: { what: L_('reloading rpcd'), max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
});
return out;
}
@@ -107,7 +111,8 @@ export function run(m) {
x.ok = p.ok;
if (p.ok) {
if (x.reported)
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
slog(p.src, 'up', x.stuck ? sprintf(L_('%s · restored'), p.back)
: x.tries ? sprintf(x.tries > 1 ? L_('%s (after %d repairs)') : L_('%s (after %d repair)'), p.back, x.tries) : p.back, null, p.who);
x.bad = 0;
x.next = 0;
x.reported = false;
@@ -128,7 +133,7 @@ export function run(m) {
if (busy)
continue;
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
slog(p.src, 'error', `${p.problem} — not repaired again (${p.repair.max} repairs didn't help)`, p.detail?.(), p.who);
slog(p.src, 'error', sprintf(L_("%s - not repaired again (%d repairs didn't help)"), p.problem, p.repair.max), p.detail?.(), p.who);
x.reported = true;
continue;
}
@@ -142,7 +147,7 @@ export function run(m) {
// trying quietly until it works again (that is logged).
if (x.tries >= 3 && !x.stuck && now - (x.last ?? 0) >= 50) {
x.stuck = true;
slog(p.src, 'error', `${p.problem} — ${x.tries} repairs didn't help`, p.detail?.(), p.who);
slog(p.src, 'error', sprintf(L_("%s - %d repairs didn't help"), p.problem, x.tries), p.detail?.(), p.who);
}
if (now < x.next)
continue;
@@ -151,13 +156,13 @@ export function run(m) {
x.next = now + WAIT[min(x.tries, length(WAIT) - 1)];
x.reported = true;
if (!x.stuck)
slog(p.src, 'repair', `${p.problem} — ${p.repair.what}`, p.detail?.(), p.who);
slog(p.src, 'repair', sprintf(L_('%s - %s'), p.problem, p.repair.what), p.detail?.(), p.who);
try {
p.repair.run(x.tries);
}
catch (e) {
if (!x.stuck)
slog(p.src, 'error', `couldn't be repaired: ${e.message}`, null, p.who);
slog(p.src, 'error', sprintf(L_("couldn't be repaired: %s"), e.message), null, p.who);
}
if (!x.stuck)
push(repairs, { ts: now, id: p.id, name: p.name });
@@ -168,18 +173,33 @@ export function run(m) {
write_json(STATE, { last: now, targets: t, repairs }, 0o644);
};
/** For the Health page: the watchdog's state and the newest log entries. */
/**
* The chip names of probes() by target id, in the language of the call. The
* others (AmneziaWG's, "Home · AmneziaWG") are names only and stay as stored.
*/
function names() {
return {
agent: _('Agent'), nft: _('Access rules'), fw: _('Firewall'), portal: _('Portal'),
resolver: _('Resolver'), rpc: _('LuCI link'),
};
}
/**
* 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.
*/
export function view(m) {
let st = read_json(STATE, {});
let beat = +(read_json(BEAT, 0) ?? 0);
let n = names();
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
let targets = [ { id: 'agent', name: 'Agent', ok: beat > 0 && time() - beat < 180, tries: 0 } ];
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: x.name, ok: !!x.ok, tries: x.tries ?? 0 });
push(targets, { id, name: 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: st.repairs ?? [],
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })),
},
log: slog_read(200),
};
+1
View File
@@ -16,6 +16,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
- Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script.
- Doc comments (`/** … */`) on every export: what it returns, including the null/empty case.
- Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked.
- Messages people read (`die()` texts, check titles and details, phases) go through `_()` / `N_()` of `dawnline.i18n`, inside functions, with `sprintf()` for values (`i18n.md`).
- nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table).
## Cost on the router
+1 -1
View File
@@ -15,7 +15,7 @@ Match the code around you: its naming, comment density and idiom win over person
- **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it).
- **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`.
- **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks. The same goes for its strings: new text is translated in the same change, removed text leaves the catalogs (`i18n.md`).
## Logic and state
+2 -2
View File
@@ -1,6 +1,6 @@
# Frontend (TypeScript: admin UI and portal)
Read with `code-standards.md` and, for anything visible, `ui-design.md`.
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`).
## Code
@@ -16,4 +16,4 @@ Read with `code-standards.md` and, for anything visible, `ui-design.md`.
## Checks
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build`; the rebuilt bundles under `package/` are committed (CI fails otherwise).
- 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).
+97
View File
@@ -0,0 +1,97 @@
# Translations (admin UI, portal, backend messages)
Dawnline is written in English and translated through gettext catalogs. Russian is the first translation. Read with `frontend.md` (and `backend.md` for messages the router sends).
## The rule
- **What is added is localized in the same change.** A new page, section, control, toast, error, check or log line in the admin UI, the portal or the backend comes with its strings wrapped (`_()`, `N_()`, `plural()`, `L_()`) and translated in every `ru.po`. Not "later": CI refuses a catalog with an untranslated string.
- **What is removed leaves nothing behind.** Deleting or rewording text deletes its old entries: `npm run i18n` drops every entry no code uses any more, and `npm run i18n:check` (CI) fails while a catalog still holds one. No dead entries, no hand-kept leftovers, no commented-out translations: the catalogs follow the code, as the code follows `code-standards.md` ("Delete, don't deprecate").
- **Every change to visible text is checked in Russian too**: the wording against the glossary below, the layout at narrow widths (Russian runs longer).
## How it fits together
- **Admin UI (LuCI).** Every visible string goes through LuCI's globals `_()` and `N_()`. The catalog is `package/luci-app-dawnline/po/ru/dawnline.po`; luci.mk compiles it with po2lmo into the separate package `luci-i18n-dawnline-ru` (`/usr/lib/lua/luci/i18n/dawnline.ru.lmo`, plus the uci-defaults that adds Russian to LuCI's languages). LuCI loads it when the page language is Russian (`luci.main.lang`, or `auto` with a Russian browser). Without the package everything stays English. The LuCI menu titles (`menu.d`) are in the same catalog.
- **Portal.** Not LuCI: it carries its own catalog (`web/src/portal/i18n/ru.po`, made into a lookup table at build time and bundled into `portal.js`), so it speaks Russian on every router, with or without the admin's package. `portal/i18n.ts` installs `_()`/`N_()` with LuCI's meaning, opens in the visitor's kept choice or the browser's language, and the language menu in the breadcrumb switches it in place. The demo's own strings are in `web/src/portal/demo/i18n/`.
- **Shared code** (`web/src/shared`) runs in both and is in both catalogs.
- **Backend messages** (ucode: `die()` texts, health checks, endpoint verdicts, the updater's phases) go through `_()` / `N_()` from `dawnline.i18n` and are in the `dawnline` catalog too. The admin page sends its language with every RPC call (`lang`, added by `web/src/admin/api.ts` and stripped by `rpcd/ucode/luci.dawnline`), the updater gets it from the job's start (`DAWNLINE_LANG`), the portal's CGI from `Accept-Language` (the portal's fetch sends the visitor's choice). `dawnline.i18n` reads LuCI's catalog through `luci.core`, so the backend speaks Russian where `luci-i18n-dawnline-ru` is installed; the portal page translates what reaches it in English from `portal.uc`, `devices.uc`, `core.uc` and `awg.uc` with its own catalog. The agent's and the CLI's terminal output stay English. Text the backend stores and shows later is stored as a code (or, for service log lines, as `L_()` templates) and put into words when it is read.
- **Delivery.** The release has `luci-i18n-dawnline-ru-<version>.{ipk,apk}` next to the app. `install.sh` adds it when LuCI is in Russian (its setting, or `luci-i18n-base-ru` installed) or with `--lang ru`; the updater installs it with every Dawnline update when it is installed; Components → Dawnline → Translation adds or removes it. LuCI reads a language's catalogs once per web server process, so each of these restarts uhttpd afterwards.
- **Collecting.** `npm run i18n` (in `web/`) reads the code and rewrites the `.pot` templates and the `.po` files: new strings are added untranslated, gone ones removed, translations kept (and reused across catalogs). `npm run i18n:check` (CI) fails when a catalog is out of date, a string is untranslated, or a translation lost a placeholder. After changing visible text: run `npm run i18n`, translate the new entries in each `ru.po`, commit the catalogs with the code.
## Writing strings
- **Every visible string is wrapped**: text, buttons, headings, toasts, errors, tooltips (`title`), `aria-label`, `placeholder`, `alt`, the page title, confirm dialogs, CSV headers. Not wrapped: product and protocol names standing alone (Dawnline, AmneziaWG, WireGuard, OpenWrt, LuCI), ids, keys, paths, commands, package names, CSS classes, URLs, values sent to the router, log/event ids, `console` output.
- **Literals only.** `_('Save')`, never `_(label)` or `` _(`Hello ${name}`) ``: the extractor cannot collect them and fails. Placeholders `%s` (or `%d`) are filled with `fmt()` from `shared/i18n.ts`: `fmt(_('Removed %s'), name)`.
- **Whole sentences.** Never glue a sentence from pieces (`'Removed ' + name + ' from ' + circle`, or `_('ends') + ' ' + date`): word order and case endings differ. One msgid per sentence with placeholders. Pieces joined by separators (`PC · 10.0.0.2 · online`) are separate facts and stay separate strings.
- **Elements inside a sentence** (a link, a `<b>`): `fill(_('Install it in %s'), link)` returns the children for `E()` / `h()`. The link text is its own `_()`.
- **Counts** go through `plural(n, '%s device', '%s devices')` (number formatted, both forms literals) or `N_(n, 'Device', 'Devices')` when the number is not in the text. Never `n === 1 ? … : …` or `` `${n} devices` ``: Russian has three forms (1 устройство, 2 устройства, 5 устройств), and 21 takes the singular. Use them even where English always has the plural.
- **Numbers and dates** in the page's language: `num(n)` (2,000 / 2 000), `num(v, 1)` for one decimal, `bytes()`, `fmtDay()`, `toLocaleDateString(locale(), …)`. Never a hard-coded `'en-GB'` or `toFixed()` for shown numbers.
- **Text is made when it is drawn**, inside functions, never at module level in the portal and the shared code (the portal changes language in place; the extractor refuses it there). A table of labels becomes a function: `kindLabel(k)` in `shared/format.ts`.
- **Context** when one English word means two things: `_('Off', 'state')` vs `_('Off', 'switch')`. Use it only for real clashes.
- **Whitespace and line breaks** are not part of a msgid: no leading/trailing spaces, no double spaces, no `\n` (LuCI squeezes whitespace before the lookup; po2lmo cannot carry newlines). Put spacing in the markup or the separator.
- **Keep the English as it is** when wrapping, except to turn a glued sentence into one with placeholders.
- **Other apps' labels** (the menus of AmneziaVPN, WireGuard and AmneziaWG in set-up steps) are quoted word for word, with a context of their own (`_('Create from QR code', 'WireGuard app')`), and translated with the app's own Russian from its sources (English where the app has no Russian). Where they come from is noted in `portal/setup.ts`.
- **Messages from the router** arrive in the page's language already (admin) or are translated with `routerText()` (portal): never glue them into a sentence of the page's own; ask the backend for a whole sentence instead.
## Writing backend messages
- `import { _, N_ } from 'dawnline.i18n';` and wrap literals only: `die(_('Backup not found.'))`, `die(sprintf(_('Download failed: %s'), asset))`, `sprintf(N_(n, '%d device', '%d devices'), n)`. Placeholders `%s` and `%d` only, filled after the lookup.
- `_()` inside functions only: rpcd keeps the modules loaded and the language changes with each call (the extractor refuses module-level calls).
- Wrap what a person reads in LuCI or the portal; leave ids, status values, command lines and sentinels alone.
- Messages a portal visitor can get belong in `portal.uc` or `devices.uc` and are best static sentences: the page can translate those without the package.
- **Service log lines** (`slog()` and the watchdog's problem/back/what texts) are written once, in English, by processes with no language (the agent), and read later. Mark their words with `L_()` instead of `_()`: `slog('awg', 'up', sprintf(L_('updated · %s → %s'), a, b), null, L_('System packages'))`. `L_` returns the English; the extractor collects it into the catalog and into `web/src/admin/events/log-templates.ts`, and the admin page matches each line against those templates and translates it (`logText()` in `events/model.ts`), values and nested templates included. Keep a template's English when you touch it (lines already in logs match it), and give the Russian the agreement its subject needs; a translation may start with «:» to go on after the subject («Сервер Home: AmneziaWG не работает»).
## Russian
Write like a careful Russian product (Telegram, Яндекс), not a word-for-word translation.
- **Tone:** polite and short, «вы» in lower case. Buttons and menu items are verbs in the infinitive (perfective where it fits): «Сохранить», «Удалить», «Скопировать», «Добавить устройство», «Изменить»; «Отмена» for Cancel, «Закрыть», «Готово», «Назад», «Далее».
- **States** in forms that fit any person: «На паузе» (not «Приостановлен/а»), «Доступ закончился», «В сети» / «Не в сети». Prefer constructions without gender; when unavoidable, masculine as the neutral form.
- **Typography:** «ёлочки» for quotes, «ё» where it belongs (ещё, всё, истёк), the ellipsis character «…». No em dashes (—): where a dash is needed, a plain one with spaces ( - ), or a colon or a comma (the catalog check refuses «—»). Ranges keep the en dash (1–32, 07:00–23:00). Numbers with a space before units: «1,5 ГБ», «20 Мбит/с».
- **Units:** Б, КБ, МБ, ГБ, ТБ; бит/с, кбит/с, Мбит/с, Гбит/с; «5 мин назад», «3 ч назад», «2 дн. назад»; «2 д 5 ч», «5 ч 12 мин», «12 мин».
- **Length:** Russian runs ~20–30% longer. Keep buttons, pills, tabs and segmented controls short (abbreviate or rephrase), and check the layout in the browser at narrow widths.
- **Product and technical names stay as they are:** Dawnline, AmneziaWG, AmneziaVPN, WireGuard, OpenWrt, LuCI, GitHub, Cloudflare, Let's Encrypt, DDNS, DNS, MTU, UDP, TCP, IPv4/IPv6, NAT, CGNAT, LAN, WAN, QR-код, opkg/apk.
### Glossary
| English | Russian |
|---|---|
| server | сервер |
| person / people (the page) | человек / люди («Люди»); Add person — «Добавить человека» |
| device | устройство |
| circle | круг |
| access | доступ |
| home network | домашняя сеть |
| internet | интернет |
| home network + internet | домашняя сеть и интернет |
| portal, personal link, personal page | портал, личная ссылка, личная страница |
| invite (card) | приглашение (карточка приглашения) |
| disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная |
| data limit | лимит трафика |
| usage, traffic | трафик |
| end date; ends in 3 days | дата окончания; закончится через 3 дня |
| allowed hours; outside allowed hours | часы доступа; вне часов доступа |
| pause / resume; paused | приостановить / возобновить; на паузе |
| online / offline; last seen 12 min ago | в сети / не в сети; «В сети 12 мин назад» (not «Было в сети») |
| set up a device; setup | настроить устройство; настройка |
| app | приложение |
| key, public key, private key | ключ, публичный ключ, приватный ключ |
| configuration file (.conf) | файл конфигурации (.conf) |
| endpoint, public address | адрес сервера, публичный адрес |
| port, port forward | порт, проброс порта |
| tunnel | туннель |
| handshake | рукопожатие |
| router | роутер |
| firewall, zone | межсетевой экран, зона |
| interface, network | интерфейс, сеть |
| certificate | сертификат |
| Overview / Servers / People / Activity | Обзор / Серверы / Люди / События |
| Diagnostics / Health / Logs | Диагностика / Состояние / Журналы |
| Settings / Components / Updates | Настройки / Компоненты / Обновления |
| backup, restore | резервная копия, восстановить |
| check (health), fix | проверка, исправить |
| What's new | Что нового |
| Advanced | Дополнительно |
| watchdog | автовосстановление |
| places (map) | места |
| Copied | Скопировано |
| Undo | Отменить |
+1 -1
View File
@@ -29,4 +29,4 @@ A mock is judged against the page it will live on, so it must already look like
## Done means seen
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow.
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow. Look at it in Russian too: a visible change is localized in the same change (`i18n.md`), and Russian text is longer.
+27 -9
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build the release packages with the OpenWrt SDK in Docker (as CI does):
# scripts/build-packages.sh [ipk|apk|all]
# Output: dist/luci-app-dawnline-<version>.{ipk,apk} and dist/sha256sums.txt
# Output: dist/luci-app-dawnline-<version>.{ipk,apk}, a translation package per
# po/<lang> (dist/luci-i18n-dawnline-<lang>-<version>.{ipk,apk}) and dist/sha256sums.txt
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -25,13 +26,29 @@ build() {
rm -rf "$OUT/.$type" && mkdir -p "$OUT/.$type"
docker cp "$id:/builder/out/." "$OUT/.$type/"
docker rm "$id" >/dev/null
local f
f="$(find "$OUT/.$type" -type f -name "*.$type" | head -n1)"
[ -n "$f" ] || { echo "no .$type built" >&2; exit 1; }
# ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk): one stable name for both.
mv "$f" "$OUT/luci-app-dawnline-$VERSION.$type"
local f name
for f in "$OUT/.$type"/*."$type"; do
[ -f "$f" ] || continue
# ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk), apk names
# dashes: one stable name per package for both, its name and the version.
name="$(basename "$f")"
name="${name%%[_-][0-9]*}"
mv "$f" "$OUT/$name-$VERSION.$type"
echo "$OUT/$name-$VERSION.$type"
done
rm -rf "$OUT/.$type"
echo "$OUT/luci-app-dawnline-$VERSION.$type"
for name in luci-app-dawnline $(i18n_packages); do
[ -f "$OUT/$name-$VERSION.$type" ] || { echo "no $name .$type built" >&2; exit 1; }
done
}
# The translation packages luci.mk makes: one per po/<lang>.
i18n_packages() {
local d
for d in "$APP"/po/*/; do
d="$(basename "$d")"
[ "$d" = templates ] || printf 'luci-i18n-dawnline-%s\n' "$d"
done
}
case "$WHAT" in
@@ -43,9 +60,10 @@ esac
(
cd "$OUT"
set -- luci-app-dawnline-"$VERSION".ipk luci-app-dawnline-"$VERSION".apk
files=""
for f in "$@"; do [ -f "$f" ] && files="$files $f"; done
for name in luci-app-dawnline $(i18n_packages); do
for f in "$name-$VERSION".ipk "$name-$VERSION".apk; do [ -f "$f" ] && files="$files $f"; done
done
# shellcheck disable=SC2086
if command -v sha256sum >/dev/null; then sha256sum $files; else shasum -a 256 $files; fi > sha256sums.txt
)
+14 -2
View File
@@ -1,7 +1,10 @@
#!/usr/bin/env bash
# Build the web bundles and pack luci-app-dawnline as a filesystem overlay
# tarball: dist/luci-app-dawnline-<version>.tar.gz (paths relative to /).
# This is the asset the in-app updater and install.sh install.
# tarball: dist/luci-app-dawnline-<version>.tar.gz (paths relative to /), with
# the translations as their packages lay them out (the catalogs compiled by
# web/i18n/lmo.ts, byte for byte po2lmo's, and the uci-defaults that adds the
# language to LuCI). scripts/deploy.sh installs it for development; releases
# are the .ipk/.apk packages (build-packages.sh).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -19,6 +22,15 @@ grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/pack
mkdir -p "$STAGE/www" "$OUT"
cp -R "$APP/root/." "$STAGE/"
cp -R "$APP/htdocs/." "$STAGE/www/"
for po in "$APP"/po/*/dawnline.po; do
l="$(basename "$(dirname "$po")")"
[ "$l" = templates ] && continue
mkdir -p "$STAGE/usr/lib/lua/luci/i18n"
node "$ROOT/web/i18n/lmo.ts" "$po" "$STAGE/usr/lib/lua/luci/i18n/dawnline.$l.lmo"
# The name LuCI lists the language by (luci.mk's LUCI_LANG.<lang>).
case "$l" in ru) name='Русский (Russian)' ;; *) name="$l" ;; esac
printf "uci set luci.languages.%s='%s'; uci commit luci\n" "$l" "$name" > "$STAGE/etc/uci-defaults/luci-i18n-dawnline-$l"
done
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \
"$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc"
+5
View File
@@ -20,6 +20,11 @@ ls -d /root/dawnline-predeploy-* 2>/dev/null | sort | head -n -5 | xargs -r rm -
tar -xozf /tmp/luci-app-dawnline.tar.gz -C /
rm -f /tmp/luci-app-dawnline.tar.gz
sh /etc/uci-defaults/90_dawnline && rm -f /etc/uci-defaults/90_dawnline
for f in /etc/uci-defaults/luci-i18n-dawnline-*; do
if [ -f "$f" ]; then sh "$f" && rm -f "$f"; fi
done
# LuCI reads a language's catalogs once per web server: the new ones need a fresh one.
/etc/init.d/uhttpd restart
sleep 1
ubus list luci.dawnline >/dev/null && echo "luci.dawnline registered (backup: /root/dawnline-predeploy-$ts)"
REMOTE
+1 -1
View File
@@ -146,7 +146,7 @@ if methods and os.path.exists(ACL):
# Layering (rules/backend.md): util, schema → core → store → domain modules →
# apply → entry points. A module importing one from a layer above it is
# reported, not failed, until the existing edges are untangled.
LAYER = {'util': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER = {'util': 0, 'i18n': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'}
notes = 0
for f in modules:
+12
View File
@@ -103,3 +103,15 @@ test('handshake_since: Reconnect hides older handshakes', () => {
eq(awg.handshake_since(1600, 1500), 1600, 'connected after');
eq(awg.handshake_since(0, 1500), 0, 'never connected');
});
test('blocked reasons', () => {
let srv = (b) => ({ name: 'Home', blocked: b });
eq(awg.blocked_text(srv(null)), null, 'not kept down');
eq(awg.blocked_text(srv({ code: 'ifname', ifname: 'bad name' })), 'Home has an invalid interface name "bad name".', 'interface name');
eq(awg.blocked_text(srv({ code: 'taken', ifname: 'wg0' })), "Home can't use the network interface wg0: it exists and isn't Dawnline's.", 'foreign interface');
eq(awg.blocked_text(srv({ code: 'disguise', need: '3.1', installed: '2.0' })), 'Home is kept down: its disguise needs AmneziaWG 3.1 (installed: 2.0).', 'disguise');
eq(awg.blocked_text(srv({ code: 'disguise', need: '3.1' })), 'Home is kept down: its disguise needs AmneziaWG 3.1 (installed: none).', 'disguise, none installed');
// 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');
});
+20
View File
@@ -0,0 +1,20 @@
// dawnline.i18n: without LuCI's catalogs (this rootfs has no luci-base) every
// message stays English, whatever language is asked for; plural forms pick
// by the count.
import * as i18n from 'dawnline.i18n';
test('English without a catalog', () => {
i18n.use('ru');
eq(i18n.current(), null, 'no Russian catalog here');
eq(i18n._('Backup not found.'), 'Backup not found.', 'as written');
eq(sprintf(i18n.N_(1, '%d device', '%d devices'), 1), '1 device', 'singular');
eq(sprintf(i18n.N_(5, '%d device', '%d devices'), 5), '5 devices', 'plural');
eq(i18n.N_(0, 'a', 'b'), 'b', 'zero takes the plural in English');
});
test('only plain language codes', () => {
for (let l in [ null, '', 'en', 'ru; rm -rf /', '../../etc', 'russian', 42 ]) {
i18n.use(l);
eq(i18n.current(), null, `${l}`);
}
});
+12
View File
@@ -0,0 +1,12 @@
// dawnline.loop: the "like a home device" link's errors, stored as codes and
// put into words when read.
import * as loop from 'dawnline.loop';
test('error_text', () => {
eq(loop.error_text(null), null, 'no error');
eq(loop.error_text({ code: 'no_lan' }), 'No LAN detected.', 'no LAN');
eq(loop.error_text({ code: 'not_bridge', dev: 'eth1' }), 'eth1 is not a bridge, so Dawnline cannot join the LAN as a device.', 'not a bridge');
eq(loop.error_text({ code: 'no_address', net: 'lan' }), 'No free address on lan.', 'no address');
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');
});
+2
View File
@@ -655,6 +655,8 @@ do_leftovers() {
/usr/share/luci/menu.d/luci-app-dawnline.json /www/luci-static/resources/dawnline \
/www/luci-static/resources/view/dawnline
for _r in /etc/rc.d/*dawnline; do [ -e "$_r" ] && set -- "$@" "$_r"; done
# The translations' catalogs (luci-i18n-dawnline-<lang> depends on the package, so it is gone too).
for _r in /usr/lib/lua/luci/i18n/dawnline.*.lmo; do [ -e "$_r" ] && set -- "$@" "$_r"; done
fi
if [ "$PURGE" -eq 1 ]; then
set -- "$@" "$DATA_DIR" /etc/config/dawnline /etc/config/dawnline-opkg /etc/config/dawnline.apk-new
+418
View File
@@ -0,0 +1,418 @@
// Dawnline's string catalogs, collected from the code (run in web/):
//
// node i18n/extract.ts rewrite the .pot templates and merge the .po translations
// node i18n/extract.ts --check CI: fail when a catalog is out of date or a string is untranslated
// node i18n/extract.ts --import a.json … also take translations from drafts: [{ id, ctx?, plural?, str }],
// str a string or, for a plural, one per form
// node i18n/extract.ts --lint [--import a.json …] [--only src/admin/x.ts …]
// write nothing: report string problems, bad or stray drafts
// and, with --only, the strings of those files left untranslated
//
// Three catalogs (rules/i18n.md):
// dawnline — the admin UI, its shared code, the backend's messages and the
// LuCI menu: package/luci-app-dawnline/po (luci.mk builds
// luci-i18n-dawnline-<lang> from it)
// portal — the personal portal, the shared code and the messages of the
// backend modules the portal runs: src/portal/i18n, bundled into portal.js
// demo — what only the portal demo says: src/portal/demo/i18n
//
// A string is collected from _('…'), N_(n, '…', '…') and plural(n, '…', '…')
// with literal arguments, and from the backend's L_('…'): a service log line's
// words, written in English and put into the reader's language when shown (they
// also go into src/admin/events/log-templates.ts, the list the admin page
// matches log lines against). Anything else under those names is an error, as is
// a string LuCI could not find again (leading, trailing or doubled whitespace,
// newlines) and, in the portal and the shared code, a call at module level
// (the portal changes language in place, so text is made when it is drawn).
// The catalogs keep the files a string comes from, not lines: they change
// only when strings do.
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 { keyOf, parsePo, pluralForms, translated, writePo, type Entry, type Po } from './po.ts';
const WEB = path.resolve(import.meta.dirname, '..');
const REPO = path.resolve(WEB, '..');
const PKG = path.join(REPO, 'package/luci-app-dawnline');
/** The translations and their gettext plural rules (po2lmo hands the formula to LuCI's N_()). */
const LANGS: Record<string, { team: string; plural: string }> = {
ru: {
team: 'Russian',
plural: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);',
},
};
const walk = (dir: string, keep: (f: string) => boolean): string[] =>
!fs.existsSync(dir)
? []
: fs
.readdirSync(dir, { withFileTypes: true })
.flatMap((d) =>
d.isDirectory() ? walk(path.join(dir, d.name), keep) : keep(path.join(dir, d.name)) ? [path.join(dir, d.name)] : [],
)
.sort();
const tsFiles = (dir: string, skip?: string) =>
walk(path.join(WEB, dir), (f) => f.endsWith('.ts') && !f.endsWith('.d.ts') && !(skip && f.startsWith(path.join(WEB, skip) + path.sep)));
/** The backend: ucode modules and the ucode programs (by their shebang) in the package. */
const ucodeFiles = () =>
walk(path.join(PKG, 'root'), (f) => f.endsWith('.uc') || (!path.extname(f) && fs.readFileSync(f, 'utf8').startsWith('#!/usr/bin/ucode')));
/**
* The backend modules whose messages reach the portal's visitors (its own
* refusals, what refuses a device change, the keys): the page translates them when
* the router sends them in English (no translation package installed).
*/
const PORTAL_UCODE = ['portal.uc', 'devices.uc', 'core.uc', 'awg.uc'].map((f) => path.join(PKG, 'root/usr/share/ucode/dawnline', f));
const menuFiles = () => walk(path.join(PKG, 'root/usr/share/luci/menu.d'), (f) => f.endsWith('.json'));
interface CatalogSpec {
name: string;
pot: string;
po: (lang: string) => string;
sources: () => string[];
menus?: () => string[];
/** Strings here are made when the page is drawn (the portal switches language in place). */
lazy: (file: string) => boolean;
/** The service log's words (L_) are in it: only the admin page shows the log. */
logs?: boolean;
}
const CATALOGS: CatalogSpec[] = [
{
name: 'dawnline',
pot: path.join(PKG, 'po/templates/dawnline.pot'),
po: (l) => path.join(PKG, `po/${l}/dawnline.po`),
sources: () => [...tsFiles('src/admin'), ...tsFiles('src/shared'), ...ucodeFiles()],
menus: menuFiles,
logs: true,
// rpcd keeps the backend's modules loaded while the language changes per call.
lazy: (f) => f.startsWith(path.join(WEB, 'src/shared')) || f.startsWith(path.join(PKG, 'root')),
},
{
name: 'portal',
pot: path.join(WEB, 'src/portal/i18n/portal.pot'),
po: (l) => path.join(WEB, `src/portal/i18n/${l}.po`),
sources: () => [...tsFiles('src/portal', 'src/portal/demo'), ...tsFiles('src/shared'), ...PORTAL_UCODE],
lazy: () => true,
},
{
name: 'demo',
pot: path.join(WEB, 'src/portal/demo/i18n/demo.pot'),
po: (l) => path.join(WEB, `src/portal/demo/i18n/${l}.po`),
sources: () => tsFiles('src/portal/demo'),
lazy: () => true,
},
];
/** Where the wrappers themselves pass strings on: not literals, by design. */
const WRAPPERS = new Set([path.join(WEB, 'src/shared/i18n.ts'), path.join(WEB, 'src/portal/i18n.ts')]);
/** The string arguments of each translation call: [msgid, msgid_plural?, msgctxt?]; `log`: a log line's words (L_). */
const CALLS: Record<string, { id: number; plural?: number; ctx?: number; log?: boolean }> = {
_: { id: 0, ctx: 1 },
N_: { id: 1, plural: 2, ctx: 3 },
plural: { id: 1, plural: 2 },
L_: { id: 0, log: true },
};
/** The generated list of log line templates (L_), for the admin page. */
const LOG_TEMPLATES_FILE = path.join(WEB, 'src/admin/events/log-templates.ts');
const logTemplates = new Set<string>();
const rel = (f: string) => path.relative(REPO, f).split(path.sep).join('/');
/** Why LuCI would not find this string again, or null. Its lookup squeezes whitespace (cbi.js trimws). */
export function badText(s: string): string | null {
if (!s) return 'is empty';
if (/[\n\r\t]/.test(s)) return 'has a newline or a tab (po2lmo cannot carry them)';
if (/^\s|\s$/.test(s)) return 'starts or ends with a space';
if (/\s\s/.test(s)) return 'has two spaces in a row';
return null;
}
interface Found extends Entry {
files: Set<string>;
}
class Errors {
list: string[] = [];
add(where: string, msg: string) {
this.list.push(`${where}: ${msg}`);
}
}
function isFunctionLike(n: ts.Node): boolean {
return ts.isFunctionLike(n) || ts.isPropertyDeclaration(n) || ts.isClassStaticBlockDeclaration(n);
}
/** 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);
const wrapper = WRAPPERS.has(file);
const visit = (node: ts.Node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && CALLS[node.expression.text] && !wrapper) {
const name = node.expression.text;
const spec = CALLS[name];
const where = `${rel(file)}:${sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1}`;
const lit = (i: number | undefined): string | undefined | null => {
if (i === undefined) return undefined;
const a = node.arguments[i];
if (!a) return undefined;
return ts.isStringLiteral(a) || ts.isNoSubstitutionTemplateLiteral(a) ? a.text : null;
};
const id = lit(spec.id);
const pl = lit(spec.plural);
const ctx = lit(spec.ctx);
if (id == null || pl === null || (spec.plural !== undefined && pl === undefined) || ctx === null) {
errors.add(
where,
`${name}() needs string literals: a variable or a template with \${…} cannot be collected (fill placeholders with fmt())`,
);
} else {
for (const [what, s] of [
['msgid', id],
['plural', pl],
['context', ctx],
] as const)
if (s !== undefined) {
const why = badText(s);
if (why) errors.add(where, `the ${what} ${JSON.stringify(s)} ${why}`);
}
// A log line's words are not translated where they are written: anywhere goes.
if (spec.log) logTemplates.add(id);
else if (lazy && !wrapper) {
let p: ts.Node | undefined = node.parent;
while (p && !isFunctionLike(p)) p = p.parent;
if (!p) errors.add(where, `${name}() at module level: here text is made when it is drawn (the portal changes language in place)`);
}
const e: Found = { id, str: [], refs: [], files: new Set([rel(file)]) };
if (spec.log && !logs) return;
if (pl !== undefined) e.plural = pl;
if (ctx !== undefined) e.ctx = ctx;
out.push(e);
}
}
ts.forEachChild(node, visit);
};
visit(sf);
}
/** LuCI's menu titles (translated by the theme's menu). */
function scanMenu(file: string, out: Found[]) {
const menu = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, { title?: string }>;
for (const node of Object.values(menu)) if (node.title) out.push({ id: node.title, str: [], refs: [], files: new Set([rel(file)]) });
}
/** One catalog's strings, deduplicated and sorted (by code unit: the same order on every machine). */
function collect(spec: CatalogSpec, 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.menus?.() ?? []) scanMenu(f, found);
const byKey = new Map<string, Found>();
for (const e of found) {
const k = keyOf(e);
const had = byKey.get(k);
if (!had) byKey.set(k, e);
else if (had.plural !== e.plural)
errors.add(
[...e.files][0],
`${JSON.stringify(e.id)} is used ${had.plural === undefined || e.plural === undefined ? 'both as a plural and as a plain string' : `with two plurals (${JSON.stringify(had.plural)}, ${JSON.stringify(e.plural)})`}: give one of them a context`,
);
else e.files.forEach((f) => had.files.add(f));
}
return [...byKey.values()]
.map(({ files, ...e }) => ({ ...e, refs: [...files].sort() }))
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : (a.ctx ?? '') < (b.ctx ?? '') ? -1 : (a.ctx ?? '') > (b.ctx ?? '') ? 1 : 0));
}
const HEADER: [string, string][] = [
['Project-Id-Version', 'Dawnline'],
['MIME-Version', '1.0'],
['Content-Type', 'text/plain; charset=UTF-8'],
['Content-Transfer-Encoding', '8bit'],
];
const read = (f: string): Po | null => (fs.existsSync(f) ? parsePo(fs.readFileSync(f, 'utf8')) : null);
interface Draft {
id: string;
ctx?: string;
plural?: string;
str: string | string[];
}
/** The placeholders of a string, in order: what a translation must keep. */
export const holes = (s: string) => (s.match(/%[sd]/g) ?? []).join(' ');
/** Problems in one translation, for --check and the summary. */
export function badTranslation(e: Entry): string | null {
const want = holes(e.plural ?? e.id);
if (e.plural !== undefined && holes(e.id) !== want) return `the singular and the plural have different placeholders`;
for (const s of e.str) {
if (!s) continue;
if (s.includes('\\')) return `${JSON.stringify(s)} has a backslash (po2lmo would show it as written)`;
if (s.includes('—')) return `${JSON.stringify(s)} has an em dash: use a plain dash (rules/i18n.md)`;
const why = badText(s);
if (why) return `${JSON.stringify(s)} ${why}`;
if (holes(s) !== want) return `${JSON.stringify(s)} has the placeholders "${holes(s)}", the English "${want}"`;
}
return null;
}
/** The command line: --check, --lint, and the files after --import and --only. */
function options(argv: string[]) {
const o = { check: false, lint: false, imports: [] as string[], only: [] as string[] };
let list: string[] | null = null;
for (const a of argv) {
if (a === '--check' || a === '--lint') {
o[a === '--check' ? 'check' : 'lint'] = true;
list = null;
} else if (a === '--import') list = o.imports;
else if (a === '--only') list = o.only;
else if (list) list.push(a);
else throw new Error(`unknown argument ${a} (see the top of i18n/extract.ts)`);
}
return o;
}
const draftKey = (d: { ctx?: string; id: string; plural?: string }) => keyOf(d) + (d.plural !== undefined ? '\u0002' : '');
/** The list of log line templates as a module (formatted as the repo formats code). */
async function logTemplatesModule(): Promise<string> {
const list = [...logTemplates].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
const code = [
"// Generated by web/i18n/extract.ts from the backend's L_() strings (npm run i18n): do not edit.",
'// The words of service log lines, as written; events/model.ts matches log lines against them.',
'',
`export const LOG_TEMPLATES: string[] = ${JSON.stringify(list)};`,
'',
].join('\n');
return prettier.format(code, { ...(await prettier.resolveConfig(LOG_TEMPLATES_FILE)), filepath: LOG_TEMPLATES_FILE });
}
async function main() {
const opt = options(process.argv.slice(2));
const errors = new Errors();
const problems: string[] = [];
const drafts = new Map<string, Draft & { from: string }>();
for (const f of opt.imports)
for (const d of JSON.parse(fs.readFileSync(path.resolve(f), 'utf8')) as Draft[]) {
const had = drafts.get(draftKey(d));
if (had && JSON.stringify(had.str) !== JSON.stringify(d.str))
problems.push(
`drafts disagree on ${JSON.stringify(d.id)}: ${JSON.stringify(had.str)} (${had.from}), ${JSON.stringify(d.str)} (${f})`,
);
drafts.set(draftKey(d), { ...d, from: f });
}
const usedDrafts = new Set<string>();
const collected = CATALOGS.map((spec) => ({ spec, entries: collect(spec, 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).
if (opt.lint) problems.push(...errors.list.filter((e) => !only.length || under(e.replace(/:\d+: [\s\S]*$/, ''))));
else if (errors.list.length) {
console.error(errors.list.join('\n'));
console.error(`\n${errors.list.length} string problem(s): fix them in the code (rules/i18n.md).`);
process.exit(1);
}
// What each language already has, across catalogs: a string translated in one is reused in the others.
const known = new Map<string, Map<string, string[]>>();
for (const lang of Object.keys(LANGS)) {
const m = new Map<string, string[]>();
for (const { spec } of collected)
for (const e of read(spec.po(lang))?.entries ?? [])
if (translated(e)) m.set(keyOf(e) + (e.plural !== undefined ? `\u0002${e.plural}` : ''), e.str);
known.set(lang, m);
}
const inOnly = (e: Entry) => e.refs.some(under);
const out = new Map<string, string>();
const report: string[] = [];
const missingOnly = new Set<string>();
for (const { spec, entries } of collected) {
out.set(
spec.pot,
writePo({
header: [...HEADER, ['Plural-Forms', 'nplurals=2; plural=(n != 1);']],
entries: entries.map((e) => ({ ...e, str: e.plural !== undefined ? ['', ''] : [''] })),
}),
);
for (const [lang, info] of Object.entries(LANGS)) {
const file = spec.po(lang);
const old = new Map((read(file)?.entries ?? []).map((e) => [draftKey(e), e]));
const header: [string, string][] = [...HEADER, ['Language', lang], ['Language-Team', info.team], ['Plural-Forms', info.plural]];
const forms = pluralForms({ header, entries: [] });
const merged = entries.map((e): Entry => {
const k = draftKey(e);
const blank = e.plural !== undefined ? Array<string>(forms).fill('') : [''];
const draft = drafts.get(k);
if (draft) {
usedDrafts.add(k);
const str = Array.isArray(draft.str) ? draft.str : [draft.str];
if (str.length === blank.length) return { ...e, str };
problems.push(`${spec.name}/${lang}: the draft for ${JSON.stringify(e.id)} has ${str.length} form(s), ${blank.length} needed`);
}
const was = old.get(k);
// A changed plural keeps its forms only when the English plural stayed the same.
if (was && translated(was) && was.plural === e.plural) return { ...e, str: was.str };
const other = known.get(lang)!.get(keyOf(e) + (e.plural !== undefined ? `\u0002${e.plural}` : ''));
return { ...e, str: other && other.length === blank.length ? other : blank };
});
out.set(file, writePo({ header, entries: merged }));
const missing = merged.filter((e) => !translated(e));
for (const e of merged) {
const why = badTranslation(e);
if (why && (!only.length || inOnly(e))) problems.push(`${rel(file)}: ${JSON.stringify(e.id)}: ${why}`);
}
report.push(`${spec.name}/${lang}: ${merged.length - missing.length} of ${merged.length} translated`);
if (opt.check)
for (const e of missing) problems.push(`${rel(file)}: untranslated ${JSON.stringify(e.id)}${e.ctx ? ` (${e.ctx})` : ''}`);
for (const e of missing)
if (inOnly(e))
missingOnly.add(
`no translation for ${JSON.stringify(e.id)}${e.ctx ? ` (context ${e.ctx})` : ''}${e.plural !== undefined ? ` (plural ${JSON.stringify(e.plural)})` : ''} [${e.refs.filter(under).join(' ')}]`,
);
}
}
for (const [k, d] of drafts)
if (!usedDrafts.has(k))
problems.push(`draft ${JSON.stringify(d.id)}${d.plural !== undefined ? ' (plural)' : ''} is not in the code (${d.from})`);
problems.push(...missingOnly);
out.set(LOG_TEMPLATES_FILE, await logTemplatesModule());
if (opt.check || opt.lint) {
if (opt.check)
for (const [f, text] of out)
if (!fs.existsSync(f) || fs.readFileSync(f, 'utf8') !== text)
problems.unshift(`${rel(f)} is out of date: run "npm run i18n" in web/ and commit the result`);
if (problems.length) {
console.error(problems.join('\n'));
process.exit(1);
}
console.log(opt.lint ? 'No problems.' : report.join('\n'));
return;
}
for (const [f, text] of out) {
if (fs.existsSync(f) && fs.readFileSync(f, 'utf8') === text) continue;
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, text);
}
console.log(report.join('\n'));
if (problems.length) console.warn(`\n${problems.join('\n')}`);
}
// Run as a program; imported (by the tests), only the checks above.
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
+110
View File
@@ -0,0 +1,110 @@
// The LMO catalog LuCI loads (/usr/lib/lua/luci/i18n/<name>.<lang>.lmo), made
// from a .po byte for byte as LuCI's po2lmo makes it. The release packages are
// built by the SDK's own po2lmo (luci.mk); this one is for the dev deploy
// (scripts/build-release.sh), which has no SDK.
//
// Layout: the translations, each padded with zeros to 4 bytes, in the .po's
// order (the Plural-Forms formula first, under key 0); then an index entry per
// string, sorted by key: key hash, number of forms, offset, length (big-endian
// uint32s); then the index's offset. A key is the msgid, with "ctx\x01" before
// it and "\x02<n>" after it for plural form n; its hash is Paul Hsieh's
// SuperFastHash seeded with the length (lmo.c sfh_hash, cbi.js sfh).
//
// node i18n/lmo.ts in.po out.lmo
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parsePo, type Po } from './po.ts';
/** SuperFastHash of the bytes, seeded with their length, as a uint32. */
export function sfh(data: Uint8Array): number {
const get16 = (i: number) => data[i] | (data[i + 1] << 8);
const s8 = (i: number) => (data[i] << 24) >> 24;
let hash = data.length >>> 0;
if (!data.length) return 0;
let i = 0;
for (let n = data.length >>> 2; n > 0; n--, i += 4) {
hash = (hash + get16(i)) >>> 0;
const tmp = ((get16(i + 2) << 11) ^ hash) >>> 0;
hash = ((hash << 16) ^ tmp) >>> 0;
hash = (hash + (hash >>> 11)) >>> 0;
}
switch (data.length & 3) {
case 3:
hash = (hash + get16(i)) >>> 0;
hash = (hash ^ (hash << 16)) >>> 0;
hash = (hash ^ (s8(i + 2) << 18)) >>> 0;
hash = (hash + (hash >>> 11)) >>> 0;
break;
case 2:
hash = (hash + get16(i)) >>> 0;
hash = (hash ^ (hash << 11)) >>> 0;
hash = (hash + (hash >>> 17)) >>> 0;
break;
case 1:
hash = (hash + s8(i)) >>> 0;
hash = (hash ^ (hash << 10)) >>> 0;
hash = (hash + (hash >>> 1)) >>> 0;
}
hash = (hash ^ (hash << 3)) >>> 0;
hash = (hash + (hash >>> 5)) >>> 0;
hash = (hash ^ (hash << 4)) >>> 0;
hash = (hash + (hash >>> 17)) >>> 0;
hash = (hash ^ (hash << 25)) >>> 0;
hash = (hash + (hash >>> 6)) >>> 0;
return hash;
}
const utf8 = (s: string) => new TextEncoder().encode(s);
export function lmo(po: Po): Uint8Array {
const chunks: Uint8Array[] = [];
const index: { key: number; forms: number; offset: number; length: number }[] = [];
let offset = 0;
const add = (key: number, forms: number, value: Uint8Array) => {
const padded = new Uint8Array(value.length + ((4 - (value.length % 4)) % 4));
padded.set(value);
index.push({ key, forms, offset, length: value.length });
chunks.push(padded);
offset += padded.length;
};
const pf = po.header.find(([k]) => k === 'Plural-Forms');
if (pf) add(0, 0, utf8(pf[1]));
for (const e of po.entries) {
if (!e.str[0]) continue;
e.str.forEach((s, i) => {
if (!s) return;
const key = utf8(`${e.ctx !== undefined ? `${e.ctx}\u0001` : ''}${e.id}${e.plural !== undefined ? `\u0002${i}` : ''}`);
const value = utf8(s);
const k = sfh(key);
// An unchanged string is left out: LuCI shows the English anyway.
if (k !== sfh(value)) add(k, e.str.length, value);
});
}
index.sort((a, b) => a.key - b.key);
const out = new Uint8Array(offset + index.length * 16 + (offset > 0 ? 4 : 0));
const view = new DataView(out.buffer);
let at = 0;
for (const c of chunks) {
out.set(c, at);
at += c.length;
}
for (const x of index) {
for (const v of [x.key, x.forms, x.offset, x.length]) {
view.setUint32(at, v);
at += 4;
}
}
if (offset > 0) view.setUint32(at, offset);
return out;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [src, dst] = process.argv.slice(2);
if (!src || !dst) {
console.error('usage: node i18n/lmo.ts in.po out.lmo');
process.exit(2);
}
fs.writeFileSync(dst, lmo(parsePo(fs.readFileSync(src, 'utf8'))));
}
+137
View File
@@ -0,0 +1,137 @@
// Gettext catalogs (.pot / .po) as Dawnline writes them: the subset LuCI's
// po2lmo reads. Entries have an optional msgctxt, a msgid, an optional
// msgid_plural and the msgstr (or msgstr[n], one per plural form), with their
// "#:" source references. Strings are one line each and know two escapes, \"
// and \\: po2lmo copies any other escape as written ("\n" stays a backslash and
// an n), so extract.ts refuses newlines and tabs in strings, and backslashes in
// translations. No dates in the header: a catalog changes only when its strings do.
//
// Pure: no files. extract.ts reads and writes the catalogs; the portal's
// bundle turns a .po into a lookup table with catalogOf().
export interface Entry {
ctx?: string;
id: string;
plural?: string;
/** The translation: one string, or one per plural form. '' where there is none yet. */
str: string[];
/** Where the string is used: "src/admin/pages/people.ts:120". */
refs: string[];
}
export interface Po {
/** Header fields in their order ("Language", "Plural-Forms", …). */
header: [string, string][];
entries: Entry[];
}
/** An entry's identity: its context and msgid (the plural form shares its msgid's). */
export const keyOf = (e: { ctx?: string; id: string }) => (e.ctx ? `${e.ctx}\u0004${e.id}` : e.id);
export const translated = (e: Entry) => e.str.length > 0 && e.str.every((s) => s !== '');
/** A quoted po string's content: \" and \\ read, any other escape kept as written (the header's \n). */
function unquote(s: string, line: number): string {
const m = /^"((?:[^"\\]|\\.)*)"$/.exec(s);
if (!m) throw new Error(`po line ${line}: expected a quoted string, got ${s}`);
return m[1].replace(/\\(.)/g, (all, c: string) => (c === '"' || c === '\\' ? c : all));
}
const quote = (s: string) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
type Draft = { ctx?: string; id?: string; plural?: string; str: string[]; refs: string[] };
export function parsePo(text: string): Po {
const po: Po = { header: [], entries: [] };
let cur: Draft = { str: [], refs: [] };
// Where a continuation line ("…") goes: the field the last keyword opened.
let append: ((s: string) => void) | null = null;
const flush = () => {
if (cur.id === '' && cur.ctx === undefined) {
for (const f of (cur.str[0] ?? '').split('\\n')) {
const i = f.indexOf(':');
if (i > 0) po.header.push([f.slice(0, i).trim(), f.slice(i + 1).trim()]);
}
} else if (cur.id !== undefined) {
const e: Entry = { id: cur.id, str: cur.str.map((s) => s ?? ''), refs: cur.refs };
if (cur.ctx !== undefined) e.ctx = cur.ctx;
if (cur.plural !== undefined) e.plural = cur.plural;
po.entries.push(e);
}
cur = { str: [], refs: [] };
};
text.split(/\r?\n/).forEach((raw, n) => {
const line = raw.trim();
if (!line) return void (append = null);
if (line.startsWith('#')) {
if (cur.id !== undefined) flush();
if (line.startsWith('#:')) cur.refs.push(...line.slice(2).trim().split(/\s+/).filter(Boolean));
append = null;
return;
}
if (line.startsWith('"')) {
if (!append) throw new Error(`po line ${n + 1}: a string outside an entry`);
return append(unquote(line, n + 1));
}
const m = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d)\])?)\s+(".*")$/.exec(line);
if (!m) throw new Error(`po line ${n + 1}: cannot read ${line}`);
const [, kw, idx, val] = m;
const v = unquote(val, n + 1);
if ((kw === 'msgctxt' || kw === 'msgid') && cur.id !== undefined) flush();
if (kw === 'msgctxt') {
cur.ctx = v;
append = (s) => (cur.ctx += s);
} else if (kw === 'msgid') {
cur.id = v;
append = (s) => (cur.id += s);
} else if (kw === 'msgid_plural') {
cur.plural = v;
append = (s) => (cur.plural += s);
} else {
const i = idx === undefined ? 0 : Number(idx);
cur.str[i] = v;
append = (s) => (cur.str[i] += s);
}
});
flush();
return po;
}
export function writePo(po: Po): string {
const out = ['msgid ""', 'msgstr ""', ...po.header.map(([k, v]) => `${quote(`${k}: ${v}`).slice(0, -1)}\\n"`), ''];
for (const e of po.entries) {
for (const r of e.refs) out.push(`#: ${r}`);
if (e.ctx !== undefined) out.push(`msgctxt ${quote(e.ctx)}`);
out.push(`msgid ${quote(e.id)}`);
if (e.plural !== undefined) {
out.push(`msgid_plural ${quote(e.plural)}`);
e.str.forEach((s, i) => out.push(`msgstr[${i}] ${quote(s)}`));
} else out.push(`msgstr ${quote(e.str[0] ?? '')}`);
out.push('');
}
return out.join('\n');
}
/** The number of plural forms a catalog's header declares (2 when it says nothing). */
export function pluralForms(po: Po): number {
const pf = po.header.find(([k]) => k === 'Plural-Forms')?.[1] ?? '';
const m = /nplurals\s*=\s*(\d+)/.exec(pf);
return m ? Number(m[1]) : 2;
}
/** What the portal looks strings up in: translated strings by key, plural forms by the singular's key. */
export interface Catalog {
s: Record<string, string>;
p: Record<string, string[]>;
}
/** A .po as a lookup table: translated entries only (an untranslated string stays English). */
export function catalogOf(po: Po): Catalog {
const c: Catalog = { s: {}, p: {} };
for (const e of po.entries) {
if (!translated(e)) continue;
if (e.plural !== undefined) c.p[keyOf(e)] = e.str;
else c.s[keyOf(e)] = e.str[0];
}
return c;
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "dawnline-web",
"version": "0.10.0",
"version": "0.11.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dawnline-web",
"version": "0.10.0",
"version": "0.11.0",
"license": "MIT",
"dependencies": {
"qrcode-generator": "1.4.4"
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "dawnline-web",
"version": "0.10.0",
"version": "0.11.0",
"private": true,
"license": "MIT",
"type": "module",
@@ -12,7 +12,9 @@
"test": "vitest run",
"format": "prettier --write .",
"format:check": "prettier --check .",
"ci": "npm run format:check && npm run typecheck && npm run test && npm run build"
"ci": "npm run format:check && npm run typecheck && 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"
+107 -91
View File
@@ -11,6 +11,7 @@ import { chipToggle, input } from './ui/controls';
import { firstBad, liveField } from './ui/layout';
import { circleNameHelp, ipv4Help, nameHelp, portsHelp } from './netcheck';
import { icon } from '../shared/icons';
import { fmt, plural } from '../shared/i18n';
type Service = Status['services'][number];
@@ -26,23 +27,23 @@ export const homeAccess = (p: Person) => p.access === 'both' || (p.access === 'l
/* ---------- Home services ---------- */
export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onSaved: () => unknown) {
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: 'NAS' });
const name = input(sv?.name ?? prefill.name ?? '', { placeholder: _('NAS') });
const addr = input(sv?.address ?? prefill.address ?? '', { placeholder: '192.168.1.10', class: 'cbi-input-text dl-mono' });
const ports = input((sv?.ports ?? prefill.ports ?? []).join(', '), {
placeholder: 'All ports, or e.g. 445, 5000',
placeholder: _('All ports, or e.g. 445, 5000'),
class: 'cbi-input-text dl-mono',
});
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown to people who may reach it.'));
const addrRow = liveField('Address', addr, () => ipv4Help(addr.value));
const portsRow = liveField('Ports', ports, () => portsHelp(ports.value));
const nameRow = liveField(_('Name', 'circle or service'), name, () => nameHelp(name.value, [], _('Shown to people who may reach it.')));
const addrRow = liveField(_('Address'), addr, () => ipv4Help(addr.value));
const portsRow = liveField(_('Ports'), ports, () => portsHelp(ports.value));
modal(
sv ? `Edit ${sv.name}` : 'Add service',
sv ? fmt(_('Edit %s'), sv.name) : _('Add service'),
[nameRow, addrRow, portsRow],
[
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
const bad = firstBad([nameRow, addrRow, portsRow]);
if (bad) {
@@ -50,7 +51,7 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
return;
}
const list = ports.value.split(/[ ,]+/).filter(Boolean);
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), _('Saved'))) {
closeModal();
onSaved();
}
@@ -61,41 +62,48 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
);
}
/** Port groups a device at home offers: what it announces over Bonjour, or the usual ones. */
const MDNS_LABEL: Record<string, string> = {
_smb: 'SMB',
_afpovertcp: 'AFP',
_http: 'Web',
_https: 'Web',
_ssh: 'SSH',
_sftp: 'SFTP',
'_sftp-ssh': 'SFTP',
_ipp: 'Printer',
_ipps: 'Printer',
_printer: 'Printer',
'_pdl-datastream': 'Printer',
_airplay: 'AirPlay',
_raop: 'AirPlay',
_rfb: 'Screen sharing',
_googlecast: 'Cast',
_hap: 'HomeKit',
_rdp: 'Remote desktop',
_ftp: 'FTP',
};
const DEFAULT_PORTS: [string, string[]][] = [
['Web', ['80', '443']],
['SMB', ['445']],
['SSH', ['22']],
];
/** The port group a Bonjour service type belongs to, by its name. */
function mdnsLabels(): Record<string, string> {
const web = _('Web');
const printer = _('Printer');
return {
_smb: 'SMB',
_afpovertcp: 'AFP',
_http: web,
_https: web,
_ssh: 'SSH',
_sftp: 'SFTP',
'_sftp-ssh': 'SFTP',
_ipp: printer,
_ipps: printer,
_printer: printer,
'_pdl-datastream': printer,
_airplay: 'AirPlay',
_raop: 'AirPlay',
_rfb: _('Screen sharing'),
_googlecast: 'Cast',
_hap: 'HomeKit',
_rdp: _('Remote desktop'),
_ftp: 'FTP',
};
}
/** Port groups a device at home offers: what it announces over Bonjour, or the usual ones. */
function portGroups(h: HomeHost): [string, string[]][] {
const labels = mdnsLabels();
const by = new Map<string, Set<string>>();
for (const s of h.services) {
const label = MDNS_LABEL[s.type.split('.')[0]];
const label = labels[s.type.split('.')[0]];
if (!label || !s.port) continue;
(by.get(label) ?? by.set(label, new Set()).get(label)!).add(String(s.port));
}
return by.size ? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)]) : DEFAULT_PORTS;
return by.size
? [...by].map(([l, p]) => [l, [...p].sort((a, b) => +a - +b)])
: [
[_('Web'), ['80', '443']],
['SMB', ['445']],
['SSH', ['22']],
];
}
/** Home services as a live part of Server → Access: `update` repaints it from a new status. */
@@ -118,7 +126,7 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
/** Devices with a change on its way: a second click would add the service twice. */
const busy = new Set<string>();
const list = E('div', { class: 'dl-list' });
const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, 'Looking for devices at home…'));
const picker = E('div', { class: 'dl-stack gap8' }, E('span', { class: 'dl-sub' }, _('Looking for devices at home…')));
const paintRows = () => {
const services = st.services;
@@ -133,25 +141,30 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
E(
'span',
{ class: 'dl-mono dl-faint' },
`${sv.address}${sv.ports.length ? ` · ports ${sv.ports.join(', ')}` : ' · all ports'}`,
`${sv.address} · ${sv.ports.length ? fmt(_('ports %s'), sv.ports.join(', ')) : _('all ports')}`,
),
]),
button('Edit', () => serviceDialog(sv, {}, reload)),
button(_('Edit'), () => serviceDialog(sv, {}, reload)),
button(
[icon('trash')],
async () => {
if (
(await confirmDialog(`Remove ${sv.name}?`, 'People limited to this service lose access to it.', 'Remove', true)) &&
(await attempt(() => api.serviceDelete(sv.id), 'Removed'))
(await confirmDialog(
fmt(_('Remove %s?'), sv.name),
_('People limited to this service lose access to it.'),
_('Remove'),
true,
)) &&
(await attempt(() => api.serviceDelete(sv.id), _('Removed')))
)
await reload();
},
'neutral',
{ title: 'Remove', 'aria-label': `Remove ${sv.name}` },
{ title: _('Remove'), 'aria-label': fmt(_('Remove %s'), sv.name) },
),
]),
)
: [E('div', { class: 'dl-row dl-muted' }, 'No services yet: pick ports of a device below.')],
: [E('div', { class: 'dl-row dl-muted' }, _('No services yet: pick ports of a device below.'))],
);
};
@@ -164,10 +177,10 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
const sv = st.services.find((s) => s.address === h.address);
const ok =
ports === null
? sv && (await attempt(() => api.serviceDelete(sv.id), `${sv.name} removed`))
? sv && (await attempt(() => api.serviceDelete(sv.id), fmt(_('%s removed'), sv.name)))
: await attempt(
() => api.serviceSet(sv?.id ?? '', sv?.name ?? (h.name || h.address), h.address, ports),
sv ? `${sv.name} updated` : `${h.name || h.address} added`,
sv ? fmt(_('%s updated'), sv.name) : fmt(_('%s added'), h.name || h.address),
);
if (ok) await reload();
} finally {
@@ -187,7 +200,7 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
icon(h.services.some((s) => s.type.startsWith('_ipp') || s.type.startsWith('_printer')) ? 'file' : 'computer'),
E('span', { class: 'dl-row-main dl-stack' }, [E('b', {}, h.name || h.address), E('span', { class: 'dl-mono dl-faint' }, h.address)]),
E('div', { class: 'dl-chips-row dl-host-ports' }, [
chip('All ports', all, () => choose(h, all ? null : [])),
chip(_('All ports'), all, () => choose(h, all ? null : [])),
...portGroups(h).map(([label, ports]) => {
const on = !all && ports.every((p) => chosen.has(p));
return chip(`${label} ${ports.join(', ')}`, on, () => {
@@ -204,15 +217,15 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
}
function paintPicker() {
if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, "Couldn't read the devices at home."));
if (failed) return dom.content(picker, E('span', { class: 'dl-sub' }, _("Couldn't read the devices at home.")));
if (!hosts) return;
const r = hosts;
if (!r.hosts.length) return dom.content(picker, E('span', { class: 'dl-sub' }, 'No devices found in the home network right now.'));
if (!r.hosts.length) return dom.content(picker, E('span', { class: 'dl-sub' }, _('No devices found in the home network right now.')));
// Open while there are no services yet (that is where they come from), then as left.
const fold = E('details', { class: 'dl-params', open: (open ?? !st.services.length) ? '' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Add from devices at home'),
E('span', {}, _('Add from devices at home')),
E('span', { class: 'dl-pcount' }, String(r.hosts.length)),
]),
E('div', { class: 'dl-params-body' }, [
@@ -220,8 +233,8 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
'span',
{ class: 'dl-sub' },
r.mdns
? 'Ports they announce over Bonjour. Pick what to open, or all ports.'
: 'Devices that got an address from this router. Pick the ports to open, or all ports.',
? _('Ports they announce over Bonjour. Pick what to open, or all ports.')
: _('Devices that got an address from this router. Pick the ports to open, or all ports.'),
),
E('div', { class: 'dl-list' }, r.hosts.map(hostRow)),
]),
@@ -245,13 +258,13 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
const el = E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-iflead' }, [
E('div', { class: 'dl-iflead-row' }, [
E('b', {}, 'Home services'),
button([icon('plus'), ' Add service'], () => serviceDialog(null, {}, reload)),
E('b', {}, _('Home services')),
button([icon('plus'), ' ', _('Add service')], () => serviceDialog(null, {}, reload)),
]),
E(
'span',
{ class: 'dl-sub' },
'Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.',
_('Home-only people can be limited to these instead of whole networks (chosen on their page). Shared by all servers.'),
),
]),
list,
@@ -271,13 +284,13 @@ export function homeServices(initial: Status, serverId: string, reload: () => Pr
export function circleDialog(st: Status, serverId: string, ci: Circle | null, onDone: () => unknown) {
const used = new Set(st.circles.filter((c) => c.server === serverId).map((c) => c.color));
let color = ci?.color ?? CIRCLE_COLORS.findIndex((_, i) => !used.has(i));
let color = ci?.color ?? CIRCLE_COLORS.findIndex((_c, i) => !used.has(i));
if (color < 0) color = 0;
const name = input(ci?.name ?? '', { placeholder: 'Family' });
const name = input(ci?.name ?? '', { placeholder: _('Family') });
const people = st.people.filter((p) => p.server === serverId).sort((a, b) => a.name.localeCompare(b.name));
const members = new Set(people.filter((p) => ci && p.circle === ci.id).map((p) => p.id));
const swatches = E('div', { class: 'dl-swatches', role: 'radiogroup', 'aria-label': 'Colour' });
const swatches = E('div', { class: 'dl-swatches', role: 'radiogroup', 'aria-label': _('Colour') });
const paintSwatches = () =>
dom.content(
swatches,
@@ -288,7 +301,7 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
class: `dl-swatch${i === color ? ' on' : ''}`,
style: `--sw:${c}`,
'aria-checked': i === color ? 'true' : 'false',
'aria-label': `Colour ${i + 1}`,
'aria-label': fmt(_('Colour %s'), i + 1),
click: () => {
color = i;
paintSwatches();
@@ -309,38 +322,38 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
type: 'button',
class: `dl-chipbtn${members.has(p.id) ? ' on' : ''}`,
title: !homeAccess(p)
? `${p.name} has no home access: their devices aren't reachable anyway`
? fmt(_("%s has no home access: their devices aren't reachable anyway"), p.name)
: other
? `Now in ${other.name}`
? fmt(_('Now in %s'), other.name)
: '',
click: (ev: Event) => {
if (!members.delete(p.id)) members.add(p.id);
(ev.currentTarget as HTMLElement).classList.toggle('on', members.has(p.id));
},
},
[p.name, !homeAccess(p) ? E('b', {}, 'internet') : other ? E('b', {}, other.name) : ''],
[p.name, !homeAccess(p) ? E('b', {}, _('internet')) : other ? E('b', {}, other.name) : ''],
);
}),
);
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
const others = st.circles.filter((c) => c.server === serverId && c.id !== ci?.id).map((c) => c.name);
const nameRow = liveField('Name', name, () => circleNameHelp(name.value, others));
const nameRow = liveField(_('Name', 'circle or service'), name, () => circleNameHelp(name.value, others));
modal(
ci ? `Edit ${ci.name}` : 'New circle',
ci ? fmt(_('Edit %s'), ci.name) : _('New circle'),
[
nameRow,
field('Colour', swatches),
field('People', chips),
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
field(_('Colour'), swatches),
field(_('People'), chips),
E('p', { class: 'dl-sub' }, _('Devices of people in one circle reach each other. A person is in one circle at a time.')),
],
[
ci
? button(
'Delete',
_('Delete'),
async () => {
if (await attempt(() => api.circleDelete(ci.id), `${ci.name} deleted`)) {
if (await attempt(() => api.circleDelete(ci.id), fmt(_('%s deleted'), ci.name))) {
closeModal();
onDone();
}
@@ -352,14 +365,14 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), _('Saved'))) {
closeModal();
onDone();
}
@@ -379,8 +392,8 @@ export function circleChips(st: Status, serverId: string, onDone: () => unknown)
const who = st.people.filter((p) => p.circle === c.id).map((p) => p.name);
return E(
'button',
{ type: 'button', class: 'dl-chip', title: `Edit ${c.name}`, click: () => circleDialog(st, serverId, c, onDone) },
[circleDot(c), E('b', {}, c.name), E('span', { class: 'dl-faint' }, who.length ? who.join(', ') : 'nobody yet')],
{ type: 'button', class: 'dl-chip', title: fmt(_('Edit %s'), c.name), click: () => circleDialog(st, serverId, c, onDone) },
[circleDot(c), E('b', {}, c.name), E('span', { class: 'dl-faint' }, who.length ? who.join(', ') : _('nobody yet'))],
);
}),
E(
@@ -388,8 +401,8 @@ export function circleChips(st: Status, serverId: string, onDone: () => unknown)
{
type: 'button',
class: 'dl-chip add',
title: 'New circle',
'aria-label': 'New circle',
title: _('New circle'),
'aria-label': _('New circle'),
click: () => circleDialog(st, serverId, null, onDone),
},
icon('plus'),
@@ -406,22 +419,23 @@ export function whoReaches(st: Status, srv: Server): HTMLElement {
const home = (list: Person[]) => {
const kinds = new Set(list.map((p) => (p.access === 'lan' && p.services?.length ? 'services' : p.home_nets?.length ? 'some' : 'all')));
if (!kinds.size) kinds.add('all');
return yes([...kinds].map((k) => ({ all: 'all networks', some: 'their networks', services: 'services' })[k]).join(' / '));
const label = { all: _('all networks'), some: _('their networks'), services: _('services') };
return yes([...kinds].map((k) => label[k]).join(' / '));
};
const each = () => (srv.mesh === 'off' ? no() : srv.mesh === 'circles' ? yes('circle') : yes());
const net = srv.lan_like ? 'like home' : 'direct';
const each = () => (srv.mesh === 'off' ? no() : srv.mesh === 'circles' ? yes(_('circle')) : yes());
const net = srv.lan_like ? _('like home') : _('direct');
const row = (label: string, list: Person[], cells: Node[]) =>
E('tr', {}, [
E('td', {}, [E('b', {}, label), E('div', { class: 'dl-sub' }, `${list.length} ${list.length === 1 ? 'person' : 'people'}`)]),
E('td', {}, [E('b', {}, label), E('div', { class: 'dl-sub' }, plural(list.length, '%s person', '%s people'))]),
...cells.map((c) => E('td', {}, c)),
]);
const by = (a: string) => people.filter((p) => p.access === a);
return E('section', { class: 'dl-setsec' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Who reaches what'),
E('h3', {}, _('Who reaches what')),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'From the rules on this server'),
E('span', { class: 'dl-sub' }, _('From the rules on this server')),
]),
E(
'div',
@@ -430,17 +444,19 @@ export function whoReaches(st: Status, srv: Server): HTMLElement {
E(
'tr',
{},
['', 'Internet', 'Home', 'This router', 'Each other'].map((t) => E('th', {}, t)),
['', _('Internet'), _('Home'), _('This router'), _('Each other')].map((t) => E('th', {}, t)),
),
row('Internet', by('internet'), [yes(net), no(), E('span', { class: 'dl-faint' }, 'DNS'), no()]),
row('Home', by('lan'), [E('span', { class: 'dl-faint' }, 'their own'), home(by('lan')), yes(), each()]),
row('Both', by('both'), [yes(net), home(by('both')), yes(), each()]),
row(_('Internet'), by('internet'), [yes(net), no(), E('span', { class: 'dl-faint' }, 'DNS'), no()]),
row(_('Home'), by('lan'), [E('span', { class: 'dl-faint' }, _('their own')), home(by('lan')), yes(), each()]),
row(_('Both'), by('both'), [yes(net), home(by('both')), yes(), each()]),
]),
),
E(
'p',
{ class: 'dl-sub' },
'Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.',
_(
'Home devices reach the devices of people with home access, on the networks those people reach. Paused, ended and over-the-limit people reach nothing.',
),
),
]),
]);
@@ -458,7 +474,7 @@ export function checkAccess(st: Status, srv: Server): HTMLElement {
const end = (placeholder: string, initial: string) => {
const sel = E('select', { class: 'cbi-input-select', 'aria-label': placeholder }, [
...devs.map((d) => E('option', { value: d.id, selected: d.id === initial ? 'selected' : null }, d.label)),
E('option', { value: ADDR, selected: initial === ADDR ? 'selected' : null }, 'Address'),
E('option', { value: ADDR, selected: initial === ADDR ? 'selected' : null }, _('Address')),
]) as HTMLSelectElement;
const addr = input('', { placeholder, class: 'cbi-input-text dl-mono' });
const wrap = E('div', { class: 'dl-check-end' }, [sel, addr]);
@@ -476,8 +492,8 @@ export function checkAccess(st: Status, srv: Server): HTMLElement {
const stop = r.steps.findIndex((s) => !s.ok);
dom.content(out, [
E('div', { class: `dl-verdict ${r.ok ? 'ok' : 'bad'}` }, [
E('b', {}, r.ok ? 'Allowed' : 'Blocked'),
E('span', { class: 'dl-sub' }, r.ok ? 'Every step lets it through' : `Stops at step ${stop + 1} of ${r.steps.length}`),
E('b', {}, r.ok ? _('Allowed') : _('Blocked')),
E('span', { class: 'dl-sub' }, r.ok ? _('Every step lets it through') : fmt(_('Stops at step %s of %s'), stop + 1, r.steps.length)),
]),
E(
'ul',
@@ -497,11 +513,11 @@ export function checkAccess(st: Status, srv: Server): HTMLElement {
return E('section', { class: 'dl-setsec' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Check access'),
E('h3', {}, _('Check access')),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'Why something does or does not connect'),
E('span', { class: 'dl-sub' }, _('Why something does or does not connect')),
]),
E('div', { class: 'dl-check-form' }, [from.el, E('span', { class: 'dl-faint' }, '→'), to.el, button('Check', run)]),
E('div', { class: 'dl-check-form' }, [from.el, E('span', { class: 'dl-faint' }, '→'), to.el, button(_('Check'), run)]),
out,
]),
]);
+9 -2
View File
@@ -5,6 +5,7 @@
import type { Network, PortHold } from './netcheck';
import type { AwgCaps, AwgState, Circle, ClientConfig, DayUsage, HealthCheck, LogEvent, MeshMode, Person, Status } from '../shared/types';
import { notify } from './ui/toast';
import { lang } from '../shared/i18n';
/** Throw a backend failure; show a warning the answer carries. */
function settle<T>(r: any): T {
@@ -15,9 +16,13 @@ function settle<T>(r: any): T {
return r as T;
}
/**
* A method of luci.dawnline. The page's language goes last, after the
* method's own arguments: the router writes its messages in it.
*/
function call<T>(method: string, params: string[] = []) {
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params });
return async (...args: unknown[]): Promise<T> => settle<T>(await fn(...args));
const fn = rpc.declare<any>({ object: 'luci.dawnline', method, params: [...params, 'lang'] });
return async (...args: unknown[]): Promise<T> => settle<T>(await fn(...params.map((_p, i) => args[i]), lang()));
}
export interface SetupDefaults {
@@ -129,6 +134,8 @@ export interface UpdatesStatus {
history: UpdateEvent[];
/** AmneziaWG interfaces (their Dawnline names): switching builds restarts them. */
tunnels: string[];
/** The admin's translations installed (luci-i18n-dawnline-<lang>): "ru". */
translations?: string[];
}
export interface UpdateEvent {
+129 -80
View File
@@ -16,6 +16,7 @@ import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck';
import { vpnKey } from '../../shared/vpnkey';
import { icon } from '../../shared/icons';
import { methodInfo, methodPicker, type Method, defaultMethod, legacyTitle } from '../disguise';
import { fmt, fill, num, plural } from '../../shared/i18n';
import { coreHead, type Core, type CoreCtx } from './common';
/** `.conf` names of the disguise parameters, in file order. */
@@ -73,31 +74,38 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
};
const jc = Number(o.jc || 0);
const signature = (o.i1 ?? '').includes('0x8580')
? 'A first packet shaped like a DNS answer.'
: 'Extra packets sent before the handshake.';
? _('A first packet shaped like a DNS answer.')
: _('Extra packets sent before the handshake.');
const conf = keys.map(([k, n]) => `${n} = ${o[k]}`).join('\n');
const body = E('div', { class: 'dl-pgrid' }, [
group(
'Junk packets',
_('Junk packets'),
'zap',
jc ? `${jc} random packet${jc === 1 ? '' : 's'} of ${o.jmin}–${o.jmax} bytes before each handshake.` : 'No junk packets.',
jc
? fmt(
N_(jc, '%s random packet of %s–%s bytes before each handshake.', '%s random packets of %s–%s bytes before each handshake.'),
num(jc),
o.jmin,
o.jmax,
)
: _('No junk packets.'),
['jc', 'jmin', 'jmax'],
),
group('Padding', 'archive', 'Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.', [
's1',
's2',
's3',
's4',
]),
group('Packet types', 'key', 'The values that replace WireGuard’s recognisable message types.', ['h1', 'h2', 'h3', 'h4']),
group('Signatures', 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']),
group('Protection', 'lock', 'AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.', [
group(
_('Padding'),
'archive',
_('Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.'),
['s1', 's2', 's3', 's4'],
),
group(_('Packet types'), 'key', _('The values that replace WireGuard’s recognisable message types.'), ['h1', 'h2', 'h3', 'h4']),
group(_('Signatures'), 'globe', signature, ['i1', 'i2', 'i3', 'i4', 'i5']),
group(_('Protection'), 'lock', _('AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.'), [
'header_protection_key',
'content_padding_addition',
'random_trailers',
'disable_cookies',
]),
group('Timing', 'clock', 'Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.', [
group(_('Timing'), 'clock', _('Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.'), [
'rekey_after_time',
'rekey_timeout',
'reject_after_time',
@@ -108,7 +116,7 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
return E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Current parameters'),
E('span', {}, _('Current parameters')),
E('span', { class: 'dl-pcount' }, String(keys.length)),
E('span', { class: 'dl-spacer' }),
E(
@@ -118,10 +126,10 @@ function paramsView(o: Record<string, string>): HTMLElement | null {
class: 'dl-linkbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(conf, 'Parameters copied');
copyText(conf, _('Parameters copied'));
},
},
'Copy as config',
_('Copy as config'),
),
]),
body,
@@ -158,11 +166,11 @@ function fileCard(cfg: AwgConfig): HTMLElement {
click: (ev: Event) => {
ev.preventDefault();
reveal = !reveal;
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? 'Hide key' : 'Show key']);
dom.content(eye, [icon(reveal ? 'x' : 'key'), reveal ? _('Hide key') : _('Show key')]);
paint();
},
},
[icon('key'), 'Show key'],
[icon('key'), _('Show key')],
);
paint();
const size = new Blob([cfg.conf]).size;
@@ -171,14 +179,14 @@ function fileCard(cfg: AwgConfig): HTMLElement {
E('span', { class: 'dl-filecard-ic' }, '.conf'),
E('span', { class: 'dl-stack' }, [
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes`),
E('span', { class: 'dl-sub' }, `AmneziaWG · ${plural(size, '%s byte', '%s bytes')}`),
]),
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
button([icon('download'), ' ', _('Download')], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Configuration'),
E('span', {}, _('Configuration')),
E('span', { class: 'dl-spacer' }),
eye,
E(
@@ -188,10 +196,10 @@ function fileCard(cfg: AwgConfig): HTMLElement {
class: 'dl-chipbtn',
click: (ev: Event) => {
ev.preventDefault();
copyText(cfg.conf, 'Configuration copied');
copyText(cfg.conf, _('Configuration copied'));
},
},
[icon('copy'), 'Copy'],
[icon('copy'), _('Copy')],
),
]),
pre,
@@ -212,7 +220,7 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
return E(
'div',
{ class: 'dl-hint' },
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
_('This device generated its own keys in the browser, so its full configuration only exists on that device.'),
);
const key = await vpnKey(cfg, cfg.server);
const panes: Record<string, () => Node> = {
@@ -222,13 +230,20 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
E(
'span',
{ class: 'dl-sub' },
plainWg(cfg) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
plainWg(cfg)
? _('Scan with AmneziaVPN or any WireGuard app on the device.')
: _('Scan with AmneziaVPN or AmneziaWG on the device.'),
),
]),
key: () =>
E('div', { class: 'dl-stack gap8' }, [
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button('Copy', () => copyText(key, 'Key copied'))]),
E('span', { class: 'dl-sub' }, 'AmneziaVPN → Add server → Insert key. Keep it private.'),
E('div', { class: 'dl-linkbox' }, [E('span', { class: 'dl-mono' }, key), button(_('Copy'), () => copyText(key, _('Key copied')))]),
// The app's own labels (portal/setup.ts has where they come from): + in its bottom bar, Insert, Continue.
E(
'span',
{ class: 'dl-sub' },
fmt(_('AmneziaVPN → %s. Keep it private.'), ['+', _('Insert', 'AmneziaVPN app'), _('Continue', 'AmneziaVPN app')].join(' → ')),
),
]),
file: () => fileCard(cfg),
};
@@ -239,9 +254,9 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
dom.content(body, panes[id]());
};
for (const [id, label] of [
['file', 'File'],
['key', 'Key'],
['qr', 'QR code'],
['file', _('File')],
['key', _('Key')],
['qr', _('QR code')],
])
seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label));
show(initial);
@@ -254,14 +269,24 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
const people = ctx.st.people.filter((p) => p.server === srv.id);
const devices = people.reduce((n, p) => n + p.devices.length, 0);
const ok = await confirmDialog(
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
`${devices} AmneziaWG device${devices === 1 ? ' stops' : 's stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : m === 'balanced' ? ' They need an app with AmneziaWG 2.0 or newer.' : ''}${ctx.st.servers.length === 1 && devices ? ' To keep the old disguise for some people, add a second server and move them there.' : ''}`,
same ? 'Generate and apply' : 'Switch and apply',
same ? _('Generate new disguise values?') : fmt(_('Switch to %s?'), info.title),
[
plural(
devices,
'%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).',
),
m === 'max' ? _('They need an app with AmneziaWG 3.1.') : m === 'balanced' ? _('They need an app with AmneziaWG 2.0 or newer.') : '',
ctx.st.servers.length === 1 && devices ? _('To keep the old disguise for some people, add a second server and move them there.') : '',
]
.filter(Boolean)
.join(' '),
same ? _('Generate and apply') : _('Switch and apply'),
true,
);
if (!ok) return;
if (await attempt(() => api.serverObfuscation(srv.id, m), same ? 'New values applied' : `${info.title} applied`)) {
notify('Devices are marked “Update config” until they import again.', 'info', 6000);
if (await attempt(() => api.serverObfuscation(srv.id, m), same ? _('New values applied') : fmt(_('%s applied'), info.title))) {
notify(_('Devices are marked “Update config” until they import again.'), 'info', 6000);
await ctx.refresh();
}
}
@@ -271,7 +296,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
const st: Status = ctx.st;
const port = input(String(srv.port), { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const mtu = input(srv.mtu ? String(srv.mtu) : '', {
placeholder: 'Auto',
placeholder: _('Auto'),
inputmode: 'numeric',
class: 'cbi-input-text dl-w-port dl-mono',
});
@@ -280,17 +305,25 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
let selected: Method = current ?? defaultMethod(st.awg);
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
const label = () =>
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
dom.content(
apply,
selected === current ? [icon('reset'), ' ', _('Generate new values')] : [fmt(_('Switch to %s'), methodInfo(selected)!.title)],
);
label();
const tools = st.awg_state?.tools !== false;
// Who holds which port arrives once the card is built (netstat on the
// router); until then the port is only checked for its range.
let holds: PortHold[] = [];
const portRow = liveRow('UDP port', port, () =>
const portRow = liveRow(_('UDP port'), port, () =>
portHelp(
Number(port.value),
holds,
`Opened on the WAN firewall automatically.${Number(port.value) === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
[
_('Opened on the WAN firewall automatically.'),
Number(port.value) === 4500 ? _('4500 is IPsec’s port: most networks let it through.') : '',
]
.filter(Boolean)
.join(' '),
),
);
api
@@ -301,27 +334,30 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
})
.catch(() => {});
const mtuRow = liveRow('MTU', mtu, () => mtuHelp(mtu.value, srv.mtus));
const kaRow = liveRow('Keep-alive', ka, () => keepaliveHelp(ka.value));
const kaRow = liveRow(_('Keep-alive'), ka, () => keepaliveHelp(ka.value));
return card(
'',
[
coreHead('AmneziaWG', srv.ifname),
group('globe', 'Listening', 'Where devices reach this core from the internet', [portRow]),
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
group('globe', _('Listening'), _('Where devices reach this core from the internet'), [portRow]),
group('file', _('In every device configuration'), _('Changing these marks devices “Update config” until they import again'), [
mtuRow,
kaRow,
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
group('shield', _('Disguise'), _('So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard'), [
// A server from before 0.8 on the old junk-only disguise: it runs, but is no longer offered.
legacyTitle(srv.preset)
? callout('warn', [
E('b', {}, legacyTitle(srv.preset)!),
' is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ',
E('b', {}, 'Balanced'),
' or ',
E('b', {}, 'Maximum'),
': devices import their configuration again.',
])
? callout(
'warn',
fill(
_(
'%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.',
),
E('b', {}, legacyTitle(srv.preset)!),
E('b', {}, _('Balanced')),
E('b', {}, _('Maximum')),
),
)
: '',
methodPicker(
st.awg,
@@ -335,29 +371,31 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
),
// Only about an installed AmneziaWG: without one the server page says what to install.
tools && !st.awg.v3
? callout('info', [
'This router runs an older AmneziaWG. ',
E('b', {}, 'Maximum'),
' becomes available with kmod-amneziawg and amneziawg-tools 3.1.',
])
? callout(
'info',
fill(
_('This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1.'),
E('b', {}, _('Maximum')),
),
)
: '',
paramsView(srv.obf ?? {}) ?? '',
E('div', { class: 'dl-row-end' }, [
E('span', { class: 'dl-sub' }, 'Applies at once: every AmneziaWG device imports its configuration again.'),
E('span', { class: 'dl-sub' }, _('Applies at once: every AmneziaWG device imports its configuration again.')),
apply,
]),
]),
E('details', { class: 'dl-params' }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Tunnel'), E('span', { class: 'dl-pcount' }, '3')]),
E('summary', {}, [icon('chevron'), E('span', {}, _('Tunnel')), E('span', { class: 'dl-pcount' }, '3')]),
E('div', { class: 'dl-params-body' }, [
row('Interface', E('span', { class: 'dl-mono' }, `${srv.ifname} · router ${srv.address}`)),
row('Tunnel subnet', E('span', { class: 'dl-mono' }, srv.subnet), 'Device addresses come from it.'),
row(_('Interface'), E('span', { class: 'dl-mono' }, `${srv.ifname} · ${fmt(_('router %s'), srv.address)}`)),
row(_('Tunnel subnet'), E('span', { class: 'dl-mono' }, srv.subnet), _('Device addresses come from it.')),
row(
'Server public key',
_('Server public key'),
E('span', { class: 'dl-keyrow' }, [
E('code', { class: 'dl-mono' }, srv.public_key),
button([icon('copy')], () => copyText(srv.public_key, 'Public key copied'), 'neutral', {
title: 'Copy',
button([icon('copy')], () => copyText(srv.public_key, _('Public key copied')), 'neutral', {
title: _('Copy'),
class: 'cbi-button cbi-button-neutral dl-icon-only sm',
}),
]),
@@ -366,9 +404,9 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
]),
],
[
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
E('span', { class: 'dl-sub' }, _('Port, MTU and keep-alive apply at once.')),
button(
'Save',
_('Save'),
() => {
// The help lines already say what is wrong: do not send it anyway.
const bad = firstBad([portRow, mtuRow, kaRow]);
@@ -376,7 +414,7 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
notify(bad, 'warning');
return;
}
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved');
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, _('AmneziaWG saved'));
},
'positive',
),
@@ -395,30 +433,30 @@ function overviewTile(srv: Server): HTMLElement {
[0, 1, 2, 3].map((i) => E('i', { class: i < n ? 'on' : '' })),
);
const chips: string[] = [];
if (+o.jc) chips.push(`${o.jc} junk · ${o.jmin}–${o.jmax} B`);
if (+o.jc) chips.push(`${plural(+o.jc, '%s junk', '%s junk')} · ${o.jmin}–${o.jmax} ${_('B')}`);
const pad = ['s1', 's2', 's3', 's4'].filter((k) => +o[k]).map((k) => `${k.toUpperCase()} ${o[k]}`);
if (pad.length) chips.push(pad.slice(0, 2).join(' · ') + (pad.length > 2 ? ` +${pad.length - 2}` : ''));
if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push('H1–H4 random');
if (o.i1) chips.push(/0x(8580|0100)0001/.test(o.i1) ? 'DNS-like first packets' : 'Signature packets');
if (o.header_protection_key) chips.push('Encrypted headers');
if (!chips.length) chips.push(m?.id === 'off' ? 'Plain WireGuard' : 'No values yet');
if (['h1', 'h2', 'h3', 'h4'].some((k) => o[k] && o[k] !== String(['h1', 'h2', 'h3', 'h4'].indexOf(k) + 1))) chips.push(_('H1–H4 random'));
if (o.i1) chips.push(/0x(8580|0100)0001/.test(o.i1) ? _('DNS-like first packets') : _('Signature packets'));
if (o.header_protection_key) chips.push(_('Encrypted headers'));
if (!chips.length) chips.push(m?.id === 'off' ? _('Plain WireGuard') : _('No values yet'));
return E('div', { class: 'dl-bento-tile dl-disg' }, [
E('div', { class: 'dl-bento-head' }, [
E('span', { class: 'dl-metric-label' }, 'Disguise'),
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, 'Change'),
E('span', { class: 'dl-metric-label' }, _('Disguise')),
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}&section=awg` }, _('Change')),
]),
E('div', { class: 'dl-disg-id' }, [
E('span', { class: `dl-disg-ic${m?.id === 'off' ? ' off' : ''}` }, icon(m?.ic ?? 'shield')),
E('span', { class: 'dl-stack' }, [
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')),
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? _('Custom', 'disguise'))),
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? _('Switch to Balanced or Maximum') : _('Set by hand')),
]),
]),
m
? E('div', { class: 'dl-disg-meters' }, [
E('span', {}, 'Stealth'),
E('span', {}, _('Stealth')),
segs(m.stealth, 'acc'),
E('span', {}, 'Speed'),
E('span', {}, _('Speed')),
segs(m.speed, 'ok'),
])
: '',
@@ -437,6 +475,17 @@ export const awg: Core = {
overviewTile,
connectBlock,
qrText: (cfg) => cfg.conf,
appKey: { label: 'Copy AmneziaVPN config', make: (cfg) => vpnKey(cfg, cfg.server) },
file: { label: 'Download AmneziaWG config', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) },
// Labels are getters: the text is made when a menu is drawn.
appKey: {
get label() {
return _('Copy AmneziaVPN config');
},
make: (cfg) => vpnKey(cfg, cfg.server),
},
file: {
get label() {
return _('Download AmneziaWG config');
},
make: (cfg) => ({ name: cfg.filename, text: cfg.conf }),
},
};
+130 -95
View File
@@ -15,7 +15,8 @@ import { liveField } from './ui/layout';
import { qrCode } from './ui/qr';
import { nameHelp } from './netcheck';
import { deviceStatus } from './ui/badges';
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
import { ago, bytes, isoDay, kindLabel, KINDS, todayOf } from '../shared/format';
import { fill, fmt, locale, num } from '../shared/i18n';
import { icon } from '../shared/icons';
import { eventBy } from './events/model';
import { spark } from './widgets/spark';
@@ -43,7 +44,7 @@ export interface DeviceOpts {
function when(ts: number): string {
return ts
? new Date(ts * 1000).toLocaleString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
? new Date(ts * 1000).toLocaleString(locale(), { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })
: '—';
}
@@ -52,7 +53,12 @@ function copyRow(label: string, value: string, mono = false): HTMLElement {
E('span', { class: 'dl-kvrow-k' }, label),
E(
'button',
{ type: 'button', class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`, title: 'Copy', click: () => copyText(value, `${label} copied`) },
{
type: 'button',
class: `dl-kvrow-v copy${mono ? ' dl-mono' : ''}`,
title: _('Copy'),
click: () => copyText(value, fmt(_('%s copied'), label)),
},
[E('span', {}, value), icon('copy')],
),
]);
@@ -62,46 +68,55 @@ function row(label: string, value: Node | string): HTMLElement {
return E('div', { class: 'dl-kvrow' }, [E('span', { class: 'dl-kvrow-k' }, label), E('span', { class: 'dl-kvrow-v' }, value)]);
}
const DEV_EVENT: Record<string, [string, string, string]> = {
connect: ['ok', 'Connected', 'plug'],
disconnect: ['', 'Went offline', 'plug'],
roam: ['', 'Changed network', 'network'],
device_added: ['ok', 'Added', 'plus'],
device_removed: ['', 'Removed', 'trash'],
device_keys: ['', 'New keys', 'reset'],
/** The device's own events: tone and icon (what they say is in eventText). */
const DEV_EVENT: Record<string, [string, string]> = {
connect: ['ok', 'plug'],
disconnect: ['', 'plug'],
roam: ['', 'network'],
device_added: ['ok', 'plus'],
device_removed: ['', 'trash'],
device_keys: ['', 'reset'],
};
/** What happened in the text colour, the details muted (as in the main log). */
function eventText(e: LogEvent): (string | HTMLElement)[] {
const m = (t: string) => E('span', { class: 'dl-muted' }, t);
const by = eventBy(e) === 'portal' ? _('on the portal') : eventBy(e) === 'admin' ? _('by you') : '';
switch (e.type) {
case 'connect':
return [...(e.detail ? fill(_('Connected from %s'), m(e.detail)) : [_('Connected')]), e.where ? m(` · ${e.where}`) : ''];
case 'disconnect':
return [_('Went offline')];
case 'roam':
return [_('Changed network'), m(` · ${e.detail ?? ''}`)];
case 'device_added':
return by ? fill(_('Added %s'), m(by)) : [_('Added')];
case 'device_removed':
return by ? fill(_('Removed %s'), m(by)) : [_('Removed')];
default: // device_keys
return by ? fill(_('New keys %s'), m(by)) : [_('New keys')];
}
}
/** Activity of one device, newest first. */
function deviceEvents(events: LogEvent[], id: string, now?: number): HTMLElement {
const mine = events
.filter((e) => e.device === id && DEV_EVENT[e.type])
.reverse()
.slice(0, 12);
if (!mine.length) return E('div', { class: 'dl-sub' }, 'No activity yet.');
if (!mine.length) return E('div', { class: 'dl-sub' }, _('No activity yet.'));
return E(
'div',
{ class: 'dl-dev-log' },
mine.map((e) => {
const [tone, label, ic] = DEV_EVENT[e.type];
// As in the main log: what happened in the text colour, the details muted.
const extra =
e.type === 'connect'
? [
e.detail ? E('span', { class: 'dl-muted' }, ` from ${e.detail}`) : '',
e.where ? E('span', { class: 'dl-muted' }, ` · ${e.where}`) : '',
]
: e.type === 'roam'
? [E('span', { class: 'dl-muted' }, ` · ${e.detail ?? ''}`)]
: e.type === 'device_added' || e.type === 'device_removed' || e.type === 'device_keys'
? [E('span', { class: 'dl-muted' }, eventBy(e) === 'portal' ? ' on the portal' : eventBy(e) === 'admin' ? ' by you' : '')]
: [];
const [tone, ic] = DEV_EVENT[e.type];
const t = new Date(e.ts * 1000);
return E('div', { class: `dl-dev-log-row${eventBy(e) === 'admin' ? ' dl-ev-by-admin' : ''}` }, [
eventBy(e) === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
? E('span', { class: 'dl-ev-tile', title: _('Done by you in LuCI') }, icon('admin'))
: E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, [E('span', {}, label), ...extra]),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString() }, ago(e.ts, now)),
E('span', { class: 'dl-row-main' }, eventText(e)),
E('span', { class: 'dl-faint dl-nowrap', title: t.toLocaleString(locale()) }, ago(e.ts, now)),
]);
}),
);
@@ -131,7 +146,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const titleEl = E('div', { class: 'dl-drawer-title' });
const stats = E('div', {});
const details = E('div', {});
const log = E('div', {}, E('div', { class: 'dl-sub' }, 'Loading…'));
const log = E('div', {}, E('div', { class: 'dl-sub' }, _('Loading…')));
let logEvents: LogEvent[] = [];
const showLog = (events: LogEvent[]) => {
logEvents = events.filter((e) => e.device === d.id);
@@ -157,9 +172,9 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
E('div', { class: 'dl-stack' }, [
E('div', { class: 'dl-title-row' }, [
E('h3', {}, d.name),
button([icon('edit')], () => rename(), 'neutral', { title: 'Rename', class: 'cbi-button cbi-button-neutral dl-icon-only sm' }),
button([icon('edit')], () => rename(), 'neutral', { title: _('Rename'), class: 'cbi-button cbi-button-neutral dl-icon-only sm' }),
]),
E('span', { class: 'dl-sub' }, `${p.name} · ${KIND_LABEL[d.kind]}`),
E('span', { class: 'dl-sub' }, `${p.name} · ${kindLabel(d.kind)}`),
]),
]);
const week = d.spark.reduce((a, b) => a + b, 0);
@@ -167,16 +182,16 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
stats,
E('div', { class: 'dl-dstats' }, [
E('div', { class: 'dl-dstats-cell wide' }, [
E('span', { class: 'dl-metric-label' }, 'Status'),
deviceStatus(d, now, 'Waiting for the first connection', p),
E('span', { class: 'dl-metric-label' }, _('Status')),
deviceStatus(d, now, _('Waiting for the first connection'), p),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'This month'),
E('span', { class: 'dl-metric-label' }, _('This month')),
E('b', {}, bytes(d.month[0] + d.month[1])),
E('span', { class: 'dl-sub dl-mono' }, `↓ ${bytes(d.month[1])} ↑ ${bytes(d.month[0])}`),
]),
E('div', { class: 'dl-dstats-cell' }, [
E('span', { class: 'dl-metric-label' }, 'Last 7 days'),
E('span', { class: 'dl-metric-label' }, _('Last 7 days')),
E('b', {}, bytes(week)),
spark(d.spark, 120, 22, today),
]),
@@ -185,13 +200,13 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
dom.content(
details,
E('div', { class: 'dl-kv2' }, [
copyRow('Tunnel address', d.address),
d.hostname && p.access !== 'internet' ? copyRow('Local address', d.hostname) : '',
copyRow(_('Tunnel address'), d.address),
d.hostname && p.access !== 'internet' ? copyRow(_('Local address'), d.hostname) : '',
// Where it connects from is under Locations (with the place and network); from home
// (not on the map) or without locations, here.
d.endpoint && !geo?.points.some((x) => x.device === d.id && x.ip === d.endpoint) ? row('Client IP', d.endpoint) : '',
d.endpoint && !geo?.points.some((x) => x.device === d.id && x.ip === d.endpoint) ? row(_('Client IP'), d.endpoint) : '',
row(
'Total',
_('Total'),
E('span', { class: 'dl-kv-act' }, [
`↓ ${bytes(d.total[1])} · ↑ ${bytes(d.total[0])}`,
E(
@@ -201,36 +216,36 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('device', d.id, d.name, () => setTimeout(changed, 300)),
},
'Reset',
_('Reset'),
),
]),
),
row('Added', `${when(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
row(_('Added'), `${when(d.created)} · ${d.created_by === 'portal' ? _('from the portal') : _('by you')}`),
// The whole key, copyable: it is what another WireGuard server needs to add this device by hand.
cfg.amnezia.client_pub_key ? copyRow('Public key', cfg.amnezia.client_pub_key) : row('Public key', '—'),
cfg.amnezia.client_pub_key ? copyRow(_('Public key'), cfg.amnezia.client_pub_key) : row(_('Public key'), '—'),
]),
);
dom.content(foot, [
button(
[icon(d.disabled ? 'play' : 'pause'), d.disabled ? ' Enable' : ' Disable'],
[icon(d.disabled ? 'play' : 'pause'), ' ', d.disabled ? _('Enable') : _('Disable')],
async () => {
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled'))
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? _('Device enabled') : _('Device disabled')))
await changed();
},
'neutral',
d.disabled ? {} : { class: 'cbi-button cbi-button-neutral dl-btn-warn' },
),
button([icon('key'), ' New keys'], async () => {
button([icon('key'), ' ', _('New keys')], async () => {
if (
!(await confirmDialog(
'Generate new keys?',
'The current configuration on this device stops working until it is imported again.',
'Generate',
_('Generate new keys?'),
_('The current configuration on this device stops working until it is imported again.'),
_('Generate'),
true,
))
)
return;
const c = await attempt(() => api.deviceRotate(d.id), 'New keys generated');
const c = await attempt(() => api.deviceRotate(d.id), _('New keys generated'));
if (c) {
o.refresh();
handle.close();
@@ -239,18 +254,18 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
}),
E('span', { class: 'dl-spacer' }),
button(
[icon('trash'), ' Remove'],
[icon('trash'), ' ', _('Remove')],
async () => {
if (
!(await confirmDialog(
`Remove ${d.name}?`,
'The device is disconnected immediately and its configuration stops working.',
'Remove',
fmt(_('Remove %s?'), d.name),
_('The device is disconnected immediately and its configuration stops working.'),
_('Remove'),
true,
))
)
return;
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) {
if (await attempt(() => api.deviceDelete(d.id), _('Device removed'))) {
handle.close();
o.refresh();
}
@@ -283,22 +298,22 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const rename = () => {
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
const nameRow = liveField('Name', input, () => nameHelp(input.value, taken, 'Shown in the portal and in the app.'));
const nameRow = liveField(_('Name'), input, () => nameHelp(input.value, taken, _('Shown in the portal and in the app.')));
modal(
`Rename ${d.name}`,
fmt(_('Rename %s'), d.name),
[nameRow],
[
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
const h = nameRow.help();
if (h.bad) {
notify(h.text, 'warning');
return;
}
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), _('Renamed'))) {
closeModal();
await changed();
}
@@ -313,14 +328,16 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
const foot = E('div', { class: 'dl-drawer-actions' });
const connectSec = E('section', { class: 'dl-dsec' }, [
// Whether it is connected (or still waiting) is in Status above.
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, 'Connect')]),
E('div', { class: 'dl-dsec-head' }, [E('h4', {}, _('Connect', 'section'))]),
d.config_stale
? E('div', { class: 'dl-note warn' }, [
icon('alert'),
E(
'span',
{},
'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.',
_(
'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.',
),
),
])
: '',
@@ -328,28 +345,35 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
]);
const activitySec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Activity'),
E('h4', {}, _('Activity')),
E('div', { class: 'dl-dsec-actions' }, [
E('button', { type: 'button', class: 'dl-linkbtn', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) }, 'Export'),
E(
'button',
{ type: 'button', class: 'dl-linkbtn', click: () => exportEvents({ people: [p] }, logEvents, 'csv', d.id) },
_('Export'),
),
E(
'button',
{
type: 'button',
class: 'dl-linkbtn danger',
click: () =>
clearLogDialog(`Clear ${d.name}'s activity`, `Removes events about ${d.name}.`, { device: d.id }, () => {
clearLogDialog(fmt(_("Clear %s's activity"), d.name), fmt(_('Removes events about %s.'), d.name), { device: d.id }, () => {
void loadLog(true);
o.refresh();
}),
},
'Clear',
_('Clear'),
),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All activity'),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, _('All activity')),
]),
]),
log,
]);
const detailsSec = E('section', { class: 'dl-dsec' }, [E('div', { class: 'dl-dsec-head' }, E('h4', {}, 'Details')), details]);
const detailsSec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, E('h4', {}, _('Details', 'section'))),
details,
]);
let locationsSec: HTMLElement | '' = '';
if (geo?.enabled) {
map = new ConnectionMap(
@@ -366,7 +390,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
}));
locationsSec = E('section', { class: 'dl-dsec' }, [
E('div', { class: 'dl-dsec-head' }, [
E('h4', {}, 'Locations'),
E('h4', {}, _('Locations')),
rangeControl(
range,
(r) => {
@@ -412,22 +436,24 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
const cfg = () => attempt(() => api.deviceConfig(d.id));
const items: (MenuItem | null)[] = [
{
label: 'Show QR code',
label: _('Show QR code'),
icon: icon('qr'),
run: async () => {
const c = await cfg();
if (!c) return;
modal(
`${d.name} · QR code`,
`${d.name} · ${_('QR code')}`,
E('div', { class: 'dl-qr-pane' }, [
qrCode(core.qrText(c)),
E(
'span',
{ class: 'dl-sub' },
plainWg(c) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
plainWg(c)
? _('Scan with AmneziaVPN or any WireGuard app on the device.')
: _('Scan with AmneziaVPN or AmneziaWG on the device.'),
),
]),
cancelButton('Close'),
cancelButton(_('Close')),
);
},
},
@@ -447,50 +473,50 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
icon: icon('copy'),
run: async () => {
const c = await cfg();
if (c) copyText(await core.appKey!.make(c), 'Key copied');
if (c) copyText(await core.appKey!.make(c), _('Key copied'));
},
}
: null,
null,
{ label: 'Rename', icon: icon('edit'), run: () => openDevice(p, d, o) },
{ label: _('Rename'), icon: icon('edit'), run: () => openDevice(p, d, o) },
{
label: 'New keys',
label: _('New keys'),
icon: icon('key'),
run: async () => {
if (
await confirmDialog(
'Generate new keys?',
'The current configuration on this device stops working until it is imported again.',
'Generate',
_('Generate new keys?'),
_('The current configuration on this device stops working until it is imported again.'),
_('Generate'),
true,
)
)
if (await attempt(() => api.deviceRotate(d.id), 'New keys generated')) o.refresh();
if (await attempt(() => api.deviceRotate(d.id), _('New keys generated'))) o.refresh();
},
},
{
label: d.disabled ? 'Enable' : 'Disable',
label: d.disabled ? _('Enable') : _('Disable'),
icon: icon(d.disabled ? 'play' : 'pause'),
warn: !d.disabled,
run: async () => {
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? 'Device enabled' : 'Device disabled'))
if (await attempt(() => api.deviceUpdate(d.id, undefined, !d.disabled), d.disabled ? _('Device enabled') : _('Device disabled')))
o.refresh();
},
},
{
label: 'Delete',
label: _('Delete'),
icon: icon('trash'),
danger: true,
run: async () => {
if (
await confirmDialog(
`Remove ${d.name}?`,
'The device is disconnected immediately and its configuration stops working.',
'Remove',
fmt(_('Remove %s?'), d.name),
_('The device is disconnected immediately and its configuration stops working.'),
_('Remove'),
true,
)
)
if (await attempt(() => api.deviceDelete(d.id), 'Device removed')) o.refresh();
if (await attempt(() => api.deviceDelete(d.id), _('Device removed'))) o.refresh();
},
},
];
@@ -502,7 +528,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
const taken = person.devices.map((x) => x.name);
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
const suggest = (k: Kind) => {
const base = KIND_LABEL[k];
const base = kindLabel(k);
let n = 1;
let name = base;
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
@@ -510,14 +536,14 @@ export function addDevice(person: Person, o: DeviceOpts) {
};
let kind: Kind = 'phone';
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
const nameRow = liveField('Name', nameInput, () =>
const nameRow = liveField(_('Name'), nameInput, () =>
nameInput.value.trim()
? nameHelp(nameInput.value, taken, 'Shown in the portal and in the app.')
: { text: `Named after its type: ${suggest(kind)}.`, bad: false },
? nameHelp(nameInput.value, taken, _('Shown in the portal and in the app.'))
: { text: fmt(_('Named after its type: %s.'), suggest(kind)), bad: false },
);
const kinds = E(
'div',
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': _('Type') },
KINDS.map((k) =>
E(
'button',
@@ -538,29 +564,38 @@ export function addDevice(person: Person, o: DeviceOpts) {
nameRow.refresh();
},
},
[icon(k), E('span', {}, KIND_LABEL[k])],
[icon(k), E('span', {}, kindLabel(k))],
),
),
);
const over = person.devices.length >= person.device_limit;
modal(
`Add a device for ${person.name}`,
fmt(_('Add a device for %s'), person.name),
[
over
? E(
'p',
{ class: 'dl-hint' },
`${person.name} already has ${person.devices.length} of ${person.device_limit} devices. As admin you can still add one.`,
fmt(
N_(
person.device_limit,
'%s already has %s of %s device. As admin you can still add one.',
'%s already has %s of %s devices. As admin you can still add one.',
),
person.name,
num(person.devices.length),
num(person.device_limit),
),
)
: '',
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Type'), kinds]),
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Type')), kinds]),
nameRow,
],
[
cancelButton(),
' ',
button(
'Add device',
_('Add device'),
async () => {
const h = nameRow.help();
if (h.bad) {
@@ -571,7 +606,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
if (!r) return;
closeModal();
notify(`${name} added`, 'success', 3000);
notify(fmt(_('%s added'), name), 'success', 3000);
o.refresh();
await reopen(person.id, r.id, o);
},
+58 -52
View File
@@ -3,6 +3,7 @@
import type { AwgCaps } from '../shared/types';
import { E } from './e';
import { icon } from '../shared/icons';
import { fmt } from '../shared/i18n';
export type Method = 'balanced' | 'max' | 'off';
/** The router features a method may need (the boolean ones of AwgCaps). */
@@ -24,42 +25,47 @@ export interface MethodInfo {
needs?: AwgNeed;
}
export const METHODS: MethodInfo[] = [
{
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',
},
];
/** The methods in picker order, in the page's language. */
export function methods(): MethodInfo[] {
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'),
},
];
}
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
export const methodInfo = (id: string): MethodInfo | undefined => methods().find((x) => x.id === id);
/** The disguise a new server gets: the strongest this router can run. */
export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.v2 ? 'balanced' : 'off');
@@ -70,21 +76,21 @@ export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.
* the picker offers Balanced or Maximum instead. The title for such a server, or null.
*/
export const legacyTitle = (preset: string): string | null =>
preset === 'standard' ? 'Standard (old)' : preset === 'strong' ? 'Strong (old)' : null;
preset === 'standard' ? _('Standard (old)') : preset === 'strong' ? _('Strong (old)') : null;
const NEEDS: Record<AwgNeed, string> = {
v2: 'Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).',
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
};
/** The same while no AmneziaWG is installed at all ("newer" would be misleading). */
const NEEDS_NONE: Record<AwgNeed, string> = {
v2: 'Needs AmneziaWG on the router.',
v3: 'Needs AmneziaWG 3.1 on the router: install it first.',
};
/**
* Why a method is not available. `installed` is false while no AmneziaWG is
* installed at all ("newer" would be misleading then).
*/
function needsText(need: AwgNeed, installed: boolean): string {
if (!installed) return need === 'v2' ? _('Needs AmneziaWG on the router.') : _('Needs AmneziaWG 3.1 on the router: install it first.');
return need === '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).');
}
function dots(n: number, label: string): HTMLElement {
return E('span', { class: 'dl-dots', title: `${label}: ${n} of 4` }, [
return E('span', { class: 'dl-dots', title: fmt(_('%s: %s of 4'), label, n) }, [
E('span', { class: 'dl-dots-label' }, label),
E(
'span',
@@ -106,11 +112,11 @@ export function methodPicker(
current?: string,
installed = true,
): HTMLElement {
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': 'Disguise method' });
const el = E('div', { class: 'dl-methods', role: 'radiogroup', 'aria-label': _('Disguise method') });
const paint = () =>
dom.content(
el,
METHODS.map((m) => {
methods().map((m) => {
const ok = !m.needs || caps[m.needs];
const on = m.id === selected;
return E(
@@ -132,16 +138,16 @@ export function methodPicker(
E('div', { class: 'dl-method-head' }, [
E('span', { class: 'dl-method-ic' }, icon(m.ic)),
E('b', {}, m.title),
m.id === current ? E('span', { class: 'dl-pill ok' }, 'Current') : '',
m.id === current ? E('span', { class: 'dl-pill ok' }, _('Current')) : '',
]),
E('p', {}, m.text),
E('div', { class: 'dl-method-meters' }, [dots(m.stealth, 'Stealth'), dots(m.speed, 'Speed')]),
E('div', { class: 'dl-method-meters' }, [dots(m.stealth, _('Stealth')), dots(m.speed, _('Speed'))]),
E(
'div',
{ class: 'dl-method-foot' },
ok
? [icon(m.id === 'off' ? 'wireguard' : 'amneziawg'), E('span', {}, m.apps)]
: [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
: [icon('alert'), E('span', {}, needsText(m.needs!, installed))],
),
],
);
+3 -2
View File
@@ -1,5 +1,6 @@
// CSV for the log export. Cells a spreadsheet would run as a formula (= + - @,
// tab, CR) get a leading apostrophe; quotes, commas and line breaks are quoted.
// The header row is the column keys unless the caller names them (translated).
export function csvCell(v: unknown): string {
let s = v == null ? '' : String(v);
@@ -7,6 +8,6 @@ export function csvCell(v: unknown): string {
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
export function toCsv<K extends string>(cols: readonly K[], rows: Record<K, unknown>[]): string {
return [cols.join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
export function toCsv<K extends string>(cols: readonly K[], rows: Record<K, unknown>[], head?: Record<K, string>): string {
return [cols.map((c) => csvCell(head?.[c] ?? c)).join(','), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(','))].join('\n');
}
+119
View File
@@ -0,0 +1,119 @@
// Generated by web/i18n/extract.ts from the backend's L_() strings (npm run i18n): do not edit.
// The words of service log lines, as written; events/model.ts matches log lines against them.
export const LOG_TEMPLATES: string[] = [
'%d system package',
'%d system packages',
'%s (after %d repair)',
'%s (after %d repairs)',
"%s - %d repairs didn't help",
'%s - %s',
"%s - not repaired again (%d repairs didn't help)",
'%s has no IPv4 address.',
'%s is not a bridge, so Dawnline cannot join the LAN as a device.',
'%s needs a manual switch in Components',
'%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.',
'%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.',
'%s · restored',
'Access rules',
'Activity',
'AmneziaWG is missing from the router',
'AmneziaWG is running again',
'AmneziaWG is running again · accepting connections on port %d',
"AmneziaWG isn't accepting connections on port %d",
"AmneziaWG isn't running",
'Backup',
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.',
'Choose another interface name in the server settings.',
'Components',
'Connections',
'DNS for Home-only devices',
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
'Firewall',
'Install it in Dawnline → Components.',
'Internet like a home device',
'MTU is now automatic',
'Missing: %s.',
'No LAN detected.',
'No free address on %s.',
'No free link-local range for the internal link.',
'No free routing table.',
'People',
'Personal links',
'Personal portal',
'Router',
'Servers',
'Speed',
'System packages',
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.',
'Traffic',
'Watchdog',
'a new build needs a manual switch in Components',
'answers again',
'are loaded again',
'are missing',
'automatic update failed',
'background check failed: %s',
"can't reach Dawnline (luci.dawnline is missing in rpcd)",
"can't use the network interface %s: it exists and isn't Dawnline's",
'certificate expires %s',
'certificate expires within 7 days',
'certificate renewed · valid until %s',
"couldn't be repaired: %s",
"couldn't be updated - the previous rules stay, and changes to access wait until they load",
"couldn't load - no device is loaded into the tunnels until they do",
"couldn't load devices into the tunnel",
"couldn't start",
"couldn't start · %d failed attempts in %d min",
'failed - internet goes out directly for now',
'failed: %s',
'has an invalid interface name "%s"',
'installed the %s build',
'installed the %s build · %s',
'is kept down',
'is kept down: its disguise needs AmneziaWG %s (installed: %s)',
'is kept down: its disguise needs AmneziaWG %s (installed: none)',
'is off',
'is on · traffic enters %s as %s',
'is ready again',
"isn't answering on port %d",
"isn't installed: no tunnel can run - install it in Dawnline → Components",
"isn't installed: tunnels were left as they are",
"isn't known to the network service - restart the network or reboot",
"isn't running",
"isn't running on this router (fw4): tunnels and the portal are closed",
"kernel module isn't installed: no tunnel can run - install it in Dawnline → Components",
"kernel module isn't loaded",
'loading it',
'loading them again',
'moved to word codes',
'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
'network changed - Dawnline set itself up again',
'nightly backup failed: %s',
'public address changed · %s → %s',
'reaches Dawnline again',
'reloading rpcd',
'restarted · version %s',
'restarting for the AmneziaWG update',
'restarting it',
'restoring them',
'rules for Dawnline are in place again',
"rules for Dawnline aren't loaded",
'rules for Dawnline were changed or removed',
'runs again',
'setting it up again',
'started',
'started with the router · version %s',
'started · accepting connections on port %s',
'started · version %s',
'stopped unexpectedly',
'stopped unexpectedly - started again',
'update failed',
'update to %s failed its check - rolled back to %s',
'updated automatically · %s',
'updated automatically · %s → %s',
'updated · %s',
'updated · %s → %s',
'updates available · %s',
'was broken - set up again (%s as %s)',
];
+204 -15
View File
@@ -3,6 +3,8 @@
import type { LogEvent } from '../../shared/types';
import type { LogCategory, LogsInfo, ServiceLogEntry } from '../api';
import { fmt, known, plural } from '../../shared/i18n';
import { LOG_TEMPLATES } from './log-templates';
/** Mirrors CATEGORY in dawnline.live. */
const CATEGORY: Record<string, LogCategory> = {
@@ -27,21 +29,24 @@ const CATEGORY: Record<string, LogCategory> = {
export const CATEGORIES: LogCategory[] = ['connections', 'people', 'problems'];
export const CATEGORY_LABEL: Record<LogCategory, string> = {
connections: 'Connections',
people: 'People',
problems: 'Problems',
};
export function categoryLabel(c: LogCategory): string {
return { connections: _('Connections'), people: _('People'), problems: _('Problems') }[c];
}
export const CATEGORY_HELP: Record<LogCategory, string> = {
connections: 'Connects, disconnects and IP changes',
people: 'People and their devices added, changed, paused, removed',
problems: 'Blocked portal sign-ins (tunnels and services are in the service log)',
};
export function categoryHelp(c: LogCategory): string {
return {
connections: _('Connects, disconnects and IP changes'),
people: _('People and their devices added, changed, paused, removed'),
problems: _('Blocked portal sign-ins (tunnels and services are in the service log)'),
}[c];
}
export const categoryOf = (type: string): LogCategory => CATEGORY[type] ?? 'problems';
export const SYSTEM_SOURCE: Record<ServiceLogEntry['src'], string> = { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: 'Portal' };
/** What a service log source is called; unknown ones by their id. */
export function sourceName(src: ServiceLogEntry['src']): string {
return { awg: 'AmneziaWG', dawnline: 'Dawnline', portal: _('Portal') }[src] ?? src;
}
const ADMIN_TYPES = ['person_added', 'person_removed', 'person_changed'];
@@ -65,10 +70,194 @@ export const isProblem = (x: LogItem) =>
x.sys ? ['error', 'repair', 'down'].includes(x.sys.level) : categoryOf(x.ev!.type) === 'problems';
export function retentionText(p: LogsInfo['policy']): string {
const age = p.keep_days > 0 ? `${p.keep_days} day${p.keep_days === 1 ? '' : 's'}` : 'no age limit';
const age = p.keep_days > 0 ? plural(p.keep_days, '%s day', '%s days') : _('no age limit');
const where =
p.persist === 'off'
? 'kept in memory only (lost on reboot)'
: `saved to flash ${p.persist === '10min' ? 'every 10 minutes' : 'hourly'}`;
return `Kept for ${age}, up to ${p.max.toLocaleString('en-GB')} events, ${where}.`;
? _('kept in memory only (lost on reboot)')
: p.persist === '10min'
? _('saved to flash every 10 minutes')
: _('saved to flash hourly');
return fmt(_('Kept for %s, %s, %s.'), age, plural(p.max, 'up to %s event', 'up to %s events'), where);
}
/* ---------- the router's words, put into the page's language ----------
* Events and service log lines are written once, in English, by whoever was
* running (the agent has no language) and read later in any language: the
* words below are their fixed vocabulary, translated when shown. Anything
* else stays as written. */
/** Why someone was paused or resumed (the agent's REASON words). */
export function reasonText(detail: string): string {
const t: Record<string, string> = {
'paused by admin': _('paused by admin'),
'end date reached': _('end date reached'),
'data limit reached': _('data limit reached'),
'outside allowed hours': _('outside allowed hours'),
'no server': _('no server'),
'server turned off': _('server turned off'),
};
return t[detail] ?? detail;
}
/** Days left in an "expiring" event's detail ("3 days"), or null. */
export function daysOf(detail: string): number | null {
const m = /^(\d+) days?$/.exec(detail);
return m ? Number(m[1]) : null;
}
/** The person's settings a person_changed event lists (option names, "moved to <server>"). */
export function changedText(detail: string): string {
const f: Record<string, string> = {
name: _('name'),
access: _('access'),
device_limit: _('device limit'),
expires: _('end date'),
expire_action: _('what happens at the end'),
expire_warn: _('warning before the end'),
quota_gb: _('data limit'),
quota_period: _('data limit period'),
bonus_gb: _('extra data'),
hours: _('allowed hours'),
dns_mode: _('DNS'),
paused: _('pause'),
services: _('home services'),
circle: _('circle', 'setting'),
home_nets: _('home networks'),
server: _('server'),
};
return detail
.split(', ')
.map((k) => {
const to = /^moved to (.+)$/.exec(k)?.[1];
return to ? fmt(_('moved to %s'), to) : (f[k] ?? k.replace(/_/g, ' '));
})
.join(', ');
}
/**
* The admin's own change in the service log ({ msg: 'changed', kind:
* 'server', who: 'Home' }), as one sentence: with %s for the name it names,
* or whole when the name is a fixed phrase ("the service log"); null for one
* this page does not know.
*/
export function adminSentence(msg: string, kind?: string | null, who?: string | null): { text: string; named: boolean } | null {
const fixed: Record<string, string> = {
'cleared|the service log': _('You cleared the service log'),
'cleared|the activity log': _('You cleared the activity log'),
'exported|all settings': _('You exported all settings'),
'imported|settings from a file': _('You imported settings from a file'),
'restored|from a file': _('You restored a backup from a file'),
'turned on|the personal portal': _('You turned on the personal portal'),
'turned off|the personal portal': _('You turned off the personal portal'),
'changed|the personal portal': _('You changed the personal portal'),
'turned on|the watchdog': _('You turned on the watchdog'),
'turned off|the watchdog': _('You turned off the watchdog'),
'reset traffic history|for everyone': _('You reset traffic history for everyone'),
};
const whole = fixed[`${msg}|${who ?? ''}`];
if (whole) return { text: whole, named: false };
const named: Record<string, string> = {
'created|server': _('You created server %s'),
'changed|server': _('You changed server %s'),
'removed|server': _('You removed server %s'),
'turned on|server': _('You turned on server %s'),
'turned off|server': _('You turned off server %s'),
'added|circle': _('You added circle %s'),
'changed|circle': _('You changed circle %s'),
'removed|circle': _('You removed circle %s'),
'restored|backup': _('You restored backup %s'),
};
const t = named[`${msg}|${kind ?? ''}`];
if (t) return { text: t, named: true };
// "reset traffic history" "for Anna": the name after "for".
const forWho = msg === 'reset traffic history' && /^for (.+)$/.exec(who ?? '')?.[1];
return forWho ? { text: _('You reset traffic history for %s'), named: true } : null;
}
/** The name in a sentence adminSentence() made with %s (its "for …" taken off). */
export const adminName = (msg: string, who: string) => (msg === 'reset traffic history' ? who.replace(/^for /, '') : who);
/** The note after an admin's change: its known pieces translated, the rest as written. */
export function noteText(note: string): string {
const one = (p: string): string => {
const t: Record<string, string> = {
'other addresses': _('other addresses'),
certificate: _('certificate'),
redirect: _('redirect'),
'devices kept apart': _('devices kept apart'),
'devices reach each other': _('devices reach each other'),
'devices reach each other in circles': _('devices reach each other in circles'),
'home network and internet path': _('home network and internet path'),
'the file holds private keys': _('the file holds private keys'),
'problems are only logged, nothing is repaired': _('problems are only logged, nothing is repaired'),
name: _('name'),
'public address': _('public address'),
'AmneziaWG port': _('AmneziaWG port'),
'tunnel network': _('tunnel network'),
connections: categoryLabel('connections'),
people: categoryLabel('people'),
problems: categoryLabel('problems'),
};
if (t[p]) return t[p];
let m: RegExpExecArray | null;
if ((m = /^port (\d+)$/.exec(p))) return fmt(_('port %s'), m[1]);
if ((m = /^address (.+)$/.exec(p))) return fmt(_('address %s'), m[1]);
if ((m = /^disguise: (.+)$/.exec(p))) return fmt(_('disguise: %s'), m[1]);
if ((m = /^(\d+) events?$/.exec(p))) return plural(Number(m[1]), '%s event', '%s events');
if ((m = /^older than (\d+) days$/.exec(p))) return plural(Number(m[1]), 'older than %s day', 'older than %s days');
if ((m = /^with (\d+) (person|people)$/.exec(p))) return plural(Number(m[1]), 'with %s person', 'with %s people');
if ((m = /^(\d+) entr(y|ies)( older than (\d+) days)?$/.exec(p)))
return m[4]
? `${plural(Number(m[1]), '%s entry', '%s entries')}, ${plural(Number(m[4]), 'older than %s day', 'older than %s days')}`
: plural(Number(m[1]), '%s entry', '%s entries');
return p;
};
return note
.split(' · ')
.map((part) => part.split(', ').map(one).join(', '))
.join(' · ');
}
/* ---------- the service log's lines ----------
* The router writes them in English from its L_() templates (the generated
* list in ./log-templates); a line is put into the page's language by the
* template it matches, its values (versions, ports, names, or another
* template's words) put back in place. Lines written before the plain dash
* have "—" where the templates have "-". */
let patterns: { t: string; re: RegExp }[] | null = null;
const LOG_EXACT = new Set(LOG_TEMPLATES);
/** The templates with values in them, the most specific (most fixed text) first. */
function logPatterns() {
return (patterns ??= LOG_TEMPLATES.filter((t) => /%[sd]/.test(t) && t.replace(/%[sd]/g, '').trim())
.map((t) => ({
t,
fixed: t.replace(/%[sd]/g, '').length,
re: new RegExp(
`^${t
.split(/(%[sd])/)
.map((p) => (p === '%s' ? '(.+?)' : p === '%d' ? '(\\d+)' : p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
.join('')}$`,
),
}))
.sort((a, b) => b.fixed - a.fixed));
}
/** A service log line (or its subject, or a line of its details) in the page's language; one it does not know as written. */
export function logText(line: string, depth = 0): string {
const s = line.replace(/ — /g, ' - ');
if (LOG_EXACT.has(s)) return known(s);
if (depth > 2) return line;
for (const p of logPatterns()) {
const m = p.re.exec(s);
if (m) return fmt(known(p.t), ...m.slice(1).map((v) => logText(v, depth + 1)));
}
// A list ("Dawnline 0.3.3, 2 system packages"): each item on its own.
return s.includes(', ')
? s
.split(', ')
.map((x) => logText(x, depth + 1))
.join(', ')
: line;
}
+132 -89
View File
@@ -1,12 +1,14 @@
// Log rows: an activity event as a sentence ("You added device Phone for
// Myata"), its tile and time, and a service log line.
// Myata", one translated sentence per event with the names in it), its tile
// and time, and a service log line (its text comes from the router).
import type { LogEvent, Status } from '../../shared/types';
import type { ServiceLogEntry } from '../api';
import { E } from '../e';
import { icon } from '../../shared/icons';
import { ago } from '../../shared/format';
import { SYSTEM_SOURCE, eventBy, plainDetail } from './model';
import { ago, fmtDay } from '../../shared/format';
import { fill, fmt, locale, num } from '../../shared/i18n';
import { adminName, adminSentence, changedText, daysOf, eventBy, logText, noteText, plainDetail, reasonText, sourceName } from './model';
/** What the people and servers in the log are called now. */
export type Names = Pick<Status, 'people' | 'servers'>;
@@ -49,6 +51,9 @@ function eventIcon(st: Names, e: LogEvent): string {
return EVENT_ICON[e.type] ?? 'activity';
}
/** A router day (YYYY-MM-DD) in the page's language; anything else as it came. */
const routerDay = (s: string) => (/^\d{4}-\d{2}-\d{2}$/.test(s) ? fmtDay(s) : s);
export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
const person = st.people.find((p) => p.id === e.person);
const who = person?.name ?? e.pname ?? e.person ?? '';
@@ -61,101 +66,97 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
e.hosts?.[ip]
? [E('span', { class: 'dl-ev-host' }, [E('b', {}, e.hosts[ip]), E('span', { class: 'dl-faint' }, ` (${ip})`)])]
: [mono(ip)];
// What the bold name is (a person, a device), said before it in grey.
const kind = (t: string) => E('span', { class: 'dl-ev-kind' }, `${t} `);
const wd = dev ? `${who} · ${dev}` : who;
const detail = plainDetail(e);
const devName = detail || dev || 'a device';
// A sentence in grey around its bold names, people and devices.
const say = (s: string, ...args: Node[]): Node[] => fill(s, ...args).map((x) => (typeof x === 'string' ? m(x) : x));
// The admin's own actions start with an accent "You".
const you = (verb: string) => [E('span', { class: 'dl-you' }, 'You'), m(` ${verb} `)];
if (eventBy(e) === 'admin')
const you = (s: string, ...args: Node[]): Node[] => {
const w = _('You');
return s.startsWith(`${w} `) ? [E('span', { class: 'dl-you' }, w), ...say(s.slice(w.length), ...args)] : say(s, ...args);
};
const wd = b(dev ? `${who} · ${dev}` : who);
const detail = plainDetail(e);
const devName = b(detail || dev || _('a device'));
const by = eventBy(e);
if (by === 'admin')
switch (e.type) {
case 'device_added':
return [...you('added'), kind('device'), b(devName), m(' for '), b(who)];
return you(_('You added device %s for %s'), devName, b(who));
case 'device_removed':
return [...you('removed'), kind('device'), b(devName), m(' from '), b(who)];
return you(_('You removed device %s from %s'), devName, b(who));
case 'paused':
return [...you('paused'), kind('person'), b(who)];
return you(_('You paused person %s'), b(who));
case 'resumed':
return [...you('resumed'), kind('person'), b(who)];
return you(_('You resumed person %s'), b(who));
case 'device_changed': {
const renamed = detail.startsWith('renamed from ');
return [
...you(renamed ? 'renamed' : detail),
kind('device'),
b(dev || 'a device'),
m(' of '),
b(who),
...(renamed ? [m(` · was ${detail.slice(13)}`)] : []),
];
const d = b(dev || _('a device'));
if (detail.startsWith('renamed from '))
return [...you(_('You renamed device %s of %s'), d, b(who)), m(` · ${fmt(_('was %s'), detail.slice(13))}`)];
if (detail === 'turned off') return you(_('You turned off device %s of %s'), d, b(who));
if (detail === 'turned on') return you(_('You turned on device %s of %s'), d, b(who));
return [...you(_('You changed device %s of %s'), d, b(who)), ...(detail ? [m(` · ${detail}`)] : [])];
}
case 'device_keys':
return [...you('issued new keys for'), kind('device'), b(devName), m(' of '), b(who), m(' · it needs its new configuration')];
return [...you(_('You issued new keys for device %s of %s'), devName, b(who)), m(` · ${_('it needs its new configuration')}`)];
case 'link_changed':
return [...you('issued a new link for'), kind('person'), b(who), m(' · the old link stopped working')];
return [...you(_('You issued a new link for person %s'), b(who)), m(` · ${_('the old link stopped working')}`)];
}
switch (e.type) {
case 'connect':
return [
kind('Device'),
b(wd),
m(' connected'),
...(e.detail ? [m(' from '), ...addr(e.detail)] : []),
...(e.detail ? say(_('Device %s connected from %s'), wd, E('span', {}, addr(e.detail))) : say(_('Device %s connected'), wd)),
...(e.where ? [m(` · ${e.where}`)] : []),
];
case 'disconnect':
return [kind('Device'), b(wd), m(' went offline')];
return say(_('Device %s went offline'), wd);
case 'roam':
return [
kind('Device'),
b(wd),
m(' changed network '),
...(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
];
return say(
_('Device %s changed network %s'),
wd,
E(
'span',
{},
(e.detail ?? '').split(' → ').flatMap((ip, i) => (i ? [m(' → '), ...addr(ip)] : addr(ip))),
),
);
case 'device_added':
return [
kind('Person'),
b(who),
m(' added '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
return by === 'portal'
? say(_('Person %s added device %s on their portal'), b(who), devName)
: say(_('Person %s added device %s'), b(who), devName);
case 'device_removed':
return [
kind('Person'),
b(who),
m(' removed '),
kind('device'),
b(devName),
...(eventBy(e) === 'portal' ? [m(' on their portal')] : []),
];
return by === 'portal'
? say(_('Person %s removed device %s on their portal'), b(who), devName)
: say(_('Person %s removed device %s'), b(who), devName);
case 'device_keys':
return [kind('Person'), b(who), m(' issued new keys for '), kind('device'), b(devName), m(' on their portal')];
return say(_('Person %s issued new keys for device %s on their portal'), b(who), devName);
case 'person_added':
return [...you('added'), kind('person'), b(e.detail ?? who)];
return you(_('You added person %s'), b(e.detail ?? who));
case 'person_removed':
return [...you('removed'), kind('person'), b(e.detail ?? who)];
return you(_('You removed person %s'), b(e.detail ?? who));
case 'person_changed':
// The detail lists changed fields by their option names (device_limit, expire_action).
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
case 'expiring':
return [kind('Person'), b(who), m(`’s access ends in ${e.detail ?? 'a few days'}`)];
return [...you(_('You changed person %s'), b(who)), ...(detail ? [m(` · ${changedText(detail)}`)] : [])];
case 'expiring': {
const n = daysOf(e.detail ?? '');
return n != null
? say(N_(n, 'Person %s’s access ends in %s day', 'Person %s’s access ends in %s days'), b(who), m(num(n)))
: say(_('Person %s’s access ends in a few days'), b(who));
}
case 'expired_kept':
return [kind('Person'), b(who), m(`’s end date passed (${e.detail ?? ''}) · access kept`)];
return say(_('Person %s’s end date passed (%s) · access kept'), b(who), m(routerDay(e.detail ?? '')));
case 'paused':
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
return e.detail ? say(_('Person %s paused - %s'), b(who), m(reasonText(e.detail))) : say(_('Person %s paused'), b(who));
case 'resumed':
return [kind('Person'), b(who), m(' resumed'), ...(e.detail && e.detail !== 'active' ? [m(` — ${e.detail}`)] : [])];
return e.detail && e.detail !== 'active'
? say(_('Person %s resumed - %s'), b(who), m(reasonText(e.detail)))
: say(_('Person %s resumed'), b(who));
case 'portal_blocked':
return [
E('b', { class: 'dl-sys-src' }, 'Personal portal'),
m(' blocked '),
mono(e.detail ?? ''),
m(' for 15 min after too many wrong codes'),
];
return say(
_('%s blocked %s for 15 min after too many wrong codes'),
E('b', { class: 'dl-sys-src' }, _('Personal portal')),
e.detail === 'all Cloudflare visitors' ? m(_('all Cloudflare visitors')) : mono(e.detail ?? ''),
);
case 'devices_removed':
return [kind('Person'), b(who), m(' — all devices removed, end date reached')];
return say(_('Person %s - all devices removed, end date reached'), b(who));
default:
return [m(`${e.type}${e.detail ? `: ${e.detail}` : ''}`)];
}
@@ -171,7 +172,7 @@ function serverPill(st: Names, e: LogEvent): HTMLElement | '' {
if (st.servers.length < 2 || !e.person) return '';
const p = st.people.find((x) => x.id === e.person);
const srv = p && st.servers.find((s) => s.id === p.server);
return srv ? E('span', { class: 'dl-ev-srv', title: 'Server' }, srv.name) : '';
return srv ? E('span', { class: 'dl-ev-srv', title: _('Server') }, srv.name) : '';
}
/** An activity event as a row; `time` replaces the "5 min ago" (`now` is the router's clock). */
@@ -180,13 +181,13 @@ export function eventRow(st: Names & { now?: number }, e: LogEvent, opts: { serv
const by = eventBy(e);
return E('div', { class: `dl-row${by === 'admin' ? ' dl-ev-by-admin' : sys ? ` dl-ev-by-system ${sys[1]}` : ''}` }, [
by === 'admin'
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
? E('span', { class: 'dl-ev-tile', title: _('Done by you in LuCI') }, icon('admin'))
: sys
? E('span', { class: 'dl-ev-tile sys' }, icon(sys[0]))
: E('span', { class: `dl-ev-tile ev ${EVENT_TONE[e.type] ?? ''}` }, icon(eventIcon(st, e))),
E('span', { class: 'dl-row-main' }, eventText(st, e)),
opts.server === false ? '' : serverPill(st, e),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, opts.time ?? ago(e.ts, st.now)),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, opts.time ?? ago(e.ts, st.now)),
]);
}
@@ -195,9 +196,47 @@ export function eventRow(st: Names & { now?: number }, e: LogEvent, opts: { serv
const SYS_TONE: Record<ServiceLogEntry['level'], string> = { info: '', up: 'ok', down: 'warn', repair: 'warn', error: 'bad' };
const SYS_ICON: Record<ServiceLogEntry['src'], string> = { awg: 'tunnel', dawnline: 'sunrise', portal: 'globe' };
/** A service log level as its tile's tooltip says it. */
function levelLabel(l: ServiceLogEntry['level']): string {
return { info: _('info'), up: _('up'), down: _('down'), repair: _('repair'), error: _('error') }[l] ?? l;
}
/**
* The admin's own change: "You changed server Home" as one sentence of the
* page's language, "You" in the accent; one this page does not know is put
* together from the router's words as before.
*/
function adminLine(e: ServiceLogEntry): (Node | string)[] {
const s = adminSentence(e.msg, e.kind, e.who);
const you = _('You');
if (!s)
return [
E('span', { class: 'dl-you' }, you),
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
e.who ? E('b', {}, e.who) : '',
];
const parts = (s.named ? fill<Node | string>(s.text, E('b', {}, adminName(e.msg, e.who ?? ''))) : [s.text]).map((x) =>
typeof x === 'string' ? E('span', { class: 'dl-muted' }, x) : x,
);
// The accent on "You" where the sentence starts with it.
const first = parts[0]?.textContent ?? '';
return first.startsWith(`${you} `)
? [E('span', { class: 'dl-you' }, you), E('span', { class: 'dl-muted' }, first.slice(you.length)), ...parts.slice(1)]
: parts;
}
/** A log line's details: its sentences in the page's language, command output as it is. */
const detailText = (d: string) =>
d
.split('\n')
.map((l) => logText(l))
.join('\n');
/** A service log line: source, message, folded details; click to unfold. */
export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void, time: string): HTMLElement {
const admin = e.by === 'admin';
const msg = logText(e.msg);
const row = E(
'div',
{
@@ -205,32 +244,35 @@ export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void,
},
[
admin
? E('span', { class: 'dl-ev-tile', title: 'Done by you in LuCI' }, icon('admin'))
: E('span', { class: 'dl-ev-tile sys', title: e.level }, icon(SYS_ICON[e.src] ?? 'zap')),
? E('span', { class: 'dl-ev-tile', title: _('Done by you in LuCI') }, icon('admin'))
: E('span', { class: 'dl-ev-tile sys', title: levelLabel(e.level) }, icon(SYS_ICON[e.src] ?? 'zap')),
E(
'span',
{ class: 'dl-row-main' },
admin
? [
E('span', { class: 'dl-you' }, 'You'),
E('span', { class: 'dl-muted' }, ` ${e.msg} `),
e.kind ? E('span', { class: 'dl-ev-kind' }, `${e.kind} `) : '',
e.who ? E('b', {}, e.who) : '',
e.note ? E('span', { class: 'dl-muted' }, ` · ${e.note}`) : '',
...adminLine(e),
e.note ? E('span', { class: 'dl-muted' }, ` · ${noteText(e.note)}`) : '',
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, detailText(e.detail)) : '',
]
: [
// Servers have names people chose: say it is a server. Services name themselves.
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, 'Server ') : '',
E('b', { class: 'dl-sys-src', title: SYSTEM_SOURCE[e.src] ?? e.src }, e.who ?? SYSTEM_SOURCE[e.src] ?? e.src),
' ',
E('span', { class: 'dl-muted' }, e.msg),
e.src === 'awg' && e.who && e.who !== 'AmneziaWG' ? E('span', { class: 'dl-ev-kind' }, `${_('Server')} `) : '',
// A server's name as it is; Dawnline's own subjects ("Access rules") in the page's language.
E(
'b',
{ class: 'dl-sys-src', title: sourceName(e.src) },
e.who ? (e.src === 'awg' ? e.who : logText(e.who)) : sourceName(e.src),
),
// A translation may go on from the subject with a colon ("Home: AmneziaWG isn't running").
/^[:,]/.test(msg) ? '' : ' ',
E('span', { class: 'dl-muted' }, msg),
e.detail ? E('span', { class: `dl-slog-more${open ? ' open' : ''}` }, icon('chevron')) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, e.detail) : '',
e.detail && open ? E('pre', { class: 'dl-slog-detail' }, detailText(e.detail)) : '',
],
),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, time),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, time),
],
);
if (e.detail)
@@ -240,13 +282,14 @@ export function systemRow(e: ServiceLogEntry, open: boolean, toggle: () => void,
return row;
}
/** "Today", "Yesterday" or "Monday 12 October". */
/** "Today", "Yesterday" or "Monday 12 October" (capitalised: Russian names weekdays in lower case). */
export function dayTitle(ts: number): string {
const d = new Date(ts * 1000);
const today = new Date();
const y = new Date();
y.setDate(today.getDate() - 1);
if (d.toDateString() === today.toDateString()) return 'Today';
if (d.toDateString() === y.toDateString()) return 'Yesterday';
return d.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });
if (d.toDateString() === today.toDateString()) return _('Today');
if (d.toDateString() === y.toDateString()) return _('Yesterday');
const t = d.toLocaleDateString(locale(), { weekday: 'long', day: 'numeric', month: 'long' });
return t.charAt(0).toLocaleUpperCase(locale()) + t.slice(1);
}
+101 -73
View File
@@ -11,13 +11,15 @@ import { seg, sw } from './ui/controls';
import { attachTip } from './ui/tooltip';
import { installMissing } from './pkgs';
import { icon } from '../shared/icons';
import { fill, fmt, locale, plural } from '../shared/i18n';
const GROUPS: [IfaceCategory, string][] = [
/** Groups of "Other interfaces", in order, with their headings. */
const groups = (): [IfaceCategory, string][] => [
['wan', 'WAN'],
['ethernet', 'Ethernet'],
['wifi', 'Wi-Fi'],
['vpn', 'VPN & tunnels'],
['other', 'Other'],
['vpn', _('VPN & tunnels')],
['other', _('Other')],
];
const ICON: Record<NetDevice['kind'], string> = {
@@ -48,7 +50,7 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const root = E(
'div',
{ class: 'dl-stack gap16' },
E('section', { class: 'dl-setsec' }, E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, 'Loading interfaces…'))),
E('section', { class: 'dl-setsec' }, E('div', { class: 'dl-setsec-body' }, E('p', { class: 'dl-muted' }, _('Loading interfaces…')))),
);
let d: InterfacesData;
let autoWan = true,
@@ -112,16 +114,16 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const usable = !blocked && (x.nets.length > 0 || sel || !!x.missing);
const noZone = (sel || isAuto) && !x.zone && !x.missing;
const sub = x.missing
? 'Not present right now'
? _('Not present right now')
: x.own
? 'This server'
? _('This server')
: x.master
? `Port of ${x.master}`
? fmt(_('Port of %s'), x.master)
: isWan
? `Internet${x.zone ? ` · zone ${x.zone}` : ''}`
? `${_('Internet')}${x.zone ? ` · ${fmt(_('zone %s'), x.zone)}` : ''}`
: x.nets.length
? x.nets.join(', ')
: 'No IPv4 network';
: _('No IPv4 network');
const el = E(
'button',
{
@@ -140,19 +142,20 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
[
E('span', { class: 'dl-if-ic' }, icon(ICON[x.kind] ?? 'link')),
E('span', { class: 'dl-if-main' }, [E('span', { class: 'dl-if-name' }, x.name), E('span', { class: 'dl-if-sub' }, sub)]),
isAuto ? E('span', { class: 'dl-if-badge ok' }, 'Auto') : sel ? E('span', { class: 'dl-if-check' }, icon('check')) : '',
isAuto ? E('span', { class: 'dl-if-badge ok' }, _('Auto')) : sel ? E('span', { class: 'dl-if-check' }, icon('check')) : '',
],
);
attachTip(el, () => [
E('div', { class: 'dl-tip-title' }, x.name),
E('div', { class: 'dl-muted' }, [
x.logical ? `Interface ${x.logical}` : 'No netifd interface',
x.zone ? ` · zone ${x.zone}` : ' · no firewall zone',
x.logical ? fmt(_('Interface %s'), x.logical) : _('No netifd interface'),
' · ',
x.zone ? fmt(_('zone %s'), x.zone) : _('no firewall zone'),
]),
x.members.length ? E('div', { class: 'dl-muted' }, `Ports: ${x.members.join(', ')}`) : '',
x.members.length ? E('div', { class: 'dl-muted' }, fmt(_('Ports: %s'), x.members.join(', '))) : '',
x.nets.length ? E('div', { class: 'dl-mono' }, x.nets.join(', ')) : '',
noZone ? E('div', { class: 'dl-warn' }, 'Not in a firewall zone: the firewall rejects this traffic.') : '',
x.master ? E('div', { class: 'dl-muted' }, `Choose ${x.master} to include it.`) : '',
noZone ? E('div', { class: 'dl-warn' }, _('Not in a firewall zone: the firewall rejects this traffic.')) : '',
x.master ? E('div', { class: 'dl-muted' }, fmt(_('Choose %s to include it.'), x.master)) : '',
]);
return el;
}
@@ -167,36 +170,39 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
function likeHomeText(): (Node | string)[] {
const lh = d.like_home;
if (!lanLike) return ['Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.'];
if (!lanLike) return [_('Off: internet traffic goes straight to the WAN, past whatever handles home traffic on this router.')];
if (d.needs?.length)
return [
E('span', { class: 'dl-warn' }, `Needs ${d.needs.join(' and ')}.`),
' Until they are installed, internet traffic goes straight to the WAN.',
E('span', { class: 'dl-warn' }, fmt(_('Needs %s.'), new Intl.ListFormat(locale(), { type: 'conjunction' }).format(d.needs))),
' ',
_('Until they are installed, internet traffic goes straight to the WAN.'),
];
if (!d.config.lan_like)
return ['Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.'];
return [_('Internet traffic will enter the router from your LAN, so it is handled like any home device. Save to turn on.')];
// A server that is off has no link on purpose: describe the setting, not its state.
if (!srv.enabled)
return ['Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.'];
if (lh.active && lh.bridged)
return [
'Internet traffic enters ',
E('span', { class: 'dl-mono' }, lh.dev ?? ''),
' as ',
E('span', { class: 'dl-mono' }, lh.address ?? ''),
', so whatever handles home traffic (proxies, filters, DNS) handles it too.',
_('Internet traffic enters the router from your LAN, so whatever handles home traffic (proxies, filters, DNS) handles it too.'),
];
if (lh.active && lh.bridged)
return fill(
_('Internet traffic enters %s as %s, so whatever handles home traffic (proxies, filters, DNS) handles it too.'),
E('span', { class: 'dl-mono' }, lh.dev ?? ''),
E('span', { class: 'dl-mono' }, lh.address ?? ''),
);
return [
E('span', { class: 'dl-warn' }, `Not working: ${lh.error ?? 'the link is down'}`),
' Internet traffic goes straight to the WAN for now.',
E('span', { class: 'dl-warn' }, fmt(_('Not working: %s'), lh.error ?? _('the link is down'))),
' ',
_('Internet traffic goes straight to the WAN for now.'),
];
}
const MESH_TEXT: Record<MeshMode, string> = {
off: "Devices of different people never reach each other; a person's own devices don't either.",
all: 'Devices of people with home access reach each other, like home devices do. Internet-only people never.',
circles: 'Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never.',
};
const meshText = (m: MeshMode): string =>
({
off: _("Devices of different people never reach each other; a person's own devices don't either."),
all: _('Devices of people with home access reach each other, like home devices do. Internet-only people never.'),
circles: _('Within a circle: family sees family, guests see guests. Everyone reaches their own devices. Internet-only people never.'),
})[m];
function setrow(
ic: string,
@@ -217,8 +223,12 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const hint = (live: string | null, saved: string) => {
const mono = (t: string) => E('span', { class: 'dl-mono' }, t);
if (live) return E('span', {}, [' Now: ', mono(live), ...(saved && saved !== live ? [', was ', mono(saved)] : []), '.']);
return E('span', {}, saved ? [' Not found now: using ', mono(saved), '.'] : [' Not found.']);
if (live)
return E('span', {}, [
' ',
...(saved && saved !== live ? fill(_('Now: %s, was %s.'), mono(live), mono(saved)) : fill(_('Now: %s.'), mono(live))),
]);
return E('span', {}, [' ', ...(saved ? fill(_('Not found now: using %s.'), mono(saved)) : [_('Not found.')])]);
};
function paint() {
@@ -226,7 +236,7 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
'select',
{
class: 'cbi-input-select',
'aria-label': 'Internet interface',
'aria-label': _('Internet interface'),
change: (ev: Event) => {
wanDev = (ev.target as HTMLSelectElement).value;
paint();
@@ -234,7 +244,9 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
},
d.devices
.filter((x) => !x.own && !x.master && x.zone && !x.missing)
.map((x) => E('option', { value: x.name, selected: x.name === wanDev ? 'selected' : null }, `${x.name} · zone ${x.zone}`)),
.map((x) =>
E('option', { value: x.name, selected: x.name === wanDev ? 'selected' : null }, `${x.name} · ${fmt(_('zone %s'), x.zone)}`),
),
) as HTMLSelectElement;
const home = homeDevs();
@@ -247,17 +259,21 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const homeDirty = changed(3, 4);
const save = (on: boolean) =>
button(
'Save',
_('Save'),
async () => {
const r = await attempt(
() => api.serverInterfaces(serverId, autoWan, autoWan ? '' : wanDev, autoLan, [...lans], lanLike, mesh !== 'off', mesh),
'Access saved',
_('Access saved'),
);
if (!r) return;
take(r, true);
if (r.nets_changed && r.lan_only)
notify(
`${r.lan_only} ${r.lan_only === 1 ? 'person has' : 'people have'} Home-only access: their devices need the configuration again to reach the new networks.`,
plural(
r.lan_only,
'%s person has Home-only access: their devices need the configuration again to reach the new networks.',
'%s people have Home-only access: their devices need the configuration again to reach the new networks.',
),
'warning',
10000,
);
@@ -269,17 +285,17 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const internet = E('section', { class: 'dl-setsec dl-ifcard' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Internet'),
E('h3', {}, _('Internet')),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'People with Internet or Both'),
E('span', { class: 'dl-sub' }, _('People with Internet or Both')),
]),
setrow(
'home',
'Internet like a home device',
_('Internet like a home device'),
likeHomeText(),
[
lanLike && d.needs?.length ? button('Install', () => installMissing('home', d.needs!, () => load(false)), 'positive') : '',
sw(lanLike, 'Internet like a home device', (v) => {
lanLike && d.needs?.length ? button(_('Install'), () => installMissing('home', d.needs!, () => load(false)), 'positive') : '',
sw(lanLike, _('Internet like a home device'), (v) => {
lanLike = v;
paint();
}),
@@ -288,14 +304,14 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
),
setrow(
'globe',
'Auto-detect WAN',
_('Auto-detect WAN'),
[
'The interface with the default route: the server port opens there and Internet access leaves through it.',
_('The interface with the default route: the server port opens there and Internet access leaves through it.'),
hint(d.detected.wan, d.saved.wan),
],
[
autoWan ? '' : wanSel,
sw(autoWan, 'Auto-detect WAN', (v) => {
sw(autoWan, _('Auto-detect WAN'), (v) => {
autoWan = v;
paint();
}),
@@ -307,10 +323,13 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
'span',
{ class: 'dl-sub' },
lanLike
? ['Internet like a home device', currentWan() ? [' · leaves through ', E('span', { class: 'dl-mono' }, currentWan())] : '']
? [
_('Internet like a home device'),
currentWan() ? [' · ', ...fill(_('leaves through %s'), E('span', { class: 'dl-mono' }, currentWan()))] : '',
]
: currentWan()
? ['Internet straight to ', E('span', { class: 'dl-mono' }, currentWan())]
: 'No WAN found',
? fill(_('Internet straight to %s'), E('span', { class: 'dl-mono' }, currentWan()))
: _('No WAN found'),
),
save(netDirty),
]),
@@ -318,19 +337,19 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const meshSeg = seg(
[
['off', 'Off'],
['all', 'Everyone'],
['circles', 'Circles'],
['off', _('Off')],
['all', _('Everyone')],
['circles', _('Circles')],
] as [MeshMode, string][],
mesh,
{
label: 'Devices reach each other',
label: _('Devices reach each other'),
cls: 'sm',
optimistic: false,
// Applies at once, like the choices on a person's page.
onChange: async (v) => {
const t = { off: 'Off', all: 'Everyone', circles: 'Circles' }[v];
if (!(await attempt(() => api.serverUpdate(serverId, { mesh: v }), `Devices reach each other: ${t}`))) return;
const t = { off: _('Off'), all: _('Everyone'), circles: _('Circles') }[v];
if (!(await attempt(() => api.serverUpdate(serverId, { mesh: v }), fmt(_('Devices reach each other: %s'), t)))) return;
mesh = v;
d.config.mesh = v;
paint();
@@ -342,23 +361,25 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
const homeCard = E('section', { class: 'dl-setsec dl-ifcard' }, [
E('div', { class: 'dl-setsec-body' }, [
E('div', { class: 'dl-panel-head' }, [
E('h3', {}, 'Home network'),
E('h3', {}, _('Home network')),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-sub' }, 'People with Home or Both'),
button([icon('reset'), ' Rescan'], () => load(false), 'neutral', { title: 'Read the interfaces again' }),
E('span', { class: 'dl-sub' }, _('People with Home or Both')),
button([icon('reset'), ' ', _('Rescan')], () => load(false), 'neutral', { title: _('Read the interfaces again') }),
]),
setrow(
'network',
'Networks',
'Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.',
_('Networks'),
_(
'Everyone with home access reaches these, unless their page leaves one out; their devices can be reached from here too. Click one to add or remove it.',
),
'',
'',
netPicker(),
),
setrow(
'link',
'Devices reach each other',
MESH_TEXT[mesh],
_('Devices reach each other'),
meshText(mesh),
meshSeg,
'',
mesh === 'circles' ? circleChips(st, serverId, refresh) : undefined,
@@ -370,8 +391,15 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
'span',
{ class: 'dl-sub dl-if-summary' },
nets.length
? ['Home access reaches ', ...nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`])]
: 'No home network: Home access reaches nothing but this router.',
? fill(
_('Home access reaches %s'),
E(
'span',
{},
nets.flatMap(([n, dev], i) => [i ? ', ' : '', E('span', { class: 'dl-mono' }, n), ` (${dev})`]),
),
)
: _('No home network: Home access reaches nothing but this router.'),
),
save(homeDirty),
]),
@@ -392,13 +420,13 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
return E('div', { class: 'dl-stack gap8 dl-netpick' }, [
avail.length
? E('div', { class: 'dl-ifgrid' }, avail.map(tile))
: E('span', { class: 'dl-warn' }, 'No home network: Home access reaches nothing but this router.'),
: E('span', { class: 'dl-warn' }, _('No home network: Home access reaches nothing but this router.')),
E('label', { class: 'dl-boxrow' }, [
E('span', { class: 'dl-stack' }, [
E('span', {}, 'Auto-detect LAN'),
E('span', { class: 'dl-sub' }, ['Adds the LAN this router uses.', hint(d.detected.lan, d.saved.lan)]),
E('span', {}, _('Auto-detect LAN')),
E('span', { class: 'dl-sub' }, [_('Adds the LAN this router uses.'), hint(d.detected.lan, d.saved.lan)]),
]),
sw(autoLan, 'Auto-detect LAN', (v) => {
sw(autoLan, _('Auto-detect LAN'), (v) => {
autoLan = v;
paint();
}),
@@ -414,16 +442,16 @@ export function accessCards(srv: Server, first: Status, refresh: () => Promise<u
[
E('summary', {}, [
icon('chevron'),
E('span', {}, 'Other interfaces'),
E('span', {}, _('Other interfaces')),
E('span', { class: 'dl-pcount' }, String(rest.length)),
]),
E('div', { class: 'dl-params-body' }, [
E(
'span',
{ class: 'dl-sub' },
'The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network.',
_('The WAN, this server, ports and Wi-Fi of a bridge (they come with it) and interfaces without an IPv4 network.'),
),
...GROUPS.map(([cat, label]) => {
...groups().map(([cat, label]) => {
const list = rest.filter((x) => x.category === cat);
return list.length
? E('div', { class: 'dl-ifgroup' }, [E('h4', {}, label), E('div', { class: 'dl-ifgrid' }, list.map(tile))])
+35 -28
View File
@@ -10,6 +10,7 @@ import { copyText, downloadFile } from './ui/files';
import { attempt, notify } from './ui/toast';
import { icon } from '../shared/icons';
import { qrSvg } from '../shared/qr';
import { fill, fmt } from '../shared/i18n';
const W = 1080,
H = 1512;
@@ -23,8 +24,9 @@ const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&
function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string {
const url = new URL(link);
const word = url.pathname.slice(1);
const hi = fmt(_('Hi, %s'), p.name);
// Long names shrink to stay on one line (roughly 0.58 em per character).
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * (4 + p.name.length))));
const nameSize = Math.min(92, Math.floor((W - 2 * M) / (0.58 * hi.length)));
const tile = W - 2 * M,
top = 392,
pad = 40;
@@ -39,8 +41,8 @@ function cardSvg(p: Pick<Person, 'name'>, server: string, link: string): string
`<g transform="scale(.9375)"><path d="M14 38a18 18 0 0 1 36 0z" fill="#0b0b0b"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0b0b0b" opacity=".5"/></g></g>` +
text(M + 82, M + 42, 36, '#a3a3a3', esc(server)) +
// Greeting
text(M, 276, nameSize, '#ffffff', `Hi, ${esc(p.name)}`, 'font-weight="600"') +
text(M, 340, 40, '#8a8a8a', `Scan to connect to ${esc(server)}`) +
text(M, 276, nameSize, '#ffffff', esc(hi), 'font-weight="600"') +
text(M, 340, 40, '#8a8a8a', esc(fmt(_('Scan to connect to %s'), server))) +
// Big QR on a white tile, edge to edge with the text above
`<rect x="${M}" y="${top}" width="${tile}" height="${tile}" rx="52" fill="#ffffff"/>` +
qr +
@@ -60,7 +62,7 @@ async function toPng(svg: string): Promise<Blob> {
canvas.height = H;
canvas.getContext('2d')!.drawImage(img, 0, 0, W, H);
return new Promise((resolve, reject) =>
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('Could not draw the card'))), 'image/png'),
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(_('Could not draw the card')))), 'image/png'),
);
}
@@ -72,7 +74,7 @@ export async function personLinks(id: string): Promise<{ link: string; links: st
const r = await attempt(() => api.personLinks(id));
if (!r) return null;
if (!r.link) {
notify('The personal portal is off. Turn it on in Settings.', 'warning');
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
return null;
}
return { link: r.link, links: r.links ?? [] };
@@ -81,7 +83,7 @@ export async function personLinks(id: string): Promise<{ link: string; links: st
/** Copy a person's personal link. */
export async function copyPersonLink(id: string) {
const r = await personLinks(id);
if (r) await copyText(r.link, 'Personal link copied');
if (r) await copyText(r.link, _('Personal link copied'));
}
/**
@@ -98,7 +100,7 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
links = r.links;
}
if (!link) {
notify('The personal portal is off. Turn it on in Settings.', 'warning');
notify(_('The personal portal is off. Turn it on in Settings.'), 'warning');
return;
}
const href = link;
@@ -123,49 +125,54 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
}
};
const share = canShareFile
? button([icon('link'), ' Share card'], () => shareIt({ files: [file], title: `Invite ${p.name}` }), 'positive')
? button([icon('link'), ' ', _('Share card')], () => shareIt({ files: [file], title: fmt(_('Invite %s'), p.name) }), 'positive')
: canShareLink
? button(
[icon('link'), ' Share link'],
() => shareIt({ url: href, title: `Invite ${p.name}`, text: `Your personal VPN link` }),
[icon('link'), ' ', _('Share link')],
() => shareIt({ url: href, title: fmt(_('Invite %s'), p.name), text: _('Your personal VPN link') }),
'positive',
)
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
: button([icon('download'), ' ', _('Download card')], () => downloadFile(file.name, png), 'positive');
modal(
opts.title ?? `Invite ${p.name}`,
opts.title ?? fmt(_('Invite %s'), p.name),
E('div', { class: 'dl-invite' }, [
E('img', { src: url, alt: `Invite card for ${p.name}` }),
E('img', { src: url, alt: fmt(_('Invite card for %s'), p.name) }),
E('div', { class: 'dl-invite-side' }, [
E(
'p',
{ class: 'dl-muted' },
opts.lead ?? `Send ${p.name} the card or the link. They open it, add their devices and connect — no account needed.`,
opts.lead ?? fmt(_('Send %s the card or the link. They open it, add their devices and connect - no account needed.'), p.name),
),
E(
'button',
{ type: 'button', class: 'dl-invite-link', title: _('Copy link'), click: () => copyText(href, _('Personal link copied')) },
[E('span', {}, href.replace(/^https:\/\//, '')), icon('copy')],
),
E('button', { type: 'button', class: 'dl-invite-link', title: 'Copy link', click: () => copyText(href, 'Personal link copied') }, [
E('span', {}, href.replace(/^https:\/\//, '')),
icon('copy'),
]),
...(links ?? [])
.filter((l) => l !== href)
.map((l) =>
E('button', { type: 'button', class: 'dl-invite-link alt', title: 'Copy this link', click: () => copyText(l, 'Link copied') }, [
E('span', {}, l.replace(/^https?:\/\//, '')),
E('span', { class: `dl-pill ${l.startsWith('http:') ? 'warn' : ''}` }, l.startsWith('http:') ? 'HTTP' : 'Also'),
icon('copy'),
]),
E(
'button',
{ type: 'button', class: 'dl-invite-link alt', title: _('Copy this link'), click: () => copyText(l, _('Link copied')) },
[
E('span', {}, l.replace(/^https?:\/\//, '')),
E('span', { class: `dl-pill ${l.startsWith('http:') ? 'warn' : ''}` }, l.startsWith('http:') ? 'HTTP' : _('Also')),
icon('copy'),
],
),
),
E('ol', { class: 'dl-invite-steps' }, [
E('li', {}, ['Install ', E('b', {}, 'AmneziaVPN'), ' on the device']),
E('li', {}, 'Open the link or scan the code'),
E('li', {}, 'Add the device and connect'),
E('li', {}, fill(_('Install %s on the device'), E('b', {}, 'AmneziaVPN'))),
E('li', {}, _('Open the link or scan the code')),
E('li', {}, _('Add the device and connect')),
]),
E('div', { class: 'dl-invite-actions' }, [
share,
button([icon('copy'), ' Copy link'], () => copyText(href, 'Personal link copied')),
button([icon('copy'), ' ', _('Copy link')], () => copyText(href, _('Personal link copied'))),
]),
]),
]),
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, 'Done')],
[E('button', { class: 'cbi-button cbi-button-neutral', click: close }, _('Done'))],
'wide',
);
}
+37 -29
View File
@@ -8,8 +8,9 @@ import { button } from './ui/button';
import { cancelButton, closeModal, modal } from './ui/modal';
import { downloadFile } from './ui/files';
import { attempt, errorText, notify } from './ui/toast';
import { CATEGORIES, CATEGORY_LABEL, SYSTEM_SOURCE, categoryOf, eventBy } from './events/model';
import { CATEGORIES, categoryLabel, categoryOf, eventBy, sourceName } from './events/model';
import { toCsv } from './events/csv';
import { fmt, plural } from '../shared/i18n';
function names(st: Pick<Status, 'people'>) {
const people = new Map(st.people.map((p) => [p.id, p.name]));
@@ -44,7 +45,7 @@ export function exportEvents(
person: '',
device: '',
detail: `${e.who ? `${e.who} ` : ''}${e.msg}${e.detail ? `\n${e.detail}` : ''}`,
where: SYSTEM_SOURCE[e.src] ?? e.src,
where: sourceName(e.src),
by: '',
})),
]
@@ -57,17 +58,26 @@ export function exportEvents(
return;
}
const cols = ['time', 'category', 'type', 'person', 'device', 'detail', 'where', 'by'] as const;
downloadFile(name, toCsv(cols, rows), 'text/csv');
// The header row in the page's language; the cells are the log's ids, names and details.
const head = {
time: _('Time'),
category: _('Category'),
type: _('Type'),
person: _('Person'),
device: _('Device'),
detail: _('Detail'),
where: _('Where'),
by: _('By'),
};
downloadFile(name, toCsv(cols, rows, head), 'text/csv');
}
const AGES: [string, string][] = [
['', 'Everything'],
['7', 'Older than 7 days'],
['30', 'Older than 30 days'],
['90', 'Older than 90 days'],
];
/** The ages the dialog offers, in days ('' = everything). */
const AGES = ['', '7', '30', '90'];
const removed = (n: number) => (n ? `${n} event${n === 1 ? '' : 's'} removed` : 'Nothing matched');
const ageLabel = (v: string) => (v ? plural(Number(v), 'Older than %s day', 'Older than %s days') : _('Everything'));
const removed = (n: number) => (n ? plural(n, '%s event removed', '%s events removed') : _('Nothing matched'));
/**
* Ask what to clear and do it. `base` pins person/device; the dialog lets you
@@ -82,27 +92,27 @@ export function clearLogDialog(
withSystem = false,
) {
const cat = E('select', { class: 'cbi-input-select' }, [
E('option', { value: '' }, 'All categories'),
...CATEGORIES.map((c) => E('option', { value: c, selected: c === category ? 'selected' : null }, CATEGORY_LABEL[c])),
withSystem ? E('option', { value: 'system', selected: category === 'system' ? 'selected' : null }, 'System') : '',
E('option', { value: '' }, _('All categories')),
...CATEGORIES.map((c) => E('option', { value: c, selected: c === category ? 'selected' : null }, categoryLabel(c))),
withSystem ? E('option', { value: 'system', selected: category === 'system' ? 'selected' : null }, _('System')) : '',
]) as HTMLSelectElement;
const age = E(
'select',
{ class: 'cbi-input-select' },
AGES.map(([v, t]) => E('option', { value: v }, t)),
AGES.map((v) => E('option', { value: v }, ageLabel(v))),
) as HTMLSelectElement;
modal(
title,
[
E('p', { class: 'dl-muted' }, `${what} This cannot be undone; export first if you want a copy.`),
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Category'), cat]),
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Which events'), age]),
E('p', { class: 'dl-muted' }, `${what} ${_('This cannot be undone; export first if you want a copy.')}`),
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Category')), cat]),
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, _('Which events')), age]),
],
[
cancelButton(),
' ',
button(
'Clear',
_('Clear'),
async () => {
// The activity log first, then the service log ("System"; "All categories"
// clears it too where it is shown). Each result is reported on its own.
@@ -120,11 +130,9 @@ export function clearLogDialog(
n += (await api.serviceLogClear(age.value)).removed;
} catch (e) {
closeModal();
notify(
`${cat.value === 'system' ? '' : `Activity: ${removed(n).toLowerCase()}. `}The service log was not cleared: ${errorText(e)}`,
'error',
10000,
);
// The router's reason last, as it came.
const failed = fmt(_('The service log was not cleared: %s'), errorText(e));
notify(cat.value === 'system' ? failed : `${fmt(_('Activity: %s.'), removed(n).toLowerCase())} ${failed}`, 'error', 10000);
done();
return;
}
@@ -143,20 +151,20 @@ export function clearLogDialog(
export function resetUsageDialog(scope: 'all' | 'person' | 'device', id: string, label: string, done: () => unknown) {
const body =
scope === 'device'
? `Clears ${label}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`
? fmt(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."), label)
: scope === 'person'
? `Clears ${label}'s traffic history and that of their devices. Their data limit starts again from zero.`
: 'Clears traffic history for everyone. Data limits start again from zero.';
? fmt(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."), label)
: _('Clears traffic history for everyone. Data limits start again from zero.');
modal(
scope === 'all' ? 'Reset all traffic history?' : `Reset traffic history for ${label}?`,
scope === 'all' ? _('Reset all traffic history?') : fmt(_('Reset traffic history for %s?'), label),
[E('p', { class: 'dl-muted' }, body)],
[
cancelButton(),
' ',
button(
'Reset',
_('Reset'),
async () => {
if (!(await attempt(() => api.usageClear(scope, id), 'Traffic history reset'))) return;
if (!(await attempt(() => api.usageClear(scope, id), _('Traffic history reset')))) return;
closeModal();
done();
},
-2
View File
@@ -113,8 +113,6 @@ declare global {
}
const E: (tag: string, attrs?: ElementAttrs | Child, children?: Child) => HTMLElement;
const _: (msg: string, ctx?: string) => string;
const N_: (n: number, singular: string, plural: string, ctx?: string) => string;
const L: LuciL;
const ui: LuciUI;
const rpc: LuciRpc;
+51 -31
View File
@@ -8,6 +8,7 @@
import type { Geo, GeoPoint, Person } from '../shared/types';
import { E } from './e';
import { ago, initials } from '../shared/format';
import { fmt, num, plural } from '../shared/i18n';
import { icon, iconSvg } from '../shared/icons';
import { onNavigate } from './ui/nav';
import { isDark } from './ui/theme';
@@ -64,8 +65,8 @@ function loadMapLibre(host: HTMLElement): Promise<any> {
loading = null;
throw new Error(
e?.message === 'integrity'
? 'The map library from the CDN is not the expected file: not loading it.'
: 'Could not load the map library (no internet access from this browser?)',
? _('The map library from the CDN is not the expected file: not loading it.')
: _('Could not load the map library (no internet access from this browser?)'),
);
},
);
@@ -416,11 +417,11 @@ export class ConnectionMap {
this.dockKey = '';
const el = E(
'div',
{ class: 'dl-mk-hub', title: `Home router${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}` },
[host, E('span', { class: 'dl-mk-label chip' }, home.city || 'Home')],
{ class: 'dl-mk-hub', title: `${_('Home router')}${home.city ? ` · ${home.city}` : ''}${home.org ? ` · ${home.org}` : ''}` },
[host, E('span', { class: 'dl-mk-label chip' }, home.city || _('Home'))],
);
// Who is docked here: listed on hover; a click on the plate zooms to them (an avatar opens its card).
el.addEventListener('mouseenter', () => this.showMerged(home.city || 'the server'));
el.addEventListener('mouseenter', () => this.showMerged(home.city));
el.addEventListener('mouseleave', () => this.focus(this.focused));
el.addEventListener('click', () => this.zoomToMerged());
this.add(el, [home.lon, home.lat], true);
@@ -448,7 +449,9 @@ export class ConnectionMap {
{
type: 'button',
class: `dl-mk${g.online ? ' online' : ''}`,
'aria-label': `${person?.name ?? 'Someone'}: ${n} device${n === 1 ? '' : 's'} in ${g.city || 'an unknown city'}`,
'aria-label': g.city
? fmt(N_(n, '%s: %s device in %s', '%s: %s devices in %s'), person?.name ?? _('Someone'), num(n), g.city)
: fmt(N_(n, '%s: %s device in an unknown city', '%s: %s devices in an unknown city'), person?.name ?? _('Someone'), num(n)),
},
[
E('span', { class: 'dl-mk-av' }, [initials(person?.name ?? '?'), badge]),
@@ -462,7 +465,15 @@ export class ConnectionMap {
ev.stopPropagation();
this.openPopup(g, at, el);
});
this.add(el, at, false, person?.name ?? 'Someone', `${g.city || g.cc || '?'} · ${g.online ? 'now' : ago(g.ts, data.now)}`, g.key, g);
this.add(
el,
at,
false,
person?.name ?? _('Someone'),
`${g.city || g.cc || '?'} · ${g.online ? _('now') : ago(g.ts, data.now)}`,
g.key,
g,
);
}
this.declutter();
@@ -488,7 +499,7 @@ export class ConnectionMap {
this.fit(coords, animate);
}
}
this.status.textContent = placed.length || home ? '' : 'No locations yet';
this.status.textContent = placed.length || home ? '' : _('No locations yet');
this.status.style.display = this.status.textContent ? '' : 'none';
this.focus(this.focused && this.people.some((x) => x.person === this.focused) ? this.focused : null);
}
@@ -605,11 +616,14 @@ export class ConnectionMap {
this.popup = null;
}
/** The people folded into the server, in the corner card. */
private showMerged(place: string) {
/** The people folded into the server, in the corner card; `city` is the server's, when known. */
private showMerged(city: string) {
if (!this.merged.length) return;
dom.content(this.card, [
E('div', { class: 'dl-map-card-head' }, [E('b', {}, `Near ${place}`), ' · click to zoom in']),
E('div', { class: 'dl-map-card-head' }, [
E('b', {}, city ? fmt(_('Near %s'), city) : _('Near the server')),
` · ${_('click to zoom in')}`,
]),
...this.merged.map((m) => E('div', { class: 'dl-map-card-row' }, [E('span', {}, m.who), E('span', { class: 'dl-faint' }, m.where)])),
]);
this.card.classList.add('on');
@@ -682,7 +696,7 @@ export class ConnectionMap {
const cities = [...new Set(slots.map((x) => x.g?.city || x.g?.cc || '?'))];
const el = E('div', { class: 'dl-mk-pile' }, [
box,
E('span', { class: 'dl-mk-label below' }, cities.length === 1 ? cities[0] : `${slots.length} people`),
E('span', { class: 'dl-mk-label below' }, cities.length === 1 ? cities[0] : plural(slots.length, '%s person', '%s people')),
]);
pile = { marker: new this.gl.Marker({ element: el }).setLngLat(at).addTo(this.map), el, box, faces };
el.addEventListener('mouseleave', () => this.focus(this.focused));
@@ -796,14 +810,16 @@ export class ConnectionMap {
const n = g.points.length;
const tile = E('span', { class: 'dl-mk-tile' });
tile.innerHTML = iconSvg(kind, 'dl-mk-tile-ic') + (n > 1 ? `<span class="dl-mk-tile-n">${n}</span>` : '');
const when = g.online ? 'now' : ago(g.ts, now);
const when = g.online ? _('now') : ago(g.ts, now);
const el = E(
'button',
{
type: 'button',
class: `dl-mk place${g.online ? ' online' : ''}`,
style: g.online ? null : `--dl-mk-fade:${Math.max(0.4, 1 - (0.6 * (now - g.ts)) / (30 * 86400)).toFixed(2)}`,
'aria-label': `${n} device${n === 1 ? '' : 's'} in ${g.city || 'an unknown city'}, ${when}`,
'aria-label': g.city
? fmt(N_(n, '%s device in %s, %s', '%s devices in %s, %s'), num(n), g.city, when)
: fmt(N_(n, '%s device in an unknown city, %s', '%s devices in an unknown city, %s'), num(n), when),
},
[tile, E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', E('span', { class: 'dl-mk-when' }, when)])],
);
@@ -850,11 +866,11 @@ export class ConnectionMap {
x.when = null;
if (on) {
// In the replay the time goes on the city's line (two lines would run into a place below).
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : 'now');
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : _('now'));
x.label.replaceChildren(city, r ? ' · ' : '', x.when);
} else x.label.replaceChildren(`${city} · ${x.g.online ? 'now' : ago(x.g.ts, this.data!.now)}`);
const when = on ? (r ? r.when : 'now') : x.g.online ? 'now' : ago(x.g.ts, this.data!.now);
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || 'an unknown city'}, ${when}`);
} else x.label.replaceChildren(`${city} · ${x.g.online ? _('now') : ago(x.g.ts, this.data!.now)}`);
const when = on ? (r ? r.when : _('now')) : x.g.online ? _('now') : ago(x.g.ts, this.data!.now);
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || _('an unknown city')}, ${when}`);
if (animate && on && !was) {
x.el.classList.remove('arrive');
void x.el.offsetWidth;
@@ -940,11 +956,11 @@ export class ConnectionMap {
.filter((p) => p.person === person)
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts);
dom.content(this.card, [
E('div', { class: 'dl-map-card-head' }, [E('b', {}, who?.name ?? person), ` · ${pts.length} device${pts.length === 1 ? '' : 's'}`]),
E('div', { class: 'dl-map-card-head' }, [E('b', {}, who?.name ?? person), ` · ${plural(pts.length, '%s device', '%s devices')}`]),
...pts.map((p) =>
E('div', { class: 'dl-map-card-row' }, [
E('span', {}, who?.devices.find((d) => d.id === p.device)?.name ?? 'Device'),
E('span', { class: 'dl-faint' }, `${p.city || p.cc || '?'} · ${p.online ? 'now' : ago(p.ts, data.now)}`),
E('span', {}, who?.devices.find((d) => d.id === p.device)?.name ?? _('Device')),
E('span', { class: 'dl-faint' }, `${p.city || p.cc || '?'} · ${p.online ? _('now') : ago(p.ts, data.now)}`),
]),
),
]);
@@ -1010,6 +1026,7 @@ export class ConnectionMap {
const data = this.data!;
const where = [g.city, g.cc || g.country].filter(Boolean).join(', ');
const people = [...new Set(g.points.map((p) => p.person))];
const owner = people.length === 1 ? data.people.find((x) => x.id === people[0])?.name : undefined;
const rows = g.points
.sort((a, b) => Number(b.online) - Number(a.online) || b.ts - a.ts)
.map((p) => {
@@ -1017,16 +1034,19 @@ export class ConnectionMap {
const dev = person?.devices.find((d) => d.id === p.device);
return E('button', { type: 'button', class: 'dl-pop-row', click: () => this.cb.openDevice(p.person, p.device) }, [
E('span', { class: `dl-pop-dot${p.online ? ' on' : ''}` }),
E('span', { class: 'dl-pop-name' }, [E('b', {}, person?.name ?? p.person), ` · ${dev?.name ?? 'device'}`]),
E('span', { class: 'dl-faint dl-nowrap' }, p.online ? 'now' : ago(p.ts, data.now)),
E('span', { class: 'dl-pop-name' }, [E('b', {}, person?.name ?? p.person), ` · ${dev?.name ?? _('device')}`]),
E('span', { class: 'dl-faint dl-nowrap' }, p.online ? _('now') : ago(p.ts, data.now)),
]);
});
const body = E('div', { class: 'dl-pop' }, [
E('div', { class: 'dl-pop-head' }, [
E('span', { class: 'dl-pop-net' }, icon('globe')),
E('div', { class: 'dl-stack' }, [
E('strong', {}, g.org || 'Unknown network'),
E('span', { class: 'dl-faint' }, [g.asn ? `AS${g.asn} · ` : '', where ? `${where} · approximate` : 'approximate location']),
E('strong', {}, g.org || _('Unknown network')),
E('span', { class: 'dl-faint' }, [
g.asn ? `AS${g.asn} · ` : '',
where ? `${where} · ${_('approximate')}` : _('approximate location'),
]),
]),
]),
E('div', { class: 'dl-pop-list' }, rows),
@@ -1035,7 +1055,7 @@ export class ConnectionMap {
E(
'button',
{ type: 'button', class: 'cbi-button cbi-button-positive important', click: () => this.cb.openPerson(people[0]) },
`Open ${data.people.find((x) => x.id === people[0])?.name ?? 'person'}`,
owner ? fmt(_('Open %s'), owner) : _('Open person'),
),
])
: '',
@@ -1198,7 +1218,7 @@ export interface Face {
function face(slot: { el: HTMLElement; at: [number, number]; who?: string; where?: string; g?: Group }): Face {
return {
key: slot.el.dataset.key ?? '',
who: slot.who ?? 'Someone',
who: slot.who ?? _('Someone'),
where: slot.where ?? '',
online: !!slot.g?.online,
at: slot.at,
@@ -1350,10 +1370,10 @@ interface Group {
/** Segmented range control for the map header. */
export function rangeControl(initial: Range, onChange: (r: Range) => void, online = true): HTMLElement {
const opts: [Range, string][] = [
['online', 'Online now'],
['24h', '24h'],
['7d', '7 days'],
['30d', '30 days'],
['online', _('Online now')],
['24h', _('24h')],
['7d', _('7 days')],
['30d', _('30 days')],
];
const el = E('div', { class: 'dl-seg', role: 'tablist' });
for (const [v, label] of opts) {
+106 -63
View File
@@ -2,6 +2,8 @@
// them (rpc/servers.uc) and said in plain words for the setup wizard. The
// addresses are three numbers ("10.77.0"): the tunnel is that /24.
import { fmt, locale, num, plural } from '../shared/i18n';
/** A network on the router, by name: an interface ("lan") or a server ("Home"). */
export interface Network {
name: string;
@@ -56,19 +58,19 @@ export function subnetOf(range: string): string {
export function rangeHelp(range: string, nets: Network[], suggest: string): Help {
const r = range.trim();
const c = /^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(r) ? parseCidr(subnetOf(r)) : null;
if (!c) return { text: 'Three numbers, like 10.77.0.', bad: true };
if (!c) return { text: _('Three numbers, like 10.77.0.'), bad: true };
if (!PRIVATE.some((p) => c.net >= p.net && c.net + c.size <= p.net + p.size))
return { text: 'Use a private range: 10.x.x, 172.16–31.x or 192.168.x.', bad: true };
return { text: _('Use a private range: 10.x.x, 172.16–31.x or 192.168.x.'), bad: true };
const hit = nets.find((n) => {
const o = parseCidr(n.cidr);
return o != null && overlaps(c, o);
});
if (hit) {
const used = hit.cidr.endsWith('/24') ? `${rangeOf(hit.cidr)}.x` : hit.cidr;
const other = suggest && suggest !== r ? ` Try ${suggest}.` : '';
return { text: `${hit.name} already uses ${used}.${other}`, bad: true };
const uses = fmt(_('%s already uses %s.'), hit.name, used);
return { text: suggest && suggest !== r ? `${uses} ${fmt(_('Try %s.'), suggest)}` : uses, bad: true };
}
return { text: `Devices get ${r}.2 – ${r}.254, the router ${r}.1.`, bad: false };
return { text: fmt(_('Devices get %s – %s, the router %s.'), `${r}.2`, `${r}.254`, `${r}.1`), bad: false };
}
const holder = (port: number, taken: PortHold[]): string | null => taken.find((t) => t.from <= port && port <= t.to)?.who ?? null;
@@ -77,19 +79,21 @@ const validPort = (port: number): boolean => Number.isInteger(port) && port >= 1
/** A port: `free` when nobody holds it, or who does. */
export function portHelp(port: number, taken: PortHold[], free: string): Help {
if (!validPort(port)) return { text: 'Use a port from 1 to 65535.', bad: true };
if (!validPort(port)) return { text: _('Use a port from 1 to 65535.'), bad: true };
const who = holder(port, taken);
return who ? { text: `Used by ${who}. Choose another port.`, bad: true } : { text: free, bad: false };
return who ? { text: fmt(_('Used by %s. Choose another port.'), who), bad: true } : { text: free, bad: false };
}
/** The portal's TCP port; links on IP addresses (`ipLinks`) use plain HTTP on the next one too. */
export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean): Help {
const free = ipLinks ? `HTTPS here, plain HTTP for links on IP addresses on ${port + 1}.` : 'HTTPS on this port, opened on WAN.';
const free = ipLinks
? fmt(_('HTTPS here, plain HTTP for links on IP addresses on %s.'), port + 1)
: _('HTTPS on this port, opened on WAN.');
const h = portHelp(port, taken, free);
if (h.bad || !ipLinks) return h;
if (port === 65535) return { text: 'Links on IP addresses also need the next port: choose a lower one.', bad: true };
if (port === 65535) return { text: _('Links on IP addresses also need the next port: choose a lower one.'), bad: true };
const who = holder(port + 1, taken);
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
return who ? { text: fmt(_('Links on IP addresses also need %s, used by %s. Choose another port.'), port + 1, who), bad: true } : h;
}
/* ---------- other fields, mirroring the router's rules (dawnline.util, schema, core) ---------- */
@@ -100,23 +104,28 @@ export const chars = (s: string): number => Array.from(s).length;
const NAME_MAX = 48;
const BAD_NAME = /[<>"\\\u0000-\u001f\u007f]/;
/** "Up to 48 characters (50 now).": a name over its limit. */
const tooLong = (max: number, s: string): string =>
fmt(N_(max, 'Up to %s character (%s now).', 'Up to %s characters (%s now).'), num(max), num(chars(s)));
/**
* A name people see (util.valid_name): 1–48 characters, none of < > " \.
* `taken` are names already used where it must be unique (case-insensitive).
*/
export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
const t = s.trim();
if (!t) return { text: 'Enter a name.', bad: true };
if (chars(s) > NAME_MAX) return { text: `Up to ${NAME_MAX} characters (${chars(s)} now).`, bad: true };
if (BAD_NAME.test(s)) return { text: 'Names can’t contain < > " or \\.', bad: true };
if (taken.some((x) => x.toLowerCase() === t.toLowerCase())) return { text: `“${t}” already exists — pick another name.`, bad: true };
if (!t) return { text: _('Enter a name.'), bad: true };
if (chars(s) > NAME_MAX) return { text: tooLong(NAME_MAX, s), bad: true };
if (BAD_NAME.test(s)) return { text: _('Names can’t contain < > " or \\.'), bad: true };
if (taken.some((x) => x.toLowerCase() === t.toLowerCase()))
return { text: fmt(_('“%s” already exists - pick another name.'), t), bad: true };
return { text: good, bad: false };
}
/** A circle's name: like a name, up to 32 characters. */
export function circleNameHelp(s: string, taken: string[] = []): Help {
if (chars(s) > 32) return { text: `Up to 32 characters (${chars(s)} now).`, bad: true };
return nameHelp(s, taken, 'Shown on the person cards.');
if (chars(s) > 32) return { text: tooLong(32, s), bad: true };
return nameHelp(s, taken, _('Shown on the person cards.'));
}
const HOSTNAME = /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
@@ -138,24 +147,28 @@ export function isIpv6(s: string): boolean {
*/
export function hostHelp(s: string, port?: number, empty: string | null = null): Help {
const t = s.trim();
if (!t) return empty != null ? { text: empty, bad: false } : { text: 'Enter a hostname or IP address.', bad: true };
if (/^[a-z]+:\/\//i.test(t)) return { text: 'Leave out https:// — just the name.', bad: true };
if (/\/.*/.test(t)) return { text: 'Just the name, without a path.', bad: true };
if (/^[^:\[]+:\d+$/.test(t)) return { text: 'Just the name, without a port (the port is on AmneziaWG).', bad: true };
if (/\s/.test(t)) return { text: 'A hostname has no spaces.', bad: true };
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: 'Use a hostname or an IP address.', bad: true };
if (!t) return empty != null ? { text: empty, bad: false } : { text: _('Enter a hostname or IP address.'), bad: true };
if (/^[a-z]+:\/\//i.test(t)) return { text: _('Leave out https:// - just the name.'), bad: true };
if (/\/.*/.test(t)) return { text: _('Just the name, without a path.'), bad: true };
if (/^[^:\[]+:\d+$/.test(t)) return { text: _('Just the name, without a port (the port is on AmneziaWG).'), bad: true };
if (/\s/.test(t)) return { text: _('A hostname has no spaces.'), bad: true };
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: _('Use a hostname or an IP address.'), bad: true };
const shown = isIpv6(t) ? `[${t}]` : t;
return { text: port ? `Devices connect to ${shown}:${port}.` : `Links use ${shown}.`, bad: false };
return { text: port ? fmt(_('Devices connect to %s.'), `${shown}:${port}`) : fmt(_('Links use %s.'), shown), bad: false };
}
/** The DNS list a server hands to devices (rpc/servers.uc dns_list): IPs, comma-separated; empty = this router. */
export function dnsHelp(s: string, routerAddr: string): Help {
const items = s.split(/[ ,]+/).filter(Boolean);
if (!items.length)
return { text: `This router (${routerAddr}): queries go where your home network sends them, and home names work.`, bad: false };
return {
text: fmt(_('This router (%s): queries go where your home network sends them, and home names work.'), routerAddr),
bad: false,
};
const bad = items.find((x) => !isIpv4(x) && !isIpv6(x));
if (bad) return { text: `“${bad}” is not an IP address. Separate several with commas.`, bad: true };
return { text: `Devices use ${items.join(' and ')} — home names and your LAN’s DNS filters no longer apply to them.`, bad: false };
if (bad) return { text: fmt(_('“%s” is not an IP address. Separate several with commas.'), bad), bad: true };
const list = new Intl.ListFormat(locale(), { type: 'conjunction' }).format(items);
return { text: fmt(_('Devices use %s - home names and your LAN’s DNS filters no longer apply to them.'), list), bad: false };
}
/** MTU (rpc/servers.uc check_mtu): empty = automatic, else 1280–1500. */
@@ -163,42 +176,66 @@ export function mtuHelp(s: string, mtus: { computer: number; phone: number }): H
const t = s.trim();
if (!t)
return {
text: `Automatic by device type and disguise: ${mtus.computer} for computers and routers, ${mtus.phone} for phones and tablets.`,
text: fmt(
_('Automatic by device type and disguise: %s for computers and routers, %s for phones and tablets.'),
mtus.computer,
mtus.phone,
),
bad: false,
};
if (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)
return { text: 'MTU must be 1280–1500, or empty for automatic.', bad: true };
return { text: _('MTU must be 1280–1500, or empty for automatic.'), bad: true };
const n = Number(t);
return { text: `Computers and routers get ${n}, phones and tablets ${Math.min(n, 1280)}.`, bad: false };
return { text: fmt(_('Computers and routers get %s, phones and tablets %s.'), n, Math.min(n, 1280)), bad: false };
}
/** Keep-alive (rpc/servers.uc): 0–600 s; empty = 25. */
export function keepaliveHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'Default: a packet every 25 s keeps NAT open and “Connected” accurate.', bad: false };
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: 'Use 0–600 seconds.', bad: true };
if (Number(t) === 0) return { text: 'Off: NAT may close the tunnel when idle, and “Connected” lags.', bad: false };
return { text: `Devices send a packet every ${t} s to keep NAT open (a little battery on phones).`, bad: false };
if (!t) return { text: _('Default: a packet every 25 s keeps NAT open and “Connected” accurate.'), bad: false };
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: _('Use 0–600 seconds.'), bad: true };
if (Number(t) === 0) return { text: _('Off: NAT may close the tunnel when idle, and “Connected” lags.'), bad: false };
return { text: fmt(_('Devices send a packet every %s s to keep NAT open (a little battery on phones).'), t), bad: false };
}
/** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */
export function limitHelp(s: string, have = 0): Help {
const t = s.trim();
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: 'Use 1–32.', bad: true };
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: _('Use 1–32.'), bad: true };
const n = Number(t);
if (have > n)
return { text: `Already has ${have} devices: remove ${have - n === 1 ? 'one' : `${have - n}`} first, or allow more.`, bad: true };
return { text: `They can add ${n} device${n === 1 ? '' : 's'} themselves.`, bad: false };
return {
text:
have - n === 1
? fmt(
N_(
have,
'Already has %s device: remove one first, or allow more.',
'Already has %s devices: remove one first, or allow more.',
),
num(have),
)
: fmt(
N_(have, 'Already has %s device: remove %s first, or allow more.', 'Already has %s devices: remove %s first, or allow more.'),
num(have),
num(have - n),
),
bad: true,
};
return { text: plural(n, 'They can add %s device themselves.', 'They can add %s devices themselves.'), bad: false };
}
/** Monthly data in GB (core.create_person): empty = unlimited, else 0–100000. */
export function quotaHelp(s: string, monthly = true): Help {
const t = s.trim();
if (!t) return { text: 'Optional. No data limit.', bad: false };
if (!t) return { text: _('Optional. No data limit.'), bad: false };
const n = Number(t);
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: 'A number of GB, up to 100000.', bad: true };
if (n === 0) return { text: 'Optional. No data limit.', bad: false };
return { text: monthly ? `Paused after ${t} GB this month, resumed on the 1st.` : `Paused after ${t} GB in total.`, bad: false };
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: _('A number of GB, up to 100000.'), bad: true };
if (n === 0) return { text: _('Optional. No data limit.'), bad: false };
return {
text: fmt(monthly ? _('Paused after %s GB this month, resumed on the 1st.') : _('Paused after %s GB in total.'), num(n)),
bad: false,
};
}
/** An end date (YYYY-MM-DD) against the router's day; empty = none. */
@@ -209,64 +246,70 @@ export function expiresHelp(
date: (d: string) => string,
): Help {
const t = s.trim();
if (!t) return { text: 'Optional. No end date.', bad: false };
if (!t) return { text: _('Optional. No end date.'), bad: false };
const left = daysLeft(t, today);
if (left == null) return { text: 'Use a date.', bad: true };
if (left < 0) return { text: 'That date has passed: access would end at once.', bad: true };
return { text: left === 1 ? `Access ends today (${date(t)}).` : `Access ends in ${left} days (${date(t)}).`, bad: false };
if (left == null) return { text: _('Use a date.'), bad: true };
if (left < 0) return { text: _('That date has passed: access would end at once.'), bad: true };
return {
text:
left === 1
? fmt(_('Access ends today (%s).'), date(t))
: fmt(N_(left, 'Access ends in %s day (%s).', 'Access ends in %s days (%s).'), num(left), date(t)),
bad: false,
};
}
/** A home service's address (rpc/home.uc): IPv4; `homeNets` warn when it is outside every home network. */
export function ipv4Help(s: string, inHome: ((ip: string) => boolean) | null = null): Help {
const t = s.trim();
if (!t) return { text: 'The device’s address at home.', bad: true };
if (!isIpv4(t)) return { text: 'Use an IPv4 address, like 192.168.1.10.', bad: true };
if (inHome && !inHome(t)) return { text: `${t} is not in any home network of this server: nobody would reach it.`, bad: false };
if (!t) return { text: _('The device’s address at home.'), bad: true };
if (!isIpv4(t)) return { text: _('Use an IPv4 address, like 192.168.1.10.'), bad: true };
if (inHome && !inHome(t)) return { text: fmt(_('%s is not in any home network of this server: nobody would reach it.'), t), bad: false };
return { text: '', bad: false };
}
/** A service's ports: empty = all, else numbers 1–65535. */
export function portsHelp(s: string): Help {
const items = s.split(/[ ,]+/).filter(Boolean);
if (!items.length) return { text: 'All ports.', bad: false };
if (!items.length) return { text: _('All ports.'), bad: false };
const bad = items.find((x) => !/^\d{1,5}$/.test(x) || Number(x) < 1 || Number(x) > 65535);
if (bad) return { text: `“${bad}” is not a port (1–65535).`, bad: true };
return { text: `Port${items.length === 1 ? '' : 's'} ${items.join(', ')}.`, bad: false };
if (bad) return { text: fmt(_('“%s” is not a port (1–65535).'), bad), bad: true };
return { text: fmt(N_(items.length, 'Port %s.', 'Ports %s.'), items.join(', ')), bad: false };
}
/** The portal's redirect for unknown links (schema portal_redirect): a full http(s) URL, or empty. */
export function urlHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'Wrong links get a bare “Not found”.', bad: false };
if (!/^https?:\/\//i.test(t)) return { text: 'Must start with http:// or https://.', bad: true };
if (!t) return { text: _('Wrong links get a bare “Not found”.'), bad: false };
if (!/^https?:\/\//i.test(t)) return { text: _('Must start with http:// or https://.'), bad: true };
if (t.length > 300 || !/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(t))
return { text: 'Not a usable address (no spaces or quotes).', bad: true };
return { text: 'Wrong links are sent there instead of a “Not found”.', bad: false };
return { text: _('Not a usable address (no spaces or quotes).'), bad: true };
return { text: _('Wrong links are sent there instead of a “Not found”.'), bad: false };
}
/** The home domain for device hostnames (schema domain): lowercase letters, digits, dashes, dots. */
export function domainHelp(s: string, example = 'phone.myata'): Help {
const t = s.trim();
// Empty keeps the default (the router stores nothing then).
if (!t) return { text: `The default, lan: devices get names like ${example}.lan.`, bad: false };
if (!t) return { text: fmt(_('The default, lan: devices get names like %s.'), `${example}.lan`), bad: false };
if (!/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(t))
return { text: /[A-Z]/.test(t) ? 'Lowercase only.' : 'Lowercase letters, digits, dashes and dots.', bad: true };
return { text: `Devices get names like ${example}.${t}.`, bad: false };
return { text: /[A-Z]/.test(t) ? _('Lowercase only.') : _('Lowercase letters, digits, dashes and dots.'), bad: true };
return { text: fmt(_('Devices get names like %s.'), `${example}.${t}`), bad: false };
}
/** The fallback DNS for home-names devices: an IPv4 address, or empty for none. */
export function fallbackDnsHelp(s: string): Help {
const t = s.trim();
if (!t) return { text: 'None: without the tunnel those devices have no DNS.', bad: false };
if (!isIpv4(t)) return { text: 'Use an IPv4 address, or leave it empty.', bad: true };
return { text: `${t} takes over when the tunnel is down.`, bad: false };
if (!t) return { text: _('None: without the tunnel those devices have no DNS.'), bad: false };
if (!isIpv4(t)) return { text: _('Use an IPv4 address, or leave it empty.'), bad: true };
return { text: fmt(_('%s takes over when the tunnel is down.'), t), bad: false };
}
/** The daily update time (schema update_time): HH:MM. */
export function timeHelp(s: string): Help {
const t = s.trim();
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: 'Use HH:MM, 00:00–23:59.', bad: true };
return { text: `Runs within an hour after ${t} (router time).`, bad: false };
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: _('Use HH:MM, 00:00–23:59.'), bad: true };
return { text: fmt(_('Runs within an hour after %s (router time).'), t), bad: false };
}
/**
@@ -310,7 +353,7 @@ export function endpointProbe(
if (h.bad || !host.trim()) return h;
if (result && result.host === host.trim()) return { text: result.text, bad: result.bad };
const idle = opts.idle?.();
return { text: idle ? `${idle} Checking where it points…` : `${h.text} Checking where it points…`, bad: false };
return { text: `${idle || h.text} ${_('Checking where it points…')}`, bad: false };
};
return { help, schedule };
}
+35 -11
View File
@@ -4,47 +4,71 @@ import type { UpdateEvent } from '../../api';
import { E } from '../../e';
import { icon } from '../../../shared/icons';
import { ago, duration } from '../../../shared/format';
import { fill, locale, plural } from '../../../shared/i18n';
import { jobComponent } from '../../updater/jobs';
import { translationName } from './hero';
import type { ComponentsPage } from './index';
const NAMES: Record<string, string> = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', all: 'Components' };
function compName(comp: string): string {
if (comp === 'app') return 'Dawnline';
if (comp === 'amneziawg') return 'AmneziaWG';
return comp === 'pkgs' ? _('System packages') : _('Components');
}
/** A finding as the history keeps it: a component and version, or "2 system packages". */
function itemText(item: string): string {
const n = /^(\d+) system packages?$/.exec(item)?.[1];
return n ? plural(Number(n), '%s system package', '%s system packages') : item;
}
export function activity(page: ComponentsPage): HTMLElement {
const st = page.st;
const row = (e: UpdateEvent) => {
const comp = jobComponent(e.component ?? 'app');
const who = NAMES[comp] ?? 'Components';
const how = e.auto ? 'automatically' : 'by you';
const who = E('b', {}, compName(comp));
let tone = 'ok',
ic = 'check',
text: (Node | string)[];
if (e.kind === 'found') {
tone = 'accent';
ic = 'download';
text = [E('b', {}, (e.items ?? []).join(', ')), ` found by ${e.auto ? 'the automatic check' : 'a check'}`];
// The items are the router's words, kept in the history ("Dawnline 0.3.3", "2 system packages").
text = fill(
e.auto ? _('%s found by the automatic check') : _('%s found by a check'),
E('b', {}, (e.items ?? []).map(itemText).join(', ')),
);
} else if (e.state === 'failed') {
tone = 'bad';
ic = 'x';
text = [E('b', {}, who), ` ${e.kind === 'install' ? 'update' : 'check'} failed${e.error ? ` · ${e.error}` : ''}`];
text = [...fill(e.kind === 'install' ? _('%s update failed') : _('%s check failed'), who), e.error ? ` · ${e.error}` : ''];
} else if (/^app:(lang:|nolang$)/.test(e.component ?? '')) {
// The admin's translation, added or removed in Components.
const lang = /^app:lang:(.+)$/.exec(e.component ?? '')?.[1];
text = lang ? fill(_('%s added by you'), E('b', {}, translationName(lang))) : [_('Translation removed by you')];
} else {
const ver = e.from && e.to && e.from !== e.to ? ` ${e.from} → ${e.to}` : e.to ? ` ${e.to}` : '';
text = [E('b', {}, who), `${ver} ${ver ? '' : 'updated '}${how}${e.took ? ` · ${duration(e.took)}` : ''}`.replace(/\s+/g, ' ')];
const ver = e.from && e.to && e.from !== e.to ? `${e.from} → ${e.to}` : (e.to ?? '');
text = [
...(ver
? fill<Node | string>(e.auto ? _('%s %s automatically') : _('%s %s by you'), who, ver)
: fill(e.auto ? _('%s updated automatically') : _('%s updated by you'), who)),
e.took ? ` · ${duration(e.took)}` : '',
];
}
return E('div', { class: 'dl-row' }, [
E('span', { class: `dl-ev-tile ev ${tone}` }, icon(ic)),
E('span', { class: 'dl-row-main' }, text),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString() }, ago(e.ts, st.now)),
E('span', { class: 'dl-faint dl-nowrap', title: new Date(e.ts * 1000).toLocaleString(locale()) }, ago(e.ts, st.now)),
]);
};
const h = st.history ?? [];
return E('section', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('h3', {}, _('Activity')),
E('span', { class: 'dl-spacer' }),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'All in Log →'),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, _('All in Log →')),
]),
h.length
? E('div', {}, h.slice(0, 8).map(row))
: E('p', { class: 'dl-sub dl-comp-empty' }, 'Updates, and checks that found something, show up here.'),
: E('p', { class: 'dl-sub dl-comp-empty' }, _('Updates, and checks that found something, show up here.')),
]);
}
+62 -40
View File
@@ -8,6 +8,7 @@ import { confirmDialog } from '../../ui/modal';
import { sw } from '../../ui/controls';
import { pill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { fmt, num } from '../../../shared/i18n';
import { whatsNew } from '../../updater/notes';
import type { ComponentsPage, MenuEntry } from './index';
@@ -25,60 +26,72 @@ export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): N
const actions: MenuEntry[] = [];
if (cur && installed)
actions.push({
label: 'Reinstall this build',
label: _('Reinstall this build'),
warn: true,
ic: 'reset',
run: () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, 'Reinstalling AmneziaWG', installed),
run: () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, _('Reinstalling AmneziaWG'), installed),
});
if (kept)
actions.push({
label: `Roll back to ${kept.version}`,
label: fmt(_('Roll back to %s'), kept.version),
ic: 'archive',
warn: true,
run: async () => {
if (
await confirmDialog(
`Roll back AmneziaWG to ${kept.version}?`,
'The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.',
'Roll back',
fmt(_('Roll back AmneziaWG to %s?'), kept.version),
_('The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.'),
_('Roll back'),
)
)
void page.op('amneziawg:rollback', 'Rolling back AmneziaWG', installed ?? undefined);
void page.op('amneziawg:rollback', _('Rolling back AmneziaWG'), installed ?? undefined);
},
});
const menu: (MenuEntry | null)[] = [
w?.release
? {
label: 'What’s new',
label: _('What’s new'),
ic: 'file',
run: () => whatsNew('amneziawg', w.release!, `What’s new in the ${curSrc?.label ?? 'AmneziaWG'} build`, cur ?? 'slava'),
run: () => whatsNew('amneziawg', w.release!, fmt(_('What’s new in the %s build'), curSrc?.label ?? 'AmneziaWG'), cur ?? 'slava'),
}
: null,
{
label: 'Open on GitHub',
label: _('Open on GitHub'),
ic: 'globe',
run: () => window.open(`https://github.com/${curSrc?.repo ?? 'Slava-Shchipunov/awg-openwrt'}`, '_blank', 'noopener'),
},
...(actions.length ? [null, ...actions] : []),
].filter((x, k, a) => x !== null || (k > 0 && a[k - 1] !== null));
const tun = st.tunnels ?? [];
const restarts = tun.length
? `Switching restarts ${tun.length === 1 ? 'the tunnel' : `${tun.length} tunnels`} for a few seconds: ${tun.join(', ')}. Devices keep their configurations.`
: 'Switching takes a few seconds. Devices keep their configurations.';
const restarts = !tun.length
? _('Switching takes a few seconds. Devices keep their configurations.')
: tun.length === 1
? fmt(_('Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations.'), tun[0])
: fmt(
N_(
tun.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.',
),
num(tun.length),
tun.join(', '),
);
// The notice under the builds: "Switching restarts Home and Family for a few seconds."
const names = tun.length > 1 ? `${tun.slice(0, -1).join(', ')} and ${tun[tun.length - 1]}` : tun[0];
const notice = tun.length ? `Switching restarts ${names} for a few seconds.` : 'Switching takes a few seconds.';
const names = tun.length > 1 ? fmt(_('%s and %s'), tun.slice(0, -1).join(', '), tun[tun.length - 1]) : tun[0];
const notice = tun.length ? fmt(_('Switching restarts %s for a few seconds.'), names) : _('Switching takes a few seconds.');
const switchTo = async (id: AwgSource) => {
const x = srcs[id]!;
const ok = await confirmDialog(
installed ? `Switch to AmneziaWG ${x.gen}?` : `Install AmneziaWG ${x.gen}?`,
`The ${x.label} build, ${x.version}. ${restarts}${x.gen === '3.1' ? ' Devices need AmneziaVPN 3.1 or newer.' : ''}`,
installed ? 'Switch' : 'Install',
installed ? fmt(_('Switch to AmneziaWG %s?'), x.gen) : fmt(_('Install AmneziaWG %s?'), x.gen),
[fmt(_('The %s build, %s.'), x.label, x.version), restarts, x.gen === '3.1' ? _('Devices need AmneziaVPN 3.1 or newer.') : '']
.filter(Boolean)
.join(' '),
installed ? _('Switch') : _('Install'),
);
if (ok)
void page.op(
`amneziawg:${id}${ru ? ':ru' : ''}`,
installed ? `Switching to AmneziaWG ${x.gen}` : 'Installing AmneziaWG',
installed ? fmt(_('Switching to AmneziaWG %s'), x.gen) : _('Installing AmneziaWG'),
installed ?? undefined,
);
};
@@ -88,47 +101,51 @@ export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): N
return E('div', { class: 'dl-row' }, [
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, x.gen ? `AmneziaWG ${x.gen}` : 'AmneziaWG'),
E('span', { class: 'dl-sub' }, `${x.label} · ${x.gen === '3.1' ? 'AmneziaVPN 3.1+' : 'every app'}`),
E('span', { class: 'dl-sub' }, `${x.label} · ${x.gen === '3.1' ? 'AmneziaVPN 3.1+' : _('every app')}`),
]),
E('span', { class: 'dl-mono dl-faint dl-comp-bver' }, x.version ?? 'none yet'),
E('span', { class: 'dl-mono dl-faint dl-comp-bver' }, x.version ?? _('none yet')),
E(
'span',
{ class: 'dl-comp-bact' },
on
? pill('ok', 'Active')
? pill('ok', _('Active', 'build'))
: x.version
? button(installed ? 'Switch' : 'Install', () => switchTo(id), installed ? 'neutral' : 'positive', { disabled: page.busy })
: pill('', 'No build'),
? button(installed ? _('Switch') : _('Install'), () => switchTo(id), installed ? 'neutral' : 'positive', {
disabled: page.busy,
})
: pill('', _('No build')),
),
]);
};
const newer = ids
.map((id) =>
srcs[id]?.newer ? `${srcs[id]!.label} moves to ${srcs[id]!.newer!.gen} with OpenWrt ${srcs[id]!.newer!.tag.replace(/^v/, '')}.` : '',
srcs[id]?.newer
? fmt(_('%s moves to %s with OpenWrt %s.'), srcs[id]!.label, srcs[id]!.newer!.gen, srcs[id]!.newer!.tag.replace(/^v/, ''))
: '',
)
.filter(Boolean);
const ruSw = sw(ru, 'Russian translation', (v) => {
const ruSw = sw(ru, _('Russian translation'), (v) => {
if (!cur) return;
void page.op(
`amneziawg:${cur}${v ? ':ru' : ''}`,
v ? 'Adding the Russian translation' : 'Removing the Russian translation',
v ? _('Adding the Russian translation') : _('Removing the Russian translation'),
installed ?? undefined,
);
});
ruSw.disabled = !cur || !installed || page.busy;
const open = page.awgOpen ?? !installed;
const fold = E('details', { class: 'dl-params dl-comp-fold', open: open ? 'open' : null }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Build and translation')]),
E('summary', {}, [icon('chevron'), E('span', {}, _('Build and translation'))]),
E('div', { class: 'dl-params-body' }, [
// The builds and the translation in one list.
E('div', { class: 'dl-list' }, [
...(ids.length
? ids.map(build)
: [E('div', { class: 'dl-row' }, E('span', { class: 'dl-sub' }, 'Check for updates to see the builds for this router.'))]),
: [E('div', { class: 'dl-row' }, E('span', { class: 'dl-sub' }, _('Check for updates to see the builds for this router.')))]),
E('div', { class: 'dl-row' }, [
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, 'Russian translation'),
E('span', { class: 'dl-sub' }, 'LuCI pages for AmneziaWG'),
E('b', {}, _('Russian translation')),
E('span', { class: 'dl-sub' }, _('LuCI pages for AmneziaWG')),
]),
E('span', { class: 'dl-comp-bact' }, ruSw),
]),
@@ -146,24 +163,29 @@ export function awgRows(page: ComponentsPage, w: UpdateComponent | undefined): N
const right: Node[] = [];
if (w?.update && installed && cur)
right.push(
button(`Update to ${w.latest}`, () => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, 'Updating AmneziaWG', installed), 'neutral', {
disabled: page.busy,
}),
button(
fmt(_('Update to %s'), w.latest),
() => page.op(`amneziawg:${cur}${ru ? ':ru' : ''}`, _('Updating AmneziaWG'), installed),
'neutral',
{
disabled: page.busy,
},
),
);
else right.push((w || missing.length) && !installed ? pill('warn', 'Not installed') : page.state('amneziawg', w, w?.latest ?? ''));
right.push(page.round(() => page.op('check:amneziawg', 'Checking AmneziaWG', installed ?? undefined), menu));
else right.push((w || missing.length) && !installed ? pill('warn', _('Not installed')) : page.state('amneziawg', w, w?.latest ?? ''));
right.push(page.round(() => page.op('check:amneziawg', _('Checking AmneziaWG'), installed ?? undefined), menu));
return [
page.row(
'shield',
'AmneziaWG',
[
installed
? `${installed}${w?.release ? ` · ${w.release} build` : ''}`
? `${installed}${w?.release ? ` · ${fmt(_('%s build'), w.release)}` : ''}`
: missing.length
? `missing ${missing.join(', ')}`
? fmt(_('missing %s'), missing.join(', '))
: w
? 'not installed'
: 'version not checked',
? _('not installed')
: _('version not checked'),
],
right,
),
+114 -53
View File
@@ -1,19 +1,30 @@
// Components → the Dawnline block: version, what the update brings, its
// settings at a glance, and every release to install (Versions).
// settings at a glance, every release to install (Versions) and the admin's
// translation.
import { E } from '../../e';
import { api, type UpdateComponent } from '../../api';
import { button, iconButton } from '../../ui/button';
import { confirmDialog } from '../../ui/modal';
import { errorText, notify } from '../../ui/toast';
import { input } from '../../ui/controls';
import { input, sw } from '../../ui/controls';
import { pill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago, duration, fmtDay } from '../../../shared/format';
import { fmt, plural } from '../../../shared/i18n';
import { whatsNew } from '../../updater/notes';
import type { ComponentsPage, MenuEntry } from './index';
const EVERY: Record<string, string> = { '6h': 'every 6 h', '12h': 'every 12 h', '1d': 'daily', '7d': 'weekly' };
/** How often Settings → Updates checks, by its interval id. */
function checksEvery(interval: string): string {
const t: Record<string, string> = {
'6h': _('checks every 6 h'),
'12h': _('checks every 12 h'),
'1d': _('checks daily'),
'7d': _('checks weekly'),
};
return t[interval] ?? t['1d'];
}
/** A release date (GitHub gives a timestamp). */
const released = (d: string | null | undefined) => (d ? fmtDay(d) : '');
@@ -34,7 +45,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
const pol = st.policy;
const kept = st.kept?.app;
const tag = a?.update && a.tag ? a.tag : st.version;
const notesOf = (t: string) => () => whatsNew('app', t, `What’s new in Dawnline ${t.replace(/^v/, '')}`);
const notesOf = (t: string) => () => whatsNew('app', t, fmt(_('What’s new in Dawnline %s'), t.replace(/^v/, '')));
// What the offered release brings, or what the installed one brought when it is the latest.
const items = a?.tag && (a.update || a.status === 'latest') ? bullets(page, a.tag, a.update ? st.version : '') : null;
const ptag = a?.tag ?? tag;
@@ -43,29 +54,29 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
const side = (label: string, value: (Node | string)[]) =>
E('div', { class: 'dl-stack gap4' }, [E('span', { class: 'dl-metric-label' }, label), E('span', { class: 'dl-comp-side-v' }, value)]);
const menu: (MenuEntry | null)[] = [
{ label: 'What’s new', ic: 'file', run: notesOf(tag) },
{ label: 'Open on GitHub', ic: 'globe', run: () => window.open(`https://github.com/${st.repo}`, '_blank', 'noopener') },
{ label: _('What’s new'), ic: 'file', run: notesOf(tag) },
{ label: _('Open on GitHub'), ic: 'globe', run: () => window.open(`https://github.com/${st.repo}`, '_blank', 'noopener') },
null,
{
label: `Reinstall ${st.version}`,
label: fmt(_('Reinstall %s'), st.version),
ic: 'reset',
warn: true,
run: () => page.op('app:reinstall', 'Reinstalling Dawnline', st.version),
run: () => page.op('app:reinstall', _('Reinstalling Dawnline'), st.version),
},
kept
? {
label: `Roll back to ${kept.version}`,
label: fmt(_('Roll back to %s'), kept.version),
ic: 'archive',
warn: true,
run: async () => {
if (
await confirmDialog(
`Roll back to Dawnline ${kept.version}?`,
`The copy kept on the router replaces ${st.version}. A backup of the settings is made first.`,
'Roll back',
fmt(_('Roll back to Dawnline %s?'), kept.version),
fmt(_('The copy kept on the router replaces %s. A backup of the settings is made first.'), st.version),
_('Roll back'),
)
)
void page.op('app:rollback', 'Rolling back Dawnline', st.version);
void page.op('app:rollback', _('Rolling back Dawnline'), st.version);
},
}
: null,
@@ -77,7 +88,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
E('b', { class: 'dl-comp-name' }, 'Dawnline'),
page.state('app', a, a?.latest ?? ''),
E('span', { class: 'dl-spacer' }),
page.round(() => page.op('check:app', 'Checking Dawnline', st.version), menu, true),
page.round(() => page.op('check:app', _('Checking Dawnline'), st.version), menu, true),
]),
// Version, what it is, and the update: one line.
E('div', { class: 'dl-comp-verrow' }, [
@@ -87,7 +98,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
a?.update
? E('small', {}, `→ ${a.latest}`)
: a?.status === 'dev' && a.latest
? E('small', { class: 'dl-faint' }, `release ${a.latest}`)
? E('small', { class: 'dl-faint' }, fmt(_('release %s'), a.latest))
: '',
]),
E(
@@ -97,13 +108,13 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
? ''
: a?.update
? a.published
? `released ${released(a.published)}`
? fmt(_('released %s'), released(a.published))
: ''
: a?.status === 'dev'
? 'ahead of the latest release'
? _('ahead of the latest release')
: a
? `latest release${a.published ? ` · released ${released(a.published)}` : ''}`
: 'not checked yet',
? [_('latest release'), a.published ? fmt(_('released %s'), released(a.published)) : ''].filter(Boolean).join(' · ')
: _('not checked yet'),
),
]),
]),
@@ -119,7 +130,7 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
? E(
'button',
{ type: 'button', class: 'dl-linkbtn dl-comp-more', click: notesOf(ptag) },
`+${items.total - items.items.length} more in What’s new`,
plural(items.total - items.items.length, '+%s more in What’s new', '+%s more in What’s new'),
)
: '',
])
@@ -128,42 +139,43 @@ export function hero(page: ComponentsPage, a: UpdateComponent | undefined): HTML
// The update and its notes; without an update What's new stays in ⋯.
a?.update
? E('div', { class: 'dl-comp-btns' }, [
button('Update now', () => page.op('app', 'Updating Dawnline', st.version), 'positive', { disabled: page.busy }),
button('What’s new', notesOf(tag)),
button(_('Update now'), () => page.op('app', _('Updating Dawnline'), st.version), 'positive', { disabled: page.busy }),
button(_('What’s new'), notesOf(tag)),
])
: '',
versions(page),
translation(page),
]),
E('div', { class: 'dl-comp-hero-side' }, [
side('Source', [icon('globe'), E('a', { href: `https://github.com/${st.repo}`, target: '_blank', rel: 'noopener' }, st.repo)]),
side('Auto-update', [
pol.auto ? pill('ok', 'On') : pill('', 'Off'),
side(_('Source'), [icon('globe'), E('a', { href: `https://github.com/${st.repo}`, target: '_blank', rel: 'noopener' }, st.repo)]),
side(_('Auto-update'), [
pol.auto ? pill('ok', _('On')) : pill('', _('Off')),
E(
'span',
{ class: 'dl-muted' },
pol.auto
? pol.mode === 'immediate'
? 'as soon as found'
: `${EVERY[pol.interval] === 'weekly' ? 'weekly' : 'daily'} at ${pol.time}`
? _('as soon as found')
: fmt(pol.interval === '7d' ? _('weekly at %s') : _('daily at %s'), pol.time)
: pol.check
? `checks ${EVERY[pol.interval]}`
: 'checks off',
? checksEvery(pol.interval)
: _('checks off'),
),
]),
side(
'Last check',
_('Last check'),
st.check
? [
ago(st.check.time, st.now),
nextCheck > st.now ? E('span', { class: 'dl-faint' }, `· next in ${duration(nextCheck - st.now)}`) : '',
nextCheck > st.now ? E('span', { class: 'dl-faint' }, `· ${fmt(_('next in %s'), duration(nextCheck - st.now))}`) : '',
]
: ['Never'],
: [_('Never')],
),
side(
'Rollback',
_('Rollback'),
kept
? [E('span', { class: 'dl-mono' }, kept.version), E('span', { class: 'dl-faint' }, 'kept on flash')]
: [E('span', { class: 'dl-muted' }, pol.keep ? 'Kept after the next update' : 'Off')],
? [E('span', { class: 'dl-mono' }, kept.version), E('span', { class: 'dl-faint' }, _('kept on flash'))]
: [E('span', { class: 'dl-muted' }, pol.keep ? _('Kept after the next update') : _('Off'))],
),
]),
]);
@@ -191,10 +203,52 @@ function bullets(page: ComponentsPage, tag: string, from: string): { items: stri
return null;
}
/** A translation's name, by its language code. */
export function translationName(lang: string): string {
return lang === 'ru' ? _('Russian translation') : lang;
}
/**
* The admin's translation, switched like AmneziaWG's: luci-i18n-dawnline-ru
* from the release of the installed version (the updater installs and
* removes it, then LuCI's web server restarts to read it).
*/
function translation(page: ComponentsPage): HTMLElement {
const ru = (page.st.translations ?? []).includes('ru');
const s = sw(ru, translationName('ru'), (v) => {
void page.op(
v ? 'app:lang:ru' : 'app:nolang',
v ? _('Adding the Russian translation') : _('Removing the Russian translation'),
page.st.version,
);
});
s.disabled = page.busy;
const fold = E('details', { class: 'dl-params dl-comp-fold', open: page.langOpen ? 'open' : null }, [
E('summary', {}, [
icon('chevron'),
E('span', {}, _('Translation')),
E('span', { class: 'dl-sub' }, ru ? _('Russian') : _('English only')),
]),
E('div', { class: 'dl-params-body' }, [
E('div', { class: 'dl-list' }, [
E('div', { class: 'dl-row' }, [
E('span', { class: 'dl-row-main dl-stack' }, [
E('b', {}, translationName('ru')),
E('span', { class: 'dl-sub' }, _('LuCI pages for Dawnline')),
]),
E('span', { class: 'dl-comp-bact' }, s),
]),
]),
]),
]);
fold.addEventListener('toggle', () => (page.langOpen = (fold as HTMLDetailsElement).open));
return fold;
}
function versions(page: ComponentsPage): HTMLElement {
const body = E('div', { class: 'dl-params-body' });
const fold = E('details', { class: 'dl-params dl-comp-vers', open: page.versOpen ? 'open' : null }, [
E('summary', {}, [icon('chevron'), E('span', {}, 'Versions'), E('span', { class: 'dl-sub' }, 'install any release')]),
E('summary', {}, [icon('chevron'), E('span', {}, _('Versions')), E('span', { class: 'dl-sub' }, _('install any release'))]),
body,
]);
fold.addEventListener('toggle', () => {
@@ -206,10 +260,10 @@ function versions(page: ComponentsPage): HTMLElement {
}
async function paintVersions(page: ComponentsPage, body: HTMLElement) {
const tag = input('', { placeholder: 'Tag, e.g. 0.3.1', class: 'cbi-input-text dl-mono', 'aria-label': 'Release tag' });
const tag = input('', { placeholder: _('Tag, e.g. 0.3.1'), class: 'cbi-input-text dl-mono', 'aria-label': _('Release tag') });
const installTag = (t: string) => {
t = t.trim();
if (!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(t)) return notify('Enter a release tag like 0.3.1', 'warning');
if (!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(t)) return notify(_('Enter a release tag like 0.3.1'), 'warning');
void install(page, t);
};
tag.addEventListener('keydown', (ev: KeyboardEvent) => {
@@ -220,7 +274,7 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
});
const head = E('div', { class: 'dl-comp-tag' }, [
tag,
button('Install', () => installTag(tag.value), 'neutral', { disabled: page.busy }),
button(_('Install'), () => installTag(tag.value), 'neutral', { disabled: page.busy }),
]);
const pageNo = page.versPage;
const turn = (d: number) => {
@@ -229,13 +283,13 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
};
const pager = (more: boolean) =>
E('div', { class: 'dl-comp-pager' }, [
E('button', { type: 'button', class: 'dl-linkbtn', disabled: pageNo <= 1 ? 'disabled' : null, click: () => turn(-1) }, '← Newer'),
E('span', { class: 'dl-faint' }, `Page ${pageNo}`),
E('button', { type: 'button', class: 'dl-linkbtn', disabled: more ? null : 'disabled', click: () => turn(1) }, 'Older →'),
E('button', { type: 'button', class: 'dl-linkbtn', disabled: pageNo <= 1 ? 'disabled' : null, click: () => turn(-1) }, _('← Newer')),
E('span', { class: 'dl-faint' }, fmt(_('Page %s'), pageNo)),
E('button', { type: 'button', class: 'dl-linkbtn', disabled: more ? null : 'disabled', click: () => turn(1) }, _('Older →')),
]);
let rows = page.versCache.get(pageNo);
if (!rows) {
dom.content(body, [head, E('p', { class: 'dl-muted dl-loading' }, 'Loading versions…')]);
dom.content(body, [head, E('p', { class: 'dl-muted dl-loading' }, _('Loading versions…'))]);
try {
rows = (await api.updatesReleases(pageNo)).releases;
} catch (e) {
@@ -244,8 +298,8 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
dom.content(body, [
head,
E('div', { class: 'dl-row-actions' }, [
E('span', { class: 'dl-muted' }, `Failed to load versions: ${errorText(e)}`),
button('Try again', () => paintVersions(page, body)),
E('span', { class: 'dl-muted' }, fmt(_('Failed to load versions: %s'), errorText(e))),
button(_('Try again'), () => paintVersions(page, body)),
]),
pager(false),
]);
@@ -255,7 +309,11 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
if (pageNo !== page.versPage || !body.isConnected) return;
}
if (!rows.length)
return dom.content(body, [head, E('p', { class: 'dl-muted' }, pageNo > 1 ? 'No more versions.' : 'No versions found.'), pager(false)]);
return dom.content(body, [
head,
E('p', { class: 'dl-muted' }, pageNo > 1 ? _('No more versions.') : _('No versions found.')),
pager(false),
]);
const cur = page.st.version;
dom.content(body, [
head,
@@ -264,13 +322,13 @@ async function paintVersions(page: ComponentsPage, body: HTMLElement) {
return E('div', { class: 'dl-comp-ver' }, [
E('span', { class: 'dl-mono' }, v),
E('span', { class: 'dl-sub' }, released(r.published)),
r.prerelease ? pill('warn', 'Pre-release') : '',
r.prerelease ? pill('warn', _('Pre-release')) : '',
E(
'span',
{ class: 'dl-comp-ic' },
iconButton('file', 'What’s new', () => whatsNew('app', r.tag, `What’s new in Dawnline ${v}`)),
iconButton('file', _('What’s new'), () => whatsNew('app', r.tag, fmt(_('What’s new in Dawnline %s'), v))),
),
v === cur ? pill('ok', 'Installed') : button('Install', () => install(page, r.tag), 'neutral', { disabled: page.busy }),
v === cur ? pill('ok', _('Installed')) : button(_('Install'), () => install(page, r.tag), 'neutral', { disabled: page.busy }),
]);
}),
pager(rows.length >= 5),
@@ -284,11 +342,14 @@ async function install(page: ComponentsPage, tag: string) {
if (
older &&
!(await confirmDialog(
`Install Dawnline ${v}?`,
`It is older than ${page.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,
'Install',
fmt(_('Install Dawnline %s?'), v),
fmt(
_('It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong.'),
page.st.version,
),
_('Install'),
))
)
return;
void page.op(`app@${tag}`, `Installing Dawnline ${v}`, page.st.version);
void page.op(`app@${tag}`, fmt(_('Installing Dawnline %s'), v), page.st.version);
}
+38 -31
View File
@@ -13,6 +13,7 @@ import { attachTip } from '../../ui/tooltip';
import { pill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago } from '../../../shared/format';
import { fmt, num, plural } from '../../../shared/i18n';
import { runOperation } from '../../updater/operation';
import { jobComponent, runningComponent } from '../../updater/jobs';
import { hero } from './hero';
@@ -44,6 +45,8 @@ export class ComponentsPage {
notes = new Map<string, { items: string[]; total: number } | null>();
/** The AmneziaWG "Build and translation" fold, once opened or closed by hand. */
awgOpen: boolean | null = null;
/** Dawnline's Translation fold. */
langOpen = false;
load() {
return api.updatesStatus();
@@ -85,7 +88,7 @@ export class ComponentsPage {
/** Run `what` in the operation modal; the cards refresh when it ends. */
async op(what: string, title: string, version?: string) {
if (this.busy || this.following === 'starting') {
notify('Another component action is already running', 'warning');
notify(_('Another component action is already running'), 'warning');
return;
}
this.following = 'starting';
@@ -101,10 +104,10 @@ export class ComponentsPage {
if (comp === 'amneziawg' && c.amneziawg?.current)
void this.op(
`amneziawg:${c.amneziawg.current}${c.amneziawg.ru ? ':ru' : ''}`,
'Updating AmneziaWG',
_('Updating AmneziaWG'),
c.amneziawg.installed ?? undefined,
);
else void this.op('app', 'Updating Dawnline', this.st.version);
else void this.op('app', _('Updating Dawnline'), this.st.version);
},
});
if (this.following === 'starting') this.following = job?.id ?? null;
@@ -113,14 +116,17 @@ export class ComponentsPage {
async follow(job: UpdateJob) {
this.following = job.id;
const comp = runningComponent(job);
const what =
({ app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'system packages', all: 'components' } as Record<string, string>)[comp] ??
'components';
// [check, automatic update, update] per component.
const titles: Record<string, string[]> = {
app: [_('Checking Dawnline'), _('Automatic update: Dawnline'), _('Updating Dawnline')],
amneziawg: [_('Checking AmneziaWG'), _('Automatic update: AmneziaWG'), _('Updating AmneziaWG')],
pkgs: [_('Checking system packages'), _('Automatic update: system packages'), _('Updating system packages')],
all: [_('Checking components'), _('Automatic update: components'), _('Updating components')],
};
await runOperation(
null,
{
title: `${job.action === 'check' ? 'Checking' : job.auto ? 'Automatic update:' : 'Updating'} ${what}`,
title: (titles[runningComponent(job)] ?? titles.all)[job.action === 'check' ? 0 : job.auto ? 1 : 2],
onDone: (s) => this.refresh(s),
},
job,
@@ -139,13 +145,13 @@ export class ComponentsPage {
dom.content(this.root, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [
E('h2', { class: 'dl-h1' }, 'Components'),
E('h2', { class: 'dl-h1' }, _('Components')),
E(
'span',
{ class: 'dl-faint' },
[
fw?.version ? `OpenWrt ${fw.version} · ${fw.target}` : '',
st.check ? `checked ${ago(st.check.time, st.now)}` : 'not checked yet',
st.check ? fmt(_('checked %s'), ago(st.check.time, st.now)) : _('not checked yet'),
]
.filter(Boolean)
.join(' · '),
@@ -155,29 +161,31 @@ export class ComponentsPage {
E(
'a',
{ class: 'cbi-button cbi-button-neutral dl-icon-btn', href: `${L.url('admin/network/dawnline/settings')}?section=updates` },
[icon('edit'), ' Settings'],
[icon('edit'), ' ', _('Settings')],
),
button([icon('refresh'), ' Check all'], () => this.op('check', 'Checking all components'), 'neutral', { disabled: this.busy }),
button([icon('refresh'), ' ', _('Check all')], () => this.op('check', _('Checking all components')), 'neutral', {
disabled: this.busy,
}),
]),
]),
hero(this, c.app),
E('div', { class: 'dl-comp-cols' }, [
E('section', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Components'),
E('h3', {}, _('Components')),
E('span', { class: 'dl-spacer' }),
E(
'span',
{ class: 'dl-faint dl-comp-count' },
awgMissing
? n
? `AmneziaWG not installed · ${n} update${n === 1 ? '' : 's'}`
: 'AmneziaWG not installed'
? `${_('AmneziaWG not installed')} · ${plural(n, '%s update', '%s updates')}`
: _('AmneziaWG not installed')
: !c.amneziawg && !c.packages
? ''
: n
? `${n} of ${1 + pk.total} need${n === 1 ? 's' : ''} an update`
: 'Everything is up to date',
? fmt(N_(n, '%s of %s needs an update', '%s of %s need an update'), num(n), num(1 + pk.total))
: _('Everything is up to date'),
),
]),
E('div', {}, [...awgRows(this, c.amneziawg), ...pk.rows]),
@@ -194,16 +202,15 @@ export class ComponentsPage {
const norm = (v: string) => (v === 'packages' ? 'pkgs' : v);
const comps = j.action === 'check' ? [norm(j.component || 'all')] : (j.component ?? '').split(' ').map((v) => norm(jobComponent(v)));
if (comps.includes(comp) || comps.includes('all'))
return E('button', { type: 'button', class: 'dl-pill info dl-comp-run', title: 'Show progress', click: () => this.follow(j) }, [
j.action === 'check' ? 'Checking' : 'Updating',
'…',
return E('button', { type: 'button', class: 'dl-pill info dl-comp-run', title: _('Show progress'), click: () => this.follow(j) }, [
j.action === 'check' ? _('Checking…') : _('Updating…'),
]);
}
if (!x) return pill('', 'Not checked');
if (x.error) return pill('warn', 'Check failed', x.error);
if (x.update) return pill('info', 'Update available');
if (x.status === 'dev') return pill('info', 'Newer than release', `The latest release is ${latest}`);
return pill('ok', 'Up to date');
if (!x) return pill('', _('Not checked'));
if (x.error) return pill('warn', _('Check failed'), x.error);
if (x.update) return pill('info', _('Update available'));
if (x.status === 'dev') return pill('info', _('Newer than release'), fmt(_('The latest release is %s'), latest));
return pill('ok', _('Up to date'));
}
/** ⋯ menu; null is a separator. Actions refuse to start while a job runs (see op). */
@@ -219,7 +226,7 @@ export class ComponentsPage {
.map((x) => (x ? { label: x.label, icon: icon(x.ic), warn: x.warn, run: x.run } : null)),
),
'neutral',
{ title: 'More', 'aria-label': 'More' },
{ title: _('More'), 'aria-label': _('More') },
);
return b;
}
@@ -229,16 +236,16 @@ export class ComponentsPage {
const busy = this.busy ? ' is-busy' : '';
let btn: HTMLButtonElement;
if (label)
btn = button([icon('refresh'), ' Check'], check, 'neutral', {
btn = button([icon('refresh'), ' ', _('Check')], check, 'neutral', {
class: `cbi-button cbi-button-neutral dl-comp-check${busy}`,
'aria-label': 'Check for updates',
'aria-label': _('Check for updates'),
});
else {
btn = iconButton('refresh', 'Check for updates', check, 'neutral', busy.trim());
btn = iconButton('refresh', _('Check for updates'), check, 'neutral', busy.trim());
// Dawnline's own tooltip (the browser's title tip is slow and plain).
btn.removeAttribute('title');
btn.setAttribute('aria-label', 'Check for updates');
attachTip(btn, () => ['Check for updates']);
btn.setAttribute('aria-label', _('Check for updates'));
attachTip(btn, () => [_('Check for updates')]);
}
return E('span', { class: 'dl-comp-ic' }, [btn, this.more(menu)]);
}
+39 -23
View File
@@ -5,38 +5,49 @@ import type { UpdateComponent } from '../../api';
import { button } from '../../ui/button';
import { confirmDialog } from '../../ui/modal';
import { E } from '../../e';
import { fmt } from '../../../shared/i18n';
import type { ComponentsPage, MenuEntry } from './index';
const SYS_ITEMS: { title: string; sub: string; pkgs: string[]; feature: 'home' | 'https' | 'acme'; optional?: boolean }[] = [
{ title: 'Home-like link', sub: 'Policy routing and the veth pair', pkgs: ['ip-full', 'kmod-veth'], feature: 'home' },
{ title: 'HTTPS for the portal', sub: 'OpenSSL for uhttpd', pkgs: ['libustream-openssl', 'openssl-util'], feature: 'https' },
{
title: 'Certificates (ACME)',
sub: 'Let’s Encrypt certificate for the portal',
pkgs: ['acme', 'acme-acmesh-dnsapi'],
feature: 'acme',
optional: true,
},
];
interface SysItem {
title: string;
sub: string;
pkgs: string[];
feature: 'home' | 'https' | 'acme';
optional?: boolean;
}
function sysItems(): SysItem[] {
return [
{ title: _('Home-like link'), sub: _('Policy routing and the veth pair'), pkgs: ['ip-full', 'kmod-veth'], feature: 'home' },
{ title: _('HTTPS for the portal'), sub: _('OpenSSL for uhttpd'), pkgs: ['libustream-openssl', 'openssl-util'], feature: 'https' },
{
title: _('Certificates (ACME)'),
sub: _('Let’s Encrypt certificate for the portal'),
pkgs: ['acme', 'acme-acmesh-dnsapi'],
feature: 'acme',
optional: true,
},
];
}
const ICONS: Record<string, string> = { home: 'network', https: 'lock', acme: 'file' };
export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined): { rows: Node[]; updates: number; total: number } {
const st = page.st;
const pkgs = p?.pkgs ?? {};
const items = SYS_ITEMS.filter((it) => (it.feature === 'home' ? st.home : st.portal));
const items = sysItems().filter((it) => (it.feature === 'home' ? st.home : st.portal));
const runPkgs = async (names: string[], what: string, shown = names) => {
const ok = await confirmDialog(
`Update ${what}?`,
`${shown.join(', ')} from the OpenWrt feeds. Services that use them restart for a moment.`,
'Update',
fmt(_('Update %s?'), what),
fmt(_('%s from the OpenWrt feeds. Services that use them restart for a moment.'), shown.join(', ')),
_('Update'),
);
if (ok) void page.op(`pkgs:${names.join(',')}`, `Updating ${what}`);
if (ok) void page.op(`pkgs:${names.join(',')}`, fmt(_('Updating %s'), what));
};
const menu: (MenuEntry | null)[] = [
{ label: 'Check system packages', ic: 'refresh', run: () => page.op('check:packages', 'Checking system packages') },
{ label: _('Check system packages'), ic: 'refresh', run: () => page.op('check:packages', _('Checking system packages')) },
{
label: 'Open the OpenWrt package list',
label: _('Open the OpenWrt package list'),
ic: 'globe',
run: () => window.open('https://openwrt.org/packages/start', '_blank', 'noopener'),
},
@@ -52,11 +63,16 @@ export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined
return page.row(
ICONS[it.feature],
it.title,
[`${it.optional ? 'not installed' : `missing ${lacks.join(', ')}`}`],
[it.optional ? _('not installed') : fmt(_('missing %s'), lacks.join(', '))],
[
button('Install', () => page.op(`pkgs:${lacks.join(',')}`, `Installing ${it.title}`), it.optional ? 'neutral' : 'positive', {
disabled: page.busy,
}),
button(
_('Install'),
() => page.op(`pkgs:${lacks.join(',')}`, fmt(_('Installing %s'), it.title)),
it.optional ? 'neutral' : 'positive',
{
disabled: page.busy,
},
),
E('span', { class: 'dl-comp-ic' }, page.more(menu)),
],
);
@@ -68,7 +84,7 @@ export function packageRows(page: ComponentsPage, p: UpdateComponent | undefined
main ? [`${pkgs[main]!.installed} → ${pkgs[main]!.latest}`, upd.length > 1 ? ` · +${upd.length - 1}` : ''] : [upd.join(', ')],
[
button(
'Update',
_('Update'),
() =>
runPkgs(
present.filter((x) => pkgs[x]?.latest || pkgs[x]?.with?.length),
+32 -20
View File
@@ -9,6 +9,7 @@ import { sw, setSwitch } from '../../ui/controls';
import { callout } from '../../ui/layout';
import { icon } from '../../../shared/icons';
import { ago, clock } from '../../../shared/format';
import { fmt, num, plural } from '../../../shared/i18n';
import { isProblem, type LogItem } from '../../events/model';
import { eventRow, systemRow } from '../../events/render';
import { fixAction, runFix } from '../../widgets/health';
@@ -59,8 +60,8 @@ export class HealthTab {
if (!checks) {
dom.content(this.summary, '');
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks')]),
E('p', { class: 'dl-muted dl-loading' }, 'Running checks…'),
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Checks'))]),
E('p', { class: 'dl-muted dl-loading' }, _('Running checks…')),
]);
return;
}
@@ -69,16 +70,16 @@ export class HealthTab {
dom.content(
this.summary,
bad
? callout('error', `${bad} problem${bad > 1 ? 's' : ''} need attention.`)
? callout('error', plural(bad, '%s problem needs attention.', '%s problems need attention.'))
: warn
? callout('warn', `${warn} warning${warn > 1 ? 's' : ''}.`)
: callout('ok', 'All checks passed.'),
? callout('warn', plural(warn, '%s warning.', '%s warnings.'))
: callout('ok', _('All checks passed.')),
);
const repaired = new Map<string, number>();
for (const x of this.sl.watchdog.repairs) repaired.set(x.id, Math.max(repaired.get(x.id) ?? 0, x.ts));
const refresh = () => this.run();
dom.content(this.checksEl, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Checks'), E('span', { class: 'dl-spacer' }), button('Run again', refresh)]),
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Checks')), E('span', { class: 'dl-spacer' }), button(_('Run again'), refresh)]),
E(
'ul',
{ class: 'dl-checks' },
@@ -86,10 +87,11 @@ export class HealthTab {
E('li', {}, [
E('span', { class: `dl-check-icon ${c.status}` }, icon(ICON[c.status])),
E('div', { class: 'dl-check-body' }, [
// The check's title and detail come from the router.
E('div', { class: 'dl-check-title' }, c.title),
E('div', { class: 'dl-check-detail' }, c.detail),
repaired.has(c.id)
? E('div', { class: 'dl-check-repaired' }, `Repaired by the watchdog at ${clock(repaired.get(c.id)!)}`)
? E('div', { class: 'dl-check-repaired' }, fmt(_('Repaired by the watchdog at %s'), clock(repaired.get(c.id)!)))
: '',
]),
fixAction(c, (fix) => void this.run(fix), refresh),
@@ -107,8 +109,8 @@ export class HealthTab {
const stale = wd.beat != null && wd.now - wd.beat > 180;
const today = wd.repairs.filter((x) => wd.now - x.ts < 86400);
const lastRep = today[today.length - 1];
const toggle = sw(wd.enabled, 'Watchdog repairs', async (v) => {
const ok = await attempt(() => api.settingsUpdate({ watchdog: v ? '1' : '0' }), v ? 'Watchdog on' : 'Watchdog off');
const toggle = sw(wd.enabled, _('Watchdog repairs'), async (v) => {
const ok = await attempt(() => api.settingsUpdate({ watchdog: v ? '1' : '0' }), v ? _('Watchdog on') : _('Watchdog off'));
if (!ok) setSwitch(toggle, !v);
const n = await api.serviceLog().catch(() => null);
if (n) this.paintLive(n, this.events);
@@ -119,13 +121,13 @@ export class HealthTab {
E('div', { class: 'dl-wd-head' }, [
E('span', { class: `dl-wd-tile${wd.enabled ? '' : ' off'}` }, icon('shield')),
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-wd-title' }, 'Watchdog'),
E('span', { class: 'dl-wd-title' }, _('Watchdog')),
E(
'span',
{ class: 'dl-sub' },
wd.enabled
? 'Every minute it checks the tunnels and services and repairs what it can on its own.'
: 'Off: problems are only written to the log. Nothing is repaired on its own.',
? _('Every minute it checks the tunnels and services and repairs what it can on its own.')
: _('Off: problems are only written to the log. Nothing is repaired on its own.'),
),
]),
E('span', { class: 'dl-spacer' }),
@@ -140,8 +142,13 @@ export class HealthTab {
'span',
{
class: `dl-check-chip${t.ok ? '' : ' error'}`,
title: t.ok ? 'OK' : `Not working${t.tries ? ` · ${t.tries} repair${t.tries > 1 ? 's' : ''}` : ''}`,
title: t.ok
? _('OK')
: t.tries
? `${_('Not working')} · ${plural(t.tries, '%s repair', '%s repairs')}`
: _('Not working'),
},
// The target's name comes from the router.
[icon(t.ok ? 'check' : 'x'), t.name],
),
),
@@ -150,13 +157,18 @@ export class HealthTab {
'span',
{ class: `dl-sub${stale ? ' dl-warn-text' : ''}` },
stale
? `The agent has not checked in for ${Math.round((wd.now - wd.beat!) / 60)} min; cron restarts it after 5.`
? fmt(_('The agent has not checked in for %s min; cron restarts it after 5.'), num(Math.round((wd.now - wd.beat!) / 60)))
: [
wd.last ? `Looked ${ago(wd.last, wd.now)}` : 'Starts within a minute',
wd.last ? fmt(_('Looked %s'), ago(wd.last, wd.now)) : _('Starts within a minute'),
' · ',
today.length
? `${today.length} repair${today.length > 1 ? 's' : ''} today, last ${lastRep.name} at ${clock(lastRep.ts)}`
: 'no repairs today',
? fmt(
N_(today.length, '%s repair today, last %s at %s', '%s repairs today, last %s at %s'),
num(today.length),
lastRep.name,
clock(lastRep.ts),
)
: _('no repairs today'),
],
),
]),
@@ -172,16 +184,16 @@ export class HealthTab {
.filter((x) => x.ts >= since && isProblem(x))
.sort((a, b) => b.ts - a.ts);
const head = E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Recent problems'),
E('h3', {}, _('Recent problems')),
E('span', { class: 'dl-spacer' }),
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, 'All in Log →') : '',
items.length ? E('a', { href: '#', click: (e: Event) => (e.preventDefault(), this.toLog()) }, `${_('All in Log')} →`) : '',
]);
if (!items.length) {
dom.content(this.recentEl, [
head,
E('div', { class: 'dl-recent-empty' }, [
E('span', { class: 'dl-check-icon ok' }, icon('check')),
'No problems in the last 7 days.',
_('No problems in the last 7 days.'),
]),
]);
return;
+8 -9
View File
@@ -13,10 +13,9 @@ type Tab = 'health' | 'log';
type Events = Awaited<ReturnType<typeof api.events>>;
type Loaded = [Status, Events, ServiceLog];
const TABS: [Tab, string][] = [
['health', 'Health'],
['log', 'Log'],
];
const TABS: Tab[] = ['health', 'log'];
const tabLabel = (t: Tab) => (t === 'log' ? _('Log') : _('Health'));
/** The whole log is large (up to 20,000 events): fetched only for the Log tab. A "since" cursor on the router would make it cheap. */
const LOG_LIMIT = 20000;
@@ -25,7 +24,7 @@ export class DiagnosticsPage {
tab: Tab = new URLSearchParams(location.search).get('tab') === 'log' ? 'log' : 'health';
health!: HealthTab;
log!: LogTab;
segEl = E('div', { class: 'dl-seg dl-srvsections dl-diag-tabs', role: 'tablist', 'aria-label': 'Diagnostics' });
segEl = E('div', { class: 'dl-seg dl-srvsections dl-diag-tabs', role: 'tablist', 'aria-label': _('Diagnostics') });
subEl = E('span', { class: 'dl-muted' });
actionsEl = E('div', { class: 'dl-row-actions' });
bodyEl = E('div', {});
@@ -61,7 +60,7 @@ export class DiagnosticsPage {
});
return E('div', {}, [
E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, 'Diagnostics'), this.subEl]),
E('div', { class: 'dl-stack' }, [E('h2', { class: 'dl-h1' }, _('Diagnostics')), this.subEl]),
this.actionsEl,
]),
this.segEl,
@@ -87,7 +86,7 @@ export class DiagnosticsPage {
this.tab = tab;
dom.content(
this.segEl,
TABS.map(([k, t]) =>
TABS.map((k) =>
E(
'button',
{
@@ -97,14 +96,14 @@ export class DiagnosticsPage {
'aria-selected': k === tab ? 'true' : 'false',
click: () => k !== this.tab && this.show(k),
},
t,
tabLabel(k),
),
),
);
// Both tabs stay alive; only the visible one is in the page.
this.bodyEl.replaceChildren(tab === 'log' ? this.log.el : this.health.el);
this.subEl.textContent =
tab === 'log' ? this.log.sub : 'Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.';
tab === 'log' ? this.log.sub : _('Everything Dawnline depends on, checked live. The watchdog repairs what it can on its own.');
dom.content(this.actionsEl, tab === 'log' ? this.log.actions() : '');
if (tab === 'log') {
this.log.paint();
+15 -11
View File
@@ -8,9 +8,10 @@ import { api, type LogCategory, type LogsInfo, type ServiceLogEntry } from '../.
import { button } from '../../ui/button';
import { dropdown } from '../../ui/menu';
import { icon } from '../../../shared/icons';
import { CATEGORIES, CATEGORY_LABEL, categoryOf, isProblem, retentionText, type LogItem } from '../../events/model';
import { CATEGORIES, categoryLabel, categoryOf, isProblem, retentionText, type LogItem } from '../../events/model';
import { dayTitle, eventRow, systemRow } from '../../events/render';
import { clearLogDialog, exportEvents } from '../../logs';
import { fmt, locale, num } from '../../../shared/i18n';
export type LogKind = 'all' | LogCategory | 'system';
type Events = Awaited<ReturnType<typeof api.events>>;
@@ -54,16 +55,16 @@ export class LogTab {
items.filter((x) => x.sys).map((x) => x.sys!),
);
};
const exp = button([icon('download'), ' Export'], () =>
const exp = button([icon('download'), ` ${_('Export')}`], () =>
dropdown(exp, [
{ label: 'CSV (spreadsheet)', icon: icon('download'), run: run('csv') },
{ label: _('CSV (spreadsheet)'), icon: icon('download'), run: run('csv') },
{ label: 'JSON', icon: icon('download'), run: run('json') },
]),
);
const clear = button([icon('trash'), ' Clear'], () =>
const clear = button([icon('trash'), ` ${_('Clear')}`], () =>
clearLogDialog(
'Clear the log',
'Removes events from the log on the router.',
_('Clear the log'),
_('Removes events from the log on the router.'),
{},
() => this.reload(),
this.kind === 'all' ? undefined : this.kind,
@@ -77,7 +78,8 @@ export class LogTab {
this.events = r.events;
this.policy = r.policy;
const off = CATEGORIES.filter((c) => !r.policy.categories.includes(c));
this.sub = `${retentionText(r.policy)}${off.length ? ` Not recorded: ${off.map((c) => CATEGORY_LABEL[c].toLowerCase()).join(', ')}.` : ''}`;
const kept = retentionText(r.policy);
this.sub = off.length ? `${kept} ${fmt(_('Not recorded: %s.'), off.map((c) => categoryLabel(c).toLowerCase()).join(', '))}` : kept;
}
async reload() {
@@ -119,7 +121,7 @@ export class LogTab {
click: () => this.show(k),
},
[
k === 'all' ? 'All' : k === 'system' ? 'System' : CATEGORY_LABEL[k],
k === 'all' ? _('All') : k === 'system' ? _('System') : categoryLabel(k),
E('b', {}, String(all.filter((x) => this.matches(x, k)).length)),
],
),
@@ -139,7 +141,9 @@ export class LogTab {
if (!items.length) {
dom.content(
this.list,
E('div', { class: 'dl-empty' }, [E('p', {}, this.events.length || this.system.length ? 'No events match.' : 'The log is empty.')]),
E('div', { class: 'dl-empty' }, [
E('p', {}, this.events.length || this.system.length ? _('No events match.') : _('The log is empty.')),
]),
);
return;
}
@@ -153,7 +157,7 @@ export class LogTab {
panel = E('div', { class: 'dl-panel flush' }, E('div', { class: 'dl-panel-head pad' }, E('h3', {}, t)));
groups.push(panel);
}
const time = new Date(x.ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
const time = new Date(x.ts * 1000).toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' });
if (x.sys) {
const key = `${x.sys.ts}|${x.sys.msg}`;
panel!.appendChild(
@@ -176,7 +180,7 @@ export class LogTab {
E(
'div',
{ class: 'dl-more-row' },
button(`Show ${Math.min(PAGE, items.length - this.shown)} more of ${items.length - this.shown}`, () => {
button(fmt(_('Show %s more of %s'), num(Math.min(PAGE, items.length - this.shown)), num(items.length - this.shown)), () => {
this.shown += PAGE;
this.paint();
}),
+62 -51
View File
@@ -8,7 +8,8 @@ import { api } from '../api';
import { svg } from '../ui/layout';
import { attachTip } from '../ui/tooltip';
import { icon } from '../../shared/icons';
import { ago, bits, bytes, date, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
import { ago, bits, bytes, date, daysLeft, duration, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
import { fill, fmt, plural } from '../../shared/i18n';
import { ConnectionMap, rangeControl, type Range } from '../map';
import { personUrl } from '../urls';
import { eventRow } from '../events/render';
@@ -32,29 +33,27 @@ interface Attention {
function attention(st: Status): Attention[] {
const out: Attention[] = [];
const link = (href: string, t: string) => E('a', { href }, t);
const diagnostics = () => link(L.url('admin/network/dawnline/diagnostics'), _('Open Diagnostics'));
const today = todayOf(st.series);
// AmneziaWG itself can't run: the health notice says so once, not "Tunnel down" for every server.
const awg = !!st.awg_state && !st.awg_state.ok;
for (const s of st.servers)
if (s.enabled && s.blocked)
// The reason, not just "down": its interface name is taken by a network section Dawnline didn't make.
out.push({ tone: 'bad', text: [`${s.name} ${s.blocked}. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')] });
else if (s.enabled && !s.up && !awg)
out.push({
tone: 'bad',
text: [`Tunnel ${s.ifname} is down. `, link(L.url('admin/network/dawnline/diagnostics'), 'Open Diagnostics')],
});
// The reason (the router's words), not just "down": its interface name is taken by a network section Dawnline didn't make.
out.push({ tone: 'bad', text: [s.blocked, ' ', diagnostics()] });
else if (s.enabled && !s.up && !awg) out.push({ tone: 'bad', text: [fmt(_('Tunnel %s is down.'), s.ifname), ' ', diagnostics()] });
for (const p of st.people) {
if (p.state === 'quota') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), ' reached the data limit.'] });
else if (p.state === 'expired') out.push({ tone: 'warn', text: [link(personUrl(p.id), p.name), '’s access has ended.'] });
const who = () => link(personUrl(p.id), p.name);
if (p.state === 'quota') out.push({ tone: 'warn', text: fill(_('%s reached the data limit.'), who()) });
else if (p.state === 'expired') out.push({ tone: 'warn', text: fill(_('%s’s access has ended.'), who()) });
else {
const left = daysLeft(p.expires, today);
if (endsSoon(p, left)) out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ${endsIn(left as number)}.`] });
if (endsSoon(p, left)) out.push({ tone: '', text: fill<Node | string>(_('%s’s access %s.'), who(), endsIn(left as number)) });
// "Keep access" at the end date: nothing changes on its own, so it is said here.
else if (left != null && left < 0 && p.expire_action === 'notify')
out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s end date passed (${date(p.expires)}) · access kept.`] });
out.push({ tone: '', text: fill<Node | string>(_('%s’s end date passed (%s) · access kept.'), who(), date(p.expires)) });
if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
out.push({ tone: '', text: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] });
out.push({ tone: '', text: fill(_('%s has used 90% of the data limit.'), who()) });
}
}
const stale = st.people.flatMap((p) => p.devices.filter((d) => d.config_stale).map((d) => [p, d] as const));
@@ -63,11 +62,17 @@ function attention(st: Status): Attention[] {
tone: 'warn',
text:
stale.length === 1
? [
? fill(
_('%s needs its configuration again.'),
link(personUrl(stale[0][0].id, stale[0][1].id), `${stale[0][0].name} · ${stale[0][1].name}`),
' needs its configuration again.',
]
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
)
: [
plural(
stale.length,
'%s device needs its configuration again (networks or DNS changed).',
'%s devices need their configuration again (networks or DNS changed).',
),
],
});
// A server that gives devices an IPv4 that is no longer the router's: one click puts the new one in.
for (const s of st.servers)
@@ -75,7 +80,8 @@ function attention(st: Status): Attention[] {
out.push({
tone: 'warn',
text: [
`Public address changed: ${s.name} still gives devices ${s.endpoint}, the router is ${st.wan} now. `,
fmt(_('Public address changed: %s still gives devices %s, the router is %s now.'), s.name, s.endpoint, st.wan),
' ',
E(
'button',
{
@@ -86,24 +92,30 @@ function attention(st: Status): Attention[] {
b.disabled = true;
await attempt(
() => api.serverUpdate(s.id, { endpoint: st.wan }),
`${s.name} uses ${st.wan} now — devices need their configuration again`,
fmt(_('%s uses %s now - devices need their configuration again'), s.name, st.wan),
);
b.disabled = false;
},
},
'Use the new address',
_('Use the new address'),
),
' A DDNS name would follow it by itself.',
' ',
_('A DDNS name would follow it by itself.'),
],
});
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
out.push({
tone: 'warn',
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/diagnostics'), 'Details')],
// The reason is the router's.
text: [
fmt(_('Internet through the LAN is off: %s'), st.like_home.error),
' ',
link(L.url('admin/network/dawnline/diagnostics'), _('Details')),
],
});
// Only while setting up: an admin who keeps the portal off has decided so.
if (!st.settings.portal_enabled && !st.people.length)
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
out.push({ tone: '', text: [_('The personal portal is off.'), ' ', link(L.url('admin/network/dawnline/settings'), _('Turn on'))] });
return out;
}
@@ -188,8 +200,8 @@ export class ServerOverview {
const st = this.st;
const head = E('div', { class: 'dl-panel-head pad' }, [
E('div', { class: 'dl-stack' }, [
E('h3', {}, 'Where people connect from'),
E('span', { class: 'dl-sub' }, 'City-level, from the client IP · locations cached on the router'),
E('h3', {}, _('Where people connect from')),
E('span', { class: 'dl-sub' }, _('City-level, from the client IP · locations cached on the router')),
]),
E('span', { class: 'dl-spacer' }),
rangeControl(this.range, (r) => {
@@ -202,11 +214,11 @@ export class ServerOverview {
if (!st.geo.enabled)
return E('div', { class: 'dl-panel flush' }, [
head,
E('div', { class: 'dl-map-off' }, [
'Locations are off. ',
E('a', { href: L.url('admin/network/dawnline/settings') }, 'Turn them on in Settings'),
'.',
]),
E(
'div',
{ class: 'dl-map-off' },
fill(_('Locations are off. %s.'), E('a', { href: L.url('admin/network/dawnline/settings') }, _('Turn them on in Settings'))),
),
]);
const map = (this.map = new ConnectionMap(
{
@@ -224,8 +236,8 @@ export class ServerOverview {
if (this.map === map) this.map = null;
});
const legend = E('div', { class: 'dl-map-legend' }, [
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
E('span', {}, [E('i', { class: 'line live' }), _('Live tunnel')]),
E('span', {}, [E('i', { class: 'line' }), _('Seen recently')]),
]);
const wrap = E('div', { class: 'dl-map-wrap' }, [map.el, legend]);
requestAnimationFrame(() => map.mount(this.mapData()));
@@ -248,9 +260,9 @@ export class ServerOverview {
this.parts.side,
E('div', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Needs attention'),
E('h3', {}, _('Needs attention')),
E('span', { class: 'dl-spacer' }),
E('a', { href: L.url('admin/network/dawnline/diagnostics') }, 'Health'),
E('a', { href: L.url('admin/network/dawnline/diagnostics') }, _('Health')),
]),
att.length
? att
@@ -262,7 +274,7 @@ export class ServerOverview {
a.action ?? '',
]),
)
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), 'All good. Nothing needs you right now.']),
: E('div', { class: 'dl-row dl-muted' }, [icon('check'), _('All good. Nothing needs you right now.')]),
]),
quiet,
);
@@ -272,13 +284,13 @@ export class ServerOverview {
this.parts.activity,
E('div', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('h3', {}, _('Activity')),
E('span', { class: 'dl-spacer' }),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, 'View all'),
E('a', { href: `${L.url('admin/network/dawnline/diagnostics')}?tab=log` }, _('View all')),
]),
events.length
? events.map((e) => eventRow(st, e))
: E('div', { class: 'dl-row dl-muted' }, 'Nothing yet. Connections, new devices and pauses appear here.'),
: E('div', { class: 'dl-row dl-muted' }, _('Nothing yet. Connections, new devices and pauses appear here.')),
]),
quiet,
);
@@ -332,7 +344,7 @@ export class ServerOverview {
E('span', { class: 'dl-onl-av sm' }, initials(p.name)),
E('span', { class: 'dl-stack' }, [
E('b', {}, p.name),
E('span', { class: 'dl-hc-since' }, since ? `online for ${ago(since, st.now).replace(' ago', '')}` : 'online'),
E('span', { class: 'dl-hc-since' }, since ? fmt(_('online for %s'), duration(Math.max(60, st.now - since))) : _('online')),
]),
E(
'span',
@@ -345,12 +357,12 @@ export class ServerOverview {
'div',
{ class: 'dl-hc-speed-row' },
idle
? [E('span', { class: 'dl-faint' }, 'Idle right now')]
? [E('span', { class: 'dl-faint' }, _('Idle right now'))]
: [
E('span', {}, [E('span', { class: 'dl-dn' }, '↓'), ` ${bits(fresh![2])}`]),
E('span', {}, [E('span', { class: 'dl-up' }, '↑'), ` ${bits(fresh![1])}`]),
E('span', { class: 'dl-spacer' }),
E('span', { class: 'dl-faint' }, '15 min'),
E('span', { class: 'dl-faint' }, _('15 min')),
],
),
chart,
@@ -364,7 +376,7 @@ export class ServerOverview {
E(
'span',
{ class: 'dl-faint' },
`${bytes(devs.reduce((n, d) => n + today(d), 0))} today · ${bytes(p.month[0] + p.month[1])} this month`,
`${fmt(_('%s today'), bytes(devs.reduce((n, d) => n + today(d), 0)))} · ${fmt(_('%s this month'), bytes(p.month[0] + p.month[1]))}`,
),
]),
]),
@@ -374,7 +386,7 @@ export class ServerOverview {
const person = (x: { p: Person; devs: Device[] }) => {
const { p, devs } = x;
const badge = E('span', { class: 'dl-onl-dev' }, devs.length > 1 ? String(devs.length) : icon(devs[0].kind));
const el = E('a', { class: `dl-onl-p${big ? '' : ' sm'}`, href: personUrl(p.id), 'aria-label': `${p.name}, online` }, [
const el = E('a', { class: `dl-onl-p${big ? '' : ' sm'}`, href: personUrl(p.id), 'aria-label': fmt(_('%s, online'), p.name) }, [
E('span', { class: 'dl-onl-av' }, [initials(p.name), badge]),
big ? E('span', { class: 'dl-onl-name' }, p.name) : '',
big
@@ -391,15 +403,14 @@ export class ServerOverview {
const count = E('b', { class: `dl-onl-count${on.length ? '' : ' none'}` }, String(on.length));
const ndev = on.reduce((n, x) => n + x.devs.length, 0);
if (on.length)
attachTip(count, () => [`${on.length} ${on.length === 1 ? 'person' : 'people'} · ${ndev} device${ndev === 1 ? '' : 's'}`]);
if (on.length) attachTip(count, () => [`${plural(on.length, '%s person', '%s people')} · ${plural(ndev, '%s device', '%s devices')}`]);
const shown = on.length > CAP ? on.slice(0, CAP - 1) : on;
const last = st.people
.flatMap((p) => p.devices.map((d) => ({ p, d })))
.filter((x) => x.d.handshake)
.sort((a, b) => b.d.handshake - a.d.handshake)[0];
return E('div', { class: 'dl-bento-tile online' }, [
E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, 'Online'), count]),
E('div', { class: 'dl-bento-head' }, [E('span', { class: 'dl-metric-label' }, _('Online')), count]),
on.length
? E('div', { class: `dl-onl-row${big ? '' : ' grid'}` }, [
...shown.map(person),
@@ -409,7 +420,7 @@ export class ServerOverview {
{
class: 'dl-onl-p sm more',
href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(this.srvId)}&section=people&filter=online`,
title: 'Everyone online',
title: _('Everyone online'),
click: (ev: Event) => {
if (this.go) {
ev.preventDefault();
@@ -423,10 +434,10 @@ export class ServerOverview {
])
: E('div', { class: 'dl-onl-empty' }, [
// A server that is off takes no connections: say so rather than "nobody".
E('span', {}, off ? 'The server is turned off' : 'Nobody is connected'),
E('span', {}, off ? _('The server is turned off') : _('Nobody is connected')),
last
? E('span', { class: 'dl-sub' }, `Last: ${last.p.name}, ${ago(last.d.handshake, st.now)}`)
: E('span', { class: 'dl-sub' }, off ? 'Devices connect once it is on' : 'No device has connected yet'),
? E('span', { class: 'dl-sub' }, fmt(_('Last: %s, %s'), last.p.name, ago(last.d.handshake, st.now)))
: E('span', { class: 'dl-sub' }, off ? _('Devices connect once it is on') : _('No device has connected yet')),
]),
]);
}
@@ -448,6 +459,6 @@ export class ServerOverview {
.filter(([, n]) => n > 0)
.sort((a, b) => b[1] - a[1])
.slice(0, 2);
return daysTile(this.st.series, top.length ? `Most: ${top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')}` : '');
return daysTile(this.st.series, top.length ? fmt(_('Most: %s'), top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')) : '');
}
}
+131 -87
View File
@@ -24,7 +24,7 @@ import { expiresHelp, limitHelp, nameHelp, quotaHelp } from '../netcheck';
import { coreFor } from '../cores';
import { icon } from '../../shared/icons';
import {
KIND_LABEL,
kindLabel,
addMonthsClamped,
ago,
bits,
@@ -38,6 +38,7 @@ import {
initials,
todayOf,
} from '../../shared/format';
import { fill, fmt, num, plural } from '../../shared/i18n';
type Sid = string;
@@ -64,13 +65,13 @@ function slotBar(p: Person): HTMLElement {
const n = Math.max(1, p.device_limit, used);
// 22px a segment until the bar is 160px long; past that the segments get thinner, so the count stays close.
const width = Math.min(160, n * 22 + (n - 1) * 3);
return E('div', { class: 'dl-slotbar', title: `${used} of ${p.device_limit} devices` }, [
return E('div', { class: 'dl-slotbar', title: fmt(N_(p.device_limit, '%s of %s device', '%s of %s devices'), used, p.device_limit) }, [
E(
'span',
{ class: 'dl-slotbar-segs', style: `width: ${width}px` },
Array.from({ length: n }, (_, i) => E('i', { class: i >= p.device_limit ? 'over' : i < used ? 'used' : '' })),
Array.from({ length: n }, (_x, i) => E('i', { class: i >= p.device_limit ? 'over' : i < used ? 'used' : '' })),
),
E('span', { class: 'dl-slotbar-text' }, `${used} of ${p.device_limit}`),
E('span', { class: 'dl-slotbar-text' }, fmt(_('%s of %s'), used, p.device_limit)),
]);
}
@@ -201,8 +202,8 @@ export class PeoplePage {
'div',
{ class: 'dl-plist-none' },
this.st.servers.length
? 'No people yet. Add someone and send them their personal link.'
: 'Set up the server first, then add people.',
? _('No people yet. Add someone and send them their personal link.')
: _('Set up the server first, then add people.'),
),
);
this.decorate();
@@ -229,7 +230,7 @@ export class PeoplePage {
'select',
{
class: 'dl-select',
'aria-label': 'Sort',
'aria-label': _('Sort'),
change: (ev: Event) => {
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
remember('dl.people.sort', page.sort);
@@ -237,17 +238,17 @@ export class PeoplePage {
},
},
[
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, 'Last seen'),
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, 'Name'),
E('option', { value: 'usage', selected: page.sort === 'usage' ? 'selected' : null }, 'Usage'),
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, _('Last seen', 'sort')),
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, _('Name', 'sort')),
E('option', { value: 'usage', selected: page.sort === 'usage' ? 'selected' : null }, _('Usage', 'sort')),
],
);
// Find, once the list is long enough to need it; "/" focuses it.
const find = E('input', {
type: 'search',
class: 'cbi-input-text dl-people-find',
placeholder: 'Find…',
'aria-label': 'Find a person or device',
placeholder: _('Find…'),
'aria-label': _('Find a person or device'),
hidden: st.people.length > 8 ? null : 'hidden',
input: (ev: Event) => {
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
@@ -268,25 +269,28 @@ export class PeoplePage {
? ''
: E('div', { class: 'dl-pagehead' }, [
E('div', { class: 'dl-stack' }, [
E('h2', { class: 'dl-h1' }, 'People'),
E('h2', { class: 'dl-h1' }, _('People')),
E('span', { class: 'dl-muted dl-people-count' }, this.countText()),
]),
st.servers.length ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
st.servers.length ? button([icon('plus'), ` ${_('Add person')}`], () => page.openCreate(), 'add') : '',
]),
st.servers.length
? ''
: E('div', { class: 'alert-message warning' }, [
'No server yet. ',
E('a', { href: L.url('admin/network/dawnline/server') }, 'Run the setup wizard'),
' before adding people.',
]),
: E(
'div',
{ class: 'alert-message warning' },
fill(
_('No server yet. %s before adding people.'),
E('a', { href: L.url('admin/network/dawnline/server') }, _('Run the setup wizard')),
),
),
E('div', { class: 'dl-toolbar' }, [
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
// Sort and add stay together on the right, wrapping as one group.
E('div', { class: 'dl-toolbar-end' }, [
find,
sort,
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
page.serverId ? button([icon('plus'), ` ${_('Add person')}`], () => page.openCreate(), 'add') : '',
]),
]),
this.list,
@@ -311,7 +315,11 @@ export class PeoplePage {
countText(): string {
const t = this.st.totals;
return `${t.people} ${t.people === 1 ? 'person' : 'people'} · ${t.devices} device${t.devices === 1 ? '' : 's'} · ${t.online} online`;
return [
plural(t.people, '%s person', '%s people'),
plural(t.devices, '%s device', '%s devices'),
fmt(_('%s online'), num(t.online)),
].join(' · ');
}
/** Row classes, counters, filter tabs and sort order; a `quiet` repaint keeps focused tabs. */
@@ -329,7 +337,7 @@ export class PeoplePage {
};
const tabs = this.el?.querySelector<HTMLElement>('.dl-people-tabs');
if (tabs && !(quiet && focusInside(tabs))) {
const label: Record<Filter, string> = { all: 'All', online: 'Online', attention: 'Needs attention', paused: 'Paused' };
const label: Record<Filter, string> = { all: _('All'), online: _('Online'), attention: _('Needs attention'), paused: _('Paused') };
dom.content(
tabs,
(Object.keys(label) as Filter[]).map((f) =>
@@ -385,7 +393,7 @@ export class PeoplePage {
// Say so when the filter leaves nobody.
let none = this.el?.querySelector<HTMLElement>('.dl-people-none') ?? null;
if (people.length && !shown) {
none ??= E('div', { class: 'dl-empty dl-people-none' }, E('p', {}, 'No one here right now.'));
none ??= E('div', { class: 'dl-empty dl-people-none' }, E('p', {}, _('No one here right now.')));
if (none.previousElementSibling !== this.list) this.list.after(none);
} else none?.remove();
}
@@ -397,7 +405,7 @@ export class PeoplePage {
renderCard(node: HTMLElement, sid: Sid): HTMLElement {
const p = this.person(sid);
if (!p) {
dom.content(node, E('em', {}, 'This person was just removed.'));
dom.content(node, E('em', {}, _('This person was just removed.')));
return node;
}
const today = this.today;
@@ -413,14 +421,14 @@ export class PeoplePage {
const soon = endsSoon(p, left);
const over = left != null && left < 0;
pills.push(
E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: `Access ends ${date(p.expires)}` }, [
E('span', { class: `dl-pill-ic${over ? ' bad' : soon ? ' warn' : ''}`, title: fmt(_('Access ends %s'), date(p.expires)) }, [
icon('calendar'),
over ? `ended ${date(p.expires)}` : soon ? endsIn(left as number) : `until ${date(p.expires)}`,
over ? fmt(_('ended %s'), date(p.expires)) : soon ? endsIn(left as number) : fmt(_('until %s'), date(p.expires)),
]),
);
}
if (p.hours && why !== 'hours')
pills.push(E('span', { class: 'dl-pill-ic', title: 'Allowed hours' }, [icon('clock'), p.hours.replace('-', '–')]));
pills.push(E('span', { class: 'dl-pill-ic', title: _('Allowed hours') }, [icon('clock'), p.hours.replace('-', '–')]));
const chips = byDeviceState(p.devices).map((d) => {
return E(
@@ -428,7 +436,13 @@ export class PeoplePage {
{
type: 'button',
class: `dl-chip${d.disabled ? ' disabled' : ''}${d.online ? ' live' : ''}`,
title: `${KIND_LABEL[d.kind]} · ${d.address}${d.online ? ` · online from ${d.endpoint}` : d.handshake ? ` · seen ${ago(d.handshake, this.st.now)}` : ''}`,
title: [
kindLabel(d.kind),
d.address,
d.online ? fmt(_('online from %s'), d.endpoint) : d.handshake ? fmt(_('seen %s'), ago(d.handshake, this.st.now)) : '',
]
.filter(Boolean)
.join(' · '),
click: (ev: Event) => {
ev.preventDefault();
void openDevice(p, d, this.deviceOpts(p));
@@ -437,7 +451,7 @@ export class PeoplePage {
[
icon(d.kind),
E('span', { class: 'dl-chip-name' }, d.name),
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, _('not set up')) : '',
// Online shows as the green chip (.dl-chip.live); no dots.
],
);
@@ -449,13 +463,13 @@ export class PeoplePage {
{
type: 'button',
class: 'dl-chip add',
title: free > 0 ? 'Add device' : 'Over the limit: admins can still add',
title: free > 0 ? _('Add device') : _('Over the limit: admins can still add'),
click: (ev: Event) => {
ev.preventDefault();
addDevice(p, this.deviceOpts(p));
},
},
[icon('plus'), 'Add device'],
[icon('plus'), _('Add device')],
),
);
@@ -465,20 +479,24 @@ export class PeoplePage {
fixes.push(
E(
'button',
{ type: 'button', class: 'dl-fix', click: () => this.quick(p, { expires: addMonth(p.expires, today) }, 'Extended by 1 month') },
'Extend 1 month',
{
type: 'button',
class: 'dl-fix',
click: () => this.quick(p, { expires: addMonth(p.expires, today) }, _('Extended by 1 month')),
},
_('Extend 1 month'),
),
);
const more = iconButton(
'more',
'More',
_('More'),
(ev: MouseEvent) =>
dropdown(
ev.currentTarget as HTMLElement,
[
{
label: 'Open',
label: _('Open'),
icon: icon('open'),
run: () => {
location.href = personUrl(p.id);
@@ -486,27 +504,27 @@ export class PeoplePage {
},
portal
? {
label: 'Invite card',
label: _('Invite card'),
icon: icon('qr'),
run: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? 'Home'),
run: () => inviteCard(p, this.st.servers.find((s) => s.id === p.server)?.name ?? _('Home')),
}
: null,
free > 0 ? { label: 'Add device', icon: icon('plus'), run: () => addDevice(p, this.deviceOpts(p)) } : null,
free > 0 ? { label: _('Add device'), icon: icon('plus'), run: () => addDevice(p, this.deviceOpts(p)) } : null,
null,
{
label: p.paused ? 'Resume' : 'Pause',
label: p.paused ? _('Resume') : _('Pause'),
icon: icon(p.paused ? 'play' : 'pause'),
warn: !p.paused,
run: () => this.togglePause(p),
},
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => this.remove(p.id) },
{ label: _('Delete'), icon: icon('trash'), danger: true, run: () => this.remove(p.id) },
].filter((x, i, a) => x || (i > 0 && a[i - 1])) as MenuItem[],
),
'neutral',
'dl-icon-only',
);
const actions = E('div', { class: 'dl-pcard-actions' }, [
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
portal ? iconButton('link', _('Copy link'), () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
more,
]);
@@ -541,28 +559,34 @@ export class PeoplePage {
const today = this.today;
// The month's data resets on the 1st (router time).
const reset = addMonthsClamped(`${today.slice(0, 8)}01`, 1);
const extra = () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
const extra = () => this.quick(p, { bonus_gb: String((p.bonus_gb || 0) + 10) }, _('+10 GB this month'));
const what: Record<typeof why, [string, 'warn' | 'bad', string, string, [string, string, () => unknown] | null]> = {
paused: ['pause', 'warn', 'Paused', 'Devices can’t connect until you resume', ['play', 'Resume', () => this.togglePause(p)]],
paused: ['pause', 'warn', _('Paused'), _('Devices can’t connect until you resume'), ['play', _('Resume'), () => this.togglePause(p)]],
quota:
p.quota_period === 'month'
? ['chart', 'bad', 'Data limit reached', `Paused until it resets on ${date(reset)}`, ['plus', '+10 GB this month', extra]]
? [
'chart',
'bad',
_('Data limit reached'),
fmt(_('Paused until it resets on %s'), date(reset)),
['plus', _('+10 GB this month'), extra],
]
: [
'chart',
'bad',
'Data limit reached',
'Paused until the limit is raised',
['edit', 'Change limit', () => (location.href = personUrl(p.id))],
_('Data limit reached'),
_('Paused until the limit is raised'),
['edit', _('Change limit'), () => (location.href = personUrl(p.id))],
],
expired: [
'calendar',
'bad',
`Access ended ${date(p.expires)}`,
'Devices can’t connect',
['calendar', 'Extend 1 month', () => this.quick(p, { expires: addMonth(p.expires, today) }, 'Extended by 1 month')],
fmt(_('Access ended %s'), date(p.expires)),
_('Devices can’t connect'),
['calendar', _('Extend 1 month'), () => this.quick(p, { expires: addMonth(p.expires, today) }, _('Extended by 1 month'))],
],
hours: ['clock', 'warn', 'Outside allowed hours', `Access ${p.hours.replace('-', '–')} (router time)`, null],
no_server: ['alert', 'warn', 'No server', 'Choose a server on their page', null],
hours: ['clock', 'warn', _('Outside allowed hours'), fmt(_('Access %s (router time)'), p.hours.replace('-', '–')), null],
no_server: ['alert', 'warn', _('No server'), _('Choose a server on their page'), null],
};
const [ic, tone, title, sub, act] = what[why];
return E('div', { class: `dl-pstrip ${tone}` }, [
@@ -586,16 +610,18 @@ export class PeoplePage {
fill.style.width = `${pct}%`;
bar.appendChild(fill);
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`),
E('div', { class: 'dl-tip-title' }, fmt(_('%s%% used'), num(pct, 1))),
E(
'div',
{ class: 'dl-muted' },
`${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`,
`${fmt(_('%s of %s'), bytes(p.quota_used), bytes(p.quota_limit))} · ${fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - p.quota_used)))}`,
),
E(
'div',
{ class: 'dl-faint' },
p.quota_period === 'total' ? 'In total' : `This month${p.bonus_gb ? ` · includes +${p.bonus_gb} GB extra` : ''}`,
p.quota_period === 'total'
? _('In total')
: [_('This month'), p.bonus_gb ? fmt(_('includes +%s GB extra'), num(p.bonus_gb)) : ''].filter(Boolean).join(' · '),
),
]);
} else {
@@ -610,7 +636,7 @@ export class PeoplePage {
});
if (devs.length)
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, 'This month by device'),
E('div', { class: 'dl-tip-title' }, _('This month by device')),
...devs.map((x, i) =>
E('div', { class: 'dl-tip-row' }, [
E('span', { class: `dl-swatch c${Math.min(i, 4)}` }),
@@ -621,12 +647,12 @@ export class PeoplePage {
]);
}
const limitText = p.quota_limit ? `${bytes(Math.max(0, p.quota_limit - p.quota_used))} left` : 'no limit';
const limitText = p.quota_limit ? fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - p.quota_used))) : _('no limit');
return E('div', { class: 'dl-pside' }, [
E('div', { class: 'dl-pside-top' }, [
live
? E('span', { class: 'dl-pside-state live' }, 'Online')
: E('span', { class: 'dl-pside-state' }, p.online ? 'Online' : p.last_seen ? 'Offline' : 'Never connected'),
? E('span', { class: 'dl-pside-state live' }, _('Online'))
: E('span', { class: 'dl-pside-state' }, p.online ? _('Online') : p.last_seen ? _('Offline') : _('Never connected')),
actions,
]),
E('div', { class: 'dl-use-num' }, [
@@ -634,38 +660,50 @@ export class PeoplePage {
E(
'span',
{ class: 'dl-faint' },
p.quota_limit ? `of ${bytes(p.quota_limit)}` : p.quota_period === 'total' && p.quota_gb ? 'in total' : 'this month',
p.quota_limit
? fmt(_('of %s'), bytes(p.quota_limit))
: p.quota_period === 'total' && p.quota_gb
? _('in total')
: _('this month'),
),
]),
bar,
live
? E('div', { class: 'dl-use-live', title: 'Right now' }, [`↓ ${bits(r![2])}`, E('span', { class: 'dl-faint' }, `↑ ${bits(r![1])}`)])
: E('div', { class: 'dl-faint dl-pside-foot' }, today ? `today ${bytes(today)} · ${limitText}` : limitText),
? E('div', { class: 'dl-use-live', title: _('Right now') }, [
`↓ ${bits(r![2])}`,
E('span', { class: 'dl-faint' }, `↑ ${bits(r![1])}`),
])
: E('div', { class: 'dl-faint dl-pside-foot' }, today ? `${fmt(_('today %s'), bytes(today))} · ${limitText}` : limitText),
]);
}
async togglePause(p: Person) {
if (await attempt(() => api.personPause(p.id, !p.paused), p.paused ? `${p.name} resumed` : `${p.name} paused`)) await this.refresh();
if (await attempt(() => api.personPause(p.id, !p.paused), fmt(p.paused ? _('%s resumed') : _('%s paused'), p.name)))
await this.refresh();
}
async remove(sid: Sid) {
const p = this.person(sid);
const ok = await confirmDialog(
`Remove ${p?.name ?? sid}?`,
`All ${p?.devices.length ?? 0} devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.`,
'Remove',
fmt(_('Remove %s?'), p?.name ?? sid),
plural(
p?.devices.length ?? 0,
'%s device is disconnected immediately and the personal link stops working. Usage history is kept in backups.',
'All %s devices are disconnected immediately and the personal link stops working. Usage history is kept in backups.',
),
_('Remove'),
true,
);
if (ok && (await attempt(() => api.personDelete(sid), 'Person removed'))) await this.refresh();
if (ok && (await attempt(() => api.personDelete(sid), _('Person removed')))) await this.refresh();
}
openCreate() {
const st = this.st;
if (!st.servers.length) {
notify('Set up the server first.', 'warning');
notify(_('Set up the server first.'), 'warning');
return;
}
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement;
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: _('e.g. Myata'), maxlength: 48 }) as HTMLInputElement;
// The last person's access and data limit come back pre-filled (most are alike).
const last = (() => {
try {
@@ -688,7 +726,7 @@ export class PeoplePage {
class: 'cbi-input-text',
min: 0,
step: 'any',
placeholder: 'Unlimited',
placeholder: _('Unlimited'),
value: last.quota ?? '',
}) as HTMLInputElement;
const quick = (label: string, months: number) =>
@@ -721,26 +759,32 @@ export class PeoplePage {
]);
// Each field says what its value means, or what is wrong, as it is typed; Create refuses what the router would.
const today = todayOf(st.series);
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown in their portal and apps.'));
const limitRow = liveField('Devices', limit, () => limitHelp(limit.value));
const nameRow = liveField(_('Name', 'person'), name, () => nameHelp(name.value, [], _('Shown in their portal and apps.')));
const limitRow = liveField(_('Devices'), limit, () => limitHelp(limit.value));
const expRow = liveField(
'End date',
_('End date'),
expires,
() => expiresHelp(expires.value, today, daysLeft, date),
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
E('div', { class: 'dl-actions' }, [
expires,
quick(_('1 month'), 1),
quick(_('3 months'), 3),
quick(_('1 year'), 12),
quick(_('None', 'end date'), 0),
]),
);
const quotaRow = liveField('Monthly data (GB)', quota, () => quotaHelp(quota.value));
const quotaRow = liveField(_('Monthly data (GB)'), quota, () => quotaHelp(quota.value));
// The quick buttons set the date without an input event.
expires.addEventListener('change', () => expRow.refresh());
const portalOn = st.settings.portal_enabled;
modal(
'Add person',
_('Add person'),
[
nameRow,
server ? row('Server', server) : '',
server ? row(_('Server'), server) : '',
E('div', { class: 'cbi-value dl-block' }, [
E('label', { class: 'cbi-value-title' }, 'Access'),
E('label', { class: 'cbi-value-title' }, _('Access')),
E('div', { class: 'cbi-value-field' }, access.el),
]),
limitRow,
@@ -752,7 +796,7 @@ export class PeoplePage {
' ',
button(
// Without the portal there is no link to copy.
portalOn ? 'Create and copy link' : 'Create',
portalOn ? _('Create and copy link') : _('Create'),
async () => {
const bad = firstBad([nameRow, limitRow, expRow, quotaRow]);
if (bad) {
@@ -774,7 +818,7 @@ export class PeoplePage {
if (!r) return;
remember('dl.person.last', JSON.stringify({ access: access.get(), quota: quota.value.trim() }));
// After the await some browsers refuse the clipboard: the card has its own Copy.
if (r.link) await copyText(r.link, 'Personal link copied', true);
if (r.link) await copyText(r.link, _('Personal link copied'), true);
this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name);
await this.refresh();
},
@@ -788,28 +832,28 @@ export class PeoplePage {
showCreated(id: string, name: string, link: string | null, server: string) {
if (link) {
inviteCard({ id, name, link }, server, {
title: `${name} is ready`,
lead: `Send ${name} the card or the link. They open it, add their devices and connect — no account needed.`,
title: fmt(_('%s is ready'), name),
lead: fmt(_('Send %s the card or the link. They open it, add their devices and connect - no account needed.'), name),
});
return;
}
// No portal, no link: the two ways on from here, as buttons.
const p = this.person(id);
modal(
`${name} is ready`,
[E('p', {}, 'Created. Turn on the personal portal in Settings to get a link, or add devices for them here.')],
fmt(_('%s is ready'), name),
[E('p', {}, _('Created. Turn on the personal portal in Settings to get a link, or add devices for them here.'))],
[
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Done'),
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, _('Done')),
' ',
E(
'a',
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}?section=portal` },
'Open Settings',
_('Open Settings'),
),
' ',
p
? button(
'Add device',
_('Add device'),
() => {
closeModal();
addDevice(p, this.deviceOpts(p));
+28 -24
View File
@@ -4,6 +4,7 @@ import { E } from '../../e';
import { button } from '../../ui/button';
import { dropdown } from '../../ui/menu';
import { icon } from '../../../shared/icons';
import { fill, fmt, num, plural } from '../../../shared/i18n';
import { ConnectionMap, rangeControl } from '../../map';
import { eventRow, eventText } from '../../events/render';
import { clearLogDialog, exportEvents } from '../../logs';
@@ -13,11 +14,11 @@ import type { PersonPage } from './index';
function mapCard(page: PersonPage): HTMLElement {
const st = page.st;
const head = E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Locations'),
E('h3', {}, _('Locations')),
E('span', { class: 'dl-spacer' }),
st.geo.enabled ? rangeControl('30d', (r) => page.map?.setRange(r), false) : '',
button(
'Hide',
_('Hide'),
() => {
page.mapOpen = false;
page.map?.destroy();
@@ -30,11 +31,11 @@ function mapCard(page: PersonPage): HTMLElement {
if (!st.geo.enabled)
return E('div', { class: 'dl-panel flush' }, [
head,
E('div', { class: 'dl-map-off' }, [
'Locations are off. ',
E('a', { href: L.url('admin/network/dawnline/settings') }, 'Turn them on in Settings'),
'.',
]),
E(
'div',
{ class: 'dl-map-off' },
fill(_('Locations are off. %s.'), E('a', { href: L.url('admin/network/dawnline/settings') }, _('Turn them on in Settings'))),
),
]);
const map = new ConnectionMap(
{
@@ -59,11 +60,11 @@ export function placesPart(page: PersonPage): HTMLElement | null {
return E('div', { class: 'dl-places' }, [
icon('pin'),
E('div', { class: 'dl-stack' }, [
E('span', {}, 'Locations are off'),
E('span', { class: 'dl-sub' }, 'City-level, from the client IP'),
E('span', {}, _('Locations are off')),
E('span', { class: 'dl-sub' }, _('City-level, from the client IP')),
]),
E('span', { class: 'dl-spacer' }),
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/settings') }, 'Turn on'),
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/settings') }, _('Turn on')),
]);
if (page.mapOpen) return page.map && page.parts.places.contains(page.map.el) ? null : mapCard(page);
const since = st.now - 30 * 86400;
@@ -73,19 +74,19 @@ export function placesPart(page: PersonPage): HTMLElement | null {
return E('div', { class: 'dl-places' }, [
icon('pin'),
E('div', { class: 'dl-stack' }, [
E('span', {}, last ? last.city || last.country : 'No locations yet'),
E('span', {}, last ? last.city || last.country : _('No locations yet')),
E(
'span',
{ class: 'dl-sub' },
last
? `${places.length} place${places.length === 1 ? '' : 's'} in 30 days${last.org ? ` · ${last.org}` : ''}`
: 'Shown after a device connects',
? [plural(places.length, '%s place in 30 days', '%s places in 30 days'), last.org].filter(Boolean).join(' · ')
: _('Shown after a device connects'),
),
]),
E('span', { class: 'dl-spacer' }),
pts.length
? button(
'Show map',
_('Show map'),
() => {
page.mapOpen = true;
page.paintPlaces();
@@ -110,7 +111,7 @@ export function activityPart(page: PersonPage): HTMLElement {
const row = eventRow(st, e, { server: false });
if (n > 1) {
const main = row.querySelector('.dl-row-main') as HTMLElement;
dom.content(main, [...eventText(st, e).slice(0, 3), E('span', { class: 'dl-muted' }, `${n} times`)]);
dom.content(main, [...eventText(st, e).slice(0, 3), E('span', { class: 'dl-muted' }, plural(n, '%s time', '%s times'))]);
main.title = latest
.slice(i, i + n)
.map((x) => x.detail ?? '')
@@ -123,29 +124,32 @@ export function activityPart(page: PersonPage): HTMLElement {
[icon('more')],
() =>
dropdown(more, [
{ label: 'Export CSV', icon: icon('download'), run: () => exportEvents(st, all, 'csv', p.id) },
{ label: 'Export JSON', icon: icon('download'), run: () => exportEvents(st, all, 'json', p.id) },
{ label: _('Export CSV'), icon: icon('download'), run: () => exportEvents(st, all, 'csv', p.id) },
{ label: _('Export JSON'), icon: icon('download'), run: () => exportEvents(st, all, 'json', p.id) },
null,
{
label: `Clear ${p.name}'s activity`,
label: fmt(_("Clear %s's activity"), p.name),
icon: icon('trash'),
danger: true,
run: () =>
clearLogDialog(`Clear ${p.name}'s activity`, `Removes events about ${p.name} and their devices.`, { person: p.id }, () =>
page.refresh(),
clearLogDialog(
fmt(_("Clear %s's activity"), p.name),
fmt(_('Removes events about %s and their devices.'), p.name),
{ person: p.id },
() => page.refresh(),
),
},
]),
'neutral',
{ title: 'Export or clear', class: 'cbi-button cbi-button-neutral dl-icon-only' },
{ title: _('Export or clear'), class: 'cbi-button cbi-button-neutral dl-icon-only' },
);
return E('div', { class: 'dl-panel flush' }, [
E('div', { class: 'dl-panel-head pad' }, [
E('h3', {}, 'Activity'),
E('span', { class: 'dl-sub' }, all.length > 10 ? `latest 10 of ${all.length}` : ''),
E('h3', {}, _('Activity')),
E('span', { class: 'dl-sub' }, all.length > 10 ? fmt(_('latest 10 of %s'), num(all.length)) : ''),
E('span', { class: 'dl-spacer' }),
more,
]),
rows.length ? rows : E('div', { class: 'dl-row dl-muted' }, 'Nothing yet.'),
rows.length ? rows : E('div', { class: 'dl-row dl-muted' }, _('Nothing yet.')),
]);
}
+15 -12
View File
@@ -9,7 +9,8 @@ import { downloadFile } from '../../ui/files';
import { attempt, notify } from '../../ui/toast';
import { deviceStatus } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { KIND_LABEL, ago, byDeviceState, bytes } from '../../../shared/format';
import { kindLabel, ago, byDeviceState, bytes } from '../../../shared/format';
import { fmt, num } from '../../../shared/i18n';
import { addDevice, openDevice, quickMenu } from '../../device';
import { dayBars } from '../../widgets/tiles';
import type { PersonPage } from './index';
@@ -18,14 +19,14 @@ import type { PersonPage } from './index';
async function showDeviceQr(page: PersonPage, d: Device) {
const cfg = await attempt(() => api.deviceConfig(d.id));
if (!cfg) return;
modal(`Set up ${d.name}`, [await page.core.connectBlock(cfg, 'qr')], [cancelButton('Close')]);
modal(fmt(_('Set up %s'), d.name), [await page.core.connectBlock(cfg, 'qr')], [cancelButton(_('Close'))]);
}
async function downloadConfig(page: PersonPage, d: Device) {
const cfg = await attempt(() => api.deviceConfig(d.id));
if (!cfg) return;
if (!cfg.has_private_key) {
notify('This device made its own keys in the browser; its configuration only exists there.', 'warning');
notify(_('This device made its own keys in the browser; its configuration only exists there.'), 'warning');
return;
}
const f = page.core.file.make(cfg);
@@ -42,7 +43,7 @@ export function devicesPart(page: PersonPage): HTMLElement {
};
const more = (d: Device) =>
button([icon('more')], (ev: MouseEvent) => quickMenu(ev.currentTarget as HTMLElement, p, d, page.deviceOpts()), 'neutral', {
title: 'QR, file, key, rename, new keys, remove',
title: _('QR, file, key, rename, new keys, remove'),
class: 'cbi-button cbi-button-neutral dl-icon-only',
});
const cards = byDeviceState(p.devices).map((d) => {
@@ -51,12 +52,12 @@ export function devicesPart(page: PersonPage): HTMLElement {
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
E('b', {}, d.name),
deviceStatus(d, now, undefined, p),
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, _('Update config')) : '',
]),
more(d),
]);
const trend = E('div', { class: 'dl-dcard-trend' }, [
E('div', { class: 'dl-stack' }, [E('b', {}, bytes(d.month[0] + d.month[1])), E('span', { class: 'dl-sub' }, 'this month')]),
E('div', { class: 'dl-stack' }, [E('b', {}, bytes(d.month[0] + d.month[1])), E('span', { class: 'dl-sub' }, _('this month'))]),
dayBars(page.devSeries[d.id] ?? []),
]);
return E('article', { class: `dl-dcard clickable${d.online ? ' online' : ''}${d.disabled ? ' off' : ''}`, click: clickCard(d) }, [
@@ -67,11 +68,11 @@ export function devicesPart(page: PersonPage): HTMLElement {
? E(
'div',
{ class: 'dl-sub' },
`${KIND_LABEL[d.kind]} · created ${ago(d.created, now)} ${d.created_by === 'portal' ? 'in the portal' : 'by you'}.`,
`${kindLabel(d.kind)} · ${fmt(d.created_by === 'portal' ? _('created %s in the portal.') : _('created %s by you.'), ago(d.created, now))}`,
)
: E('div', { class: 'dl-chips-row' }, [
E('button', { type: 'button', class: 'dl-chipbtn', click: () => showDeviceQr(page, d) }, [icon('qr'), 'Show QR']),
E('button', { type: 'button', class: 'dl-chipbtn', click: () => downloadConfig(page, d) }, [icon('download'), 'Config']),
E('button', { type: 'button', class: 'dl-chipbtn', click: () => showDeviceQr(page, d) }, [icon('qr'), _('Show QR')]),
E('button', { type: 'button', class: 'dl-chipbtn', click: () => downloadConfig(page, d) }, [icon('download'), _('Config')]),
]),
]);
});
@@ -81,17 +82,19 @@ export function devicesPart(page: PersonPage): HTMLElement {
E('button', { type: 'button', class: 'dl-dslot add', click: () => addDevice(p, page.deviceOpts()) }, [
E('span', { class: 'dl-dslot-ic' }, icon('plus')),
E('span', { class: 'dl-stack' }, [
E('b', {}, 'Add device'),
E('b', {}, _('Add device')),
E(
'span',
{ class: 'dl-sub' },
over ? `Over the limit · ${p.devices.length} of ${p.device_limit}` : `${p.devices.length} of ${p.device_limit}`,
over
? `${_('Over the limit')} · ${fmt(_('%s of %s'), p.devices.length, p.device_limit)}`
: fmt(_('%s of %s'), p.devices.length, p.device_limit),
),
]),
]),
);
return E('section', { class: 'dl-devsec' }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Devices'), E('span', { class: 'dl-sub' }, `${p.online} online`)]),
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Devices')), E('span', { class: 'dl-sub' }, fmt(_('%s online'), num(p.online)))]),
E('div', { class: 'dl-dgrid' }, cards),
]);
}
+49 -36
View File
@@ -10,13 +10,14 @@ import { liveField } from '../../ui/layout';
import { nameHelp } from '../../netcheck';
import { inviteCard } from '../../invite';
import { peopleUrl } from '../../urls';
import { fmt, plural } from '../../../shared/i18n';
import type { PersonPage } from './index';
const field = (label: string, el: Node) =>
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
export function invite(page: PersonPage) {
const server = page.st.servers.find((s) => s.id === page.p.server)?.name ?? 'Home';
const server = page.st.servers.find((s) => s.id === page.p.server)?.name ?? _('Home');
void inviteCard(page.p, server);
}
@@ -32,10 +33,10 @@ export async function newLink(page: PersonPage) {
const boxes = suspect.map(
(d) => E('input', { type: 'checkbox', id: `dl-rm-${d.id}`, checked: 'checked', 'data-id': d.id }) as HTMLInputElement,
);
const body: Node[] = [E('p', {}, 'The old link stops working right away.')];
const body: Node[] = [E('p', {}, _('The old link stops working right away.'))];
if (suspect.length)
body.push(
E('p', {}, 'Devices added through the old link keep working until they are removed. Remove them too:'),
E('p', {}, _('Devices added through the old link keep working until they are removed. Remove them too:')),
E(
'div',
{ class: 'dl-checklist' },
@@ -46,33 +47,35 @@ export async function newLink(page: PersonPage) {
const remove = boxes.filter((b) => b.checked).map((b) => b.dataset.id as string);
const r = await attempt(
() => api.personRegen(p.id, remove),
remove.length ? `New link created, ${remove.length} device${remove.length === 1 ? '' : 's'} removed` : 'New link created',
remove.length
? plural(remove.length, 'New link created, %s device removed', 'New link created, %s devices removed')
: _('New link created'),
);
if (!r) return;
closeModal();
if (remove.length) await page.refresh();
if (r.link) await copyText(r.link, 'New link copied');
if (r.link) await copyText(r.link, _('New link copied'));
};
modal('Create a new link?', body, [cancelButton(), ' ', button('Create new link', go, 'negative')]);
modal(_('Create a new link?'), body, [cancelButton(), ' ', button(_('Create new link'), go, 'negative')]);
}
export function editNote(page: PersonPage) {
const input = E(
'textarea',
{ class: 'cbi-input-textarea dl-note-input', rows: 3, maxlength: 500, placeholder: 'Only you see this' },
{ class: 'cbi-input-textarea dl-note-input', rows: 3, maxlength: 500, placeholder: _('Only you see this') },
page.p.note ?? '',
) as HTMLTextAreaElement;
modal(
'Note',
_('Note'),
[input],
[
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
closeModal();
await page.patch({ note: input.value.trim() }, input.value.trim() ? 'Note saved' : 'Note removed');
await page.patch({ note: input.value.trim() }, input.value.trim() ? _('Note saved') : _('Note removed'));
},
'positive',
),
@@ -84,9 +87,9 @@ export function editNote(page: PersonPage) {
export function endSettings(page: PersonPage) {
const p = page.p;
const act = E('select', { class: 'cbi-input-select' }, [
E('option', { value: 'pause', selected: p.expire_action === 'pause' ? 'selected' : null }, 'Pause access'),
E('option', { value: 'notify', selected: p.expire_action === 'notify' ? 'selected' : null }, 'Keep access'),
E('option', { value: 'remove', selected: p.expire_action === 'remove' ? 'selected' : null }, 'Remove their devices'),
E('option', { value: 'pause', selected: p.expire_action === 'pause' ? 'selected' : null }, _('Pause access')),
E('option', { value: 'notify', selected: p.expire_action === 'notify' ? 'selected' : null }, _('Keep access')),
E('option', { value: 'remove', selected: p.expire_action === 'remove' ? 'selected' : null }, _('Remove their devices')),
]) as HTMLSelectElement;
const warn = E(
'select',
@@ -95,19 +98,19 @@ export function endSettings(page: PersonPage) {
E(
'option',
{ value: n, selected: p.expire_warn === n ? 'selected' : null },
n ? `${n} day${n === 1 ? '' : 's'} before` : 'Don’t warn',
n ? plural(n, '%s day before', '%s days before') : _('Don’t warn'),
),
),
) as HTMLSelectElement;
modal(
'When access ends',
_('When access ends'),
[
field('Then', act),
field(_('Then'), act),
E('div', { class: 'cbi-value' }, [
E('label', { class: 'cbi-value-title' }, 'Warn'),
E('label', { class: 'cbi-value-title' }, _('Warn')),
E('div', { class: 'cbi-value-field' }, [
warn,
E('div', { class: 'cbi-value-description' }, 'Shown in their portal and on the Overview.'),
E('div', { class: 'cbi-value-description' }, _('Shown in their portal and on the Overview.')),
]),
]),
],
@@ -115,10 +118,10 @@ export function endSettings(page: PersonPage) {
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
closeModal();
await page.patch({ expire_action: act.value, expire_warn: warn.value }, 'Saved');
await page.patch({ expire_action: act.value, expire_warn: warn.value }, _('Saved'));
},
'positive',
),
@@ -128,15 +131,15 @@ export function endSettings(page: PersonPage) {
export function rename(page: PersonPage) {
const input = E('input', { type: 'text', class: 'cbi-input-text', value: page.p.name, maxlength: 48 }) as HTMLInputElement;
const nameRow = liveField('Name', input, () => nameHelp(input.value, [], 'Shown in their portal and apps.'));
const nameRow = liveField(_('Name', 'person'), input, () => nameHelp(input.value, [], _('Shown in their portal and apps.')));
modal(
'Rename',
_('Rename'),
[nameRow],
[
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
const h = nameRow.help();
if (h.bad) {
@@ -144,7 +147,7 @@ export function rename(page: PersonPage) {
return;
}
// The dialog stays open on a refusal, with the name still typed.
if (await page.patch({ name: input.value.trim() }, 'Renamed')) closeModal();
if (await page.patch({ name: input.value.trim() }, _('Renamed'))) closeModal();
},
'positive',
),
@@ -160,30 +163,36 @@ export function moveToServer(page: PersonPage) {
const sel = E(
'select',
{ class: 'cbi-input-select' },
others.map((s) => E('option', { value: s.id }, `${s.name} · ${s.endpoint || 'no address'}:${s.port}`)),
others.map((s) => E('option', { value: s.id }, `${s.name} · ${s.endpoint || _('no address')}:${s.port}`)),
) as HTMLSelectElement;
const n = p.devices.length;
modal(
`Move ${p.name} to another server`,
fmt(_('Move %s to another server'), p.name),
[
field('Server', sel),
field(_('Server'), sel),
E(
'p',
{ class: 'dl-muted' },
n
? `${n} device${n === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${n === 1 ? 'it imports its' : 'they import their'} configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.`
: 'They have no devices yet: nothing else changes.',
? plural(
n,
'%s device gets a new address and stops connecting until it imports its configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.',
'%s devices get new addresses and stop connecting until they import their configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.',
)
: _('They have no devices yet: nothing else changes.'),
),
],
[
cancelButton(),
' ',
button(
'Move',
_('Move'),
async () => {
if (await page.patch({ server: sel.value }, `Moved to ${others.find((s) => s.id === sel.value)?.name ?? 'the server'}`)) {
if (
await page.patch({ server: sel.value }, fmt(_('Moved to %s'), others.find((s) => s.id === sel.value)?.name ?? _('the server')))
) {
closeModal();
if (n) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
if (n) notify(_('Devices are marked “Update config” until they import again.'), 'info', 6000);
}
},
'positive',
@@ -195,10 +204,14 @@ export function moveToServer(page: PersonPage) {
export async function remove(page: PersonPage) {
const p = page.p;
const ok = await confirmDialog(
`Delete ${p.name}?`,
`All ${p.devices.length} devices are disconnected immediately and the personal link stops working.`,
'Delete',
fmt(_('Delete %s?'), p.name),
plural(
p.devices.length,
'%s device is disconnected immediately and the personal link stops working.',
'All %s devices are disconnected immediately and the personal link stops working.',
),
_('Delete'),
true,
);
if (ok && (await attempt(() => api.personDelete(p.id), 'Deleted'))) location.href = peopleUrl(p.server);
if (ok && (await attempt(() => api.personDelete(p.id), _('Deleted')))) location.href = peopleUrl(p.server);
}
+20 -15
View File
@@ -6,6 +6,7 @@ import { dropdown, type MenuItem } from '../../ui/menu';
import { statePill } from '../../ui/badges';
import { icon } from '../../../shared/icons';
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
import { fmt } from '../../../shared/i18n';
import { copyPersonLink } from '../../invite';
import { daysTile, speedTile } from '../../widgets/tiles';
import { editNote, invite, moveToServer, newLink, remove, rename } from './dialogs';
@@ -14,26 +15,26 @@ import type { PersonPage } from './index';
export function headPart(page: PersonPage): HTMLElement {
const p = page.p;
const st = page.st;
const lastSeen = p.online ? 'online now' : p.last_seen ? `last seen ${ago(p.last_seen, st.now)}` : 'never connected';
const added = p.created ? `Added ${date(isoDay(new Date(p.created * 1000)))}` : '';
const lastSeen = p.online ? _('online now') : p.last_seen ? fmt(_('last seen %s'), ago(p.last_seen, st.now)) : _('never connected');
const added = p.created ? fmt(_('Added %s', 'date'), date(isoDay(new Date(p.created * 1000)))) : '';
// The personal link is not in the status: its actions ask for it while there is one.
const portal = p.has_link ?? st.settings.portal_enabled;
const menu: (MenuItem | null)[] = [
{ label: 'Rename', icon: icon('edit'), run: () => rename(page) },
{ label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => editNote(page) },
{ label: _('Rename'), icon: icon('edit'), run: () => rename(page) },
{ label: p.note ? _('Edit note') : _('Add note'), icon: icon('file'), run: () => editNote(page) },
// With one server there is nowhere to move to.
...(st.servers.length > 1 ? [{ label: 'Move to server…', icon: icon('server'), run: () => moveToServer(page) }] : []),
...(st.servers.length > 1 ? [{ label: _('Move to server…'), icon: icon('server'), run: () => moveToServer(page) }] : []),
...(portal
? [
null,
{ label: 'Invite card', icon: icon('qr'), run: () => invite(page) },
{ label: 'New link', icon: icon('key'), run: () => newLink(page) },
{ label: _('Invite card'), icon: icon('qr'), run: () => invite(page) },
{ label: _('New link'), icon: icon('key'), run: () => newLink(page) },
]
: []),
null,
// While paused, Resume is the page's own button (as the server's Turn on).
...(p.paused ? [] : [{ label: 'Pause', icon: icon('pause'), warn: true, run: () => page.patch({ paused: true }, 'Paused') }]),
{ label: 'Delete', icon: icon('trash'), danger: true, run: () => remove(page) },
...(p.paused ? [] : [{ label: _('Pause'), icon: icon('pause'), warn: true, run: () => page.patch({ paused: true }, _('Paused')) }]),
{ label: _('Delete'), icon: icon('trash'), danger: true, run: () => remove(page) },
];
return E('div', { class: 'dl-person-head' }, [
E('div', { class: 'dl-pagehead' }, [
@@ -41,19 +42,23 @@ export function headPart(page: PersonPage): HTMLElement {
E('span', { class: `dl-avatar lg${p.online ? ' online' : ''}` }, initials(p.name)),
E('div', { class: 'dl-stack' }, [
E('div', { class: 'dl-title-row' }, [E('h2', { class: 'dl-h1' }, p.name), statePill(p)]),
E('span', { class: 'dl-faint', title: added }, `${p.devices.length} of ${p.device_limit} devices · ${lastSeen}`),
E(
'span',
{ class: 'dl-faint', title: added },
`${fmt(N_(p.device_limit, '%s of %s device', '%s of %s devices'), p.devices.length, p.device_limit)} · ${lastSeen}`,
),
]),
]),
E('div', { class: 'dl-pcard-actions' }, [
// White, as the server's Turn on.
p.paused ? button([icon('play'), ' Resume'], () => page.patch({ paused: false }, 'Resumed'), 'add') : '',
portal ? iconButton('link', 'Copy link', () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
iconButton('more', 'More', (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
p.paused ? button([icon('play'), ` ${_('Resume')}`], () => page.patch({ paused: false }, _('Resumed')), 'add') : '',
portal ? iconButton('link', _('Copy link'), () => copyPersonLink(p.id), 'neutral', 'dl-icon-only') : '',
iconButton('more', _('More'), (ev: MouseEvent) => dropdown(ev.currentTarget as HTMLElement, menu), 'neutral', 'dl-icon-only'),
]),
]),
// Under the name block, not inside it, so the avatar centres on name + status; indented to the name.
p.note
? E('button', { type: 'button', class: 'dl-pnote', title: 'Edit note', click: () => editNote(page) }, [
? E('button', { type: 'button', class: 'dl-pnote', title: _('Edit note'), click: () => editNote(page) }, [
icon('file'),
E('span', {}, p.note),
])
@@ -68,6 +73,6 @@ export function trafficPart(page: PersonPage): HTMLElement {
const todayUse = page.series[page.series.length - 1];
return E('div', { class: `dl-person-live${p.online ? '' : ' solo'}` }, [
p.online ? speedTile(p.rate ?? [], page.st.now, todayUse ? [todayUse.rx, todayUse.tx] : [0, 0]) : '',
daysTile(page.series, `${bytes(p.month[0] + p.month[1])} this month`),
daysTile(page.series, fmt(_('%s this month'), bytes(p.month[0] + p.month[1]))),
]);
}
+6 -6
View File
@@ -64,9 +64,9 @@ export class PersonPage {
const p = this.st.people.find((x) => x.id === this.id);
if (!p)
return E('div', { class: 'dl-empty' }, [
E('h3', {}, 'Person not found'),
E('p', {}, 'They may have been removed.'),
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, 'Back to Servers'),
E('h3', {}, _('Person not found')),
E('p', {}, _('They may have been removed.')),
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, _('Back to Servers')),
]);
this.p = p;
for (const k of ['crumbs', 'head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
@@ -173,10 +173,10 @@ export class PersonPage {
/** Server / People / name: the server changes when the person is moved. */
private crumbs(): HTMLElement {
const p = this.p;
return E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
return E('nav', { class: 'dl-crumbs', 'aria-label': _('Breadcrumb') }, [
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? _('Servers')),
E('span', {}, '/'),
E('a', { href: peopleUrl(p.server) }, 'People'),
E('a', { href: peopleUrl(p.server) }, _('People')),
E('span', {}, '/'),
E('span', {}, p.name),
]);
+87 -61
View File
@@ -11,18 +11,21 @@ import { liveField } from '../../ui/layout';
import { quotaHelp } from '../../netcheck';
import { attachTip } from '../../ui/tooltip';
import { icon } from '../../../shared/icons';
import { ACCESS_LABEL, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
import { accessLabel, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
import { fmt, num, plural } from '../../../shared/i18n';
import { resetUsageDialog } from '../../logs';
import { homeAccess } from '../../access';
import { endSettings } from './dialogs';
import { circleTile, devTile, dnsPicker, netsPicker, servicesPicker } from './pickers';
import type { PersonPage } from './index';
const ACCESS_TEXT: Record<Person['access'], string> = {
internet: 'Browse the internet through your router. No access to devices at home, and home cannot reach theirs.',
lan: 'Reach devices at home, and home reaches theirs. Internet stays on their own connection.',
both: 'Home devices and the internet, all through your router. Home reaches their devices too.',
};
function accessText(a: Person['access']): string {
return {
internet: _('Browse the internet through your router. No access to devices at home, and home cannot reach theirs.'),
lan: _('Reach devices at home, and home reaches theirs. Internet stays on their own connection.'),
both: _('Home devices and the internet, all through your router. Home reaches their devices too.'),
}[a];
}
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
@@ -39,19 +42,19 @@ function endTile(page: PersonPage): HTMLElement {
}) as HTMLInputElement;
dateInput.addEventListener(
'change',
() => dateInput.value && page.patch({ expires: dateInput.value }, `Access until ${date(dateInput.value)}`),
() => dateInput.value && page.patch({ expires: dateInput.value }, fmt(_('Access until %s'), date(dateInput.value))),
);
// Extend from the current end, or from today when there is none or it has passed.
const extend = (step: 'week' | 'month' | 'year', n: number) => {
const next = shiftDay(p.expires && (left ?? -1) >= 0 ? p.expires : '', step, n, today);
void page.patch({ expires: next }, `Access until ${date(next)}`);
void page.patch({ expires: next }, fmt(_('Access until %s'), date(next)));
};
const ext = (
[
['week', 1, '+1 week'],
['month', 1, '+1 month'],
['month', 3, '+3 months'],
['year', 1, '+1 year'],
['week', 1, _('+1 week')],
['month', 1, _('+1 month')],
['month', 3, _('+3 months')],
['year', 1, _('+1 year')],
] as const
).map(([step, n, label]) => E('button', { type: 'button', class: 'dl-chipbtn', click: () => extend(step, n) }, label));
// The native date input stays hidden behind the chip and only opens its picker. It takes the
@@ -71,34 +74,40 @@ function endTile(page: PersonPage): HTMLElement {
}
},
},
[icon('calendar'), p.expires ? date(p.expires) : 'Date'],
[icon('calendar'), p.expires ? date(p.expires) : _('Date')],
),
dateInput,
]);
const action = { pause: 'pause access', notify: 'keep access', remove: 'remove their devices' }[p.expire_action];
const action = { pause: _('pause access'), notify: _('keep access'), remove: _('remove their devices') }[p.expire_action];
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [
E('span', {}, 'Access ends'),
E('span', {}, _('Access ends')),
p.expires
? E(
'span',
{ class: left != null && left < 0 ? 'dl-bad' : endsSoon(p, left) ? 'dl-warn' : 'dl-ok' },
left != null && left < 0 ? 'ended' : `${left} day${left === 1 ? '' : 's'} left`,
left != null && left < 0 ? _('ended') : plural(left ?? 0, '%s day left', '%s days left'),
)
: E('span', { class: 'dl-faint' }, 'no end date'),
: E('span', { class: 'dl-faint' }, _('no end date')),
]),
E('div', { class: 'dl-chips-row' }, [
...ext,
pick,
p.expires
? E('button', { type: 'button', class: 'dl-chipbtn', click: () => page.patch({ expires: '' }, 'No end date') }, 'No end')
? E('button', { type: 'button', class: 'dl-chipbtn', click: () => page.patch({ expires: '' }, _('No end date')) }, _('No end'))
: '',
]),
E('div', { class: 'dl-tile2-foot' }, [
E(
'span',
{ class: 'dl-muted' },
`When it ends: ${action}${p.expire_warn ? `, warn ${p.expire_warn} day${p.expire_warn === 1 ? '' : 's'} before` : ''}`,
p.expire_warn
? fmt(
N_(p.expire_warn, 'When it ends: %s, warn %s day before', 'When it ends: %s, warn %s days before'),
action,
num(p.expire_warn),
)
: fmt(_('When it ends: %s'), action),
),
E(
'a',
@@ -109,7 +118,7 @@ function endTile(page: PersonPage): HTMLElement {
endSettings(page);
},
},
'Change',
_('Change'),
),
]),
]);
@@ -121,26 +130,26 @@ function dataTile(page: PersonPage): HTMLElement {
const pct = p.quota_limit ? Math.min(100, (p.quota_used / p.quota_limit) * 100) : 0;
const bar = E('div', { class: `dl-meter${pct >= 100 ? ' bad' : pct >= 90 ? ' warn' : ''}` }, [
E('i'),
p.quota_limit ? E('span', { class: 'mark', title: 'Alert at 90%' }) : '',
p.quota_limit ? E('span', { class: 'mark', title: _('Alert at 90%') }) : '',
]);
(bar.firstChild as HTMLElement).style.width = `${pct}%`;
if (p.quota_limit)
attachTip(bar, () => [
E('div', { class: 'dl-tip-title' }, `${pct.toFixed(1)}% used`),
E('div', { class: 'dl-tip-title' }, fmt(_('%s%% used'), num(pct, 1))),
E(
'div',
{ class: 'dl-muted' },
`${bytes(p.quota_used)} of ${bytes(p.quota_limit)} · ${bytes(Math.max(0, p.quota_limit - p.quota_used))} left`,
`${fmt(_('%s of %s'), bytes(p.quota_used), bytes(p.quota_limit))} · ${fmt(_('%s left'), bytes(Math.max(0, p.quota_limit - p.quota_used)))}`,
),
E('div', { class: 'dl-faint' }, 'Alert at 90%'),
E('div', { class: 'dl-faint' }, _('Alert at 90%')),
]);
const period = seg(
[
['month', 'Monthly'],
['total', 'Total'],
['month', _('Monthly')],
['total', _('Total')],
],
p.quota_period,
{ label: 'Data limit period', cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
{ label: _('Data limit period'), cls: 'sm', optimistic: false, onChange: (v) => page.patch({ quota_period: v }) },
);
const presets = [10, 50, 100].map((gb) =>
E(
@@ -148,16 +157,16 @@ function dataTile(page: PersonPage): HTMLElement {
{
type: 'button',
class: `dl-chipbtn${p.quota_gb === gb ? ' on' : ''}`,
click: () => page.patch({ quota_gb: String(gb) }, `Data limit ${gb} GB`),
click: () => page.patch({ quota_gb: String(gb) }, fmt(_('Data limit %s GB'), num(gb))),
},
`${gb} GB`,
`${num(gb)} ${_('GB')}`,
),
);
presets.push(
E(
'button',
{ type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => page.patch({ quota_gb: '' }, 'No data limit') },
'Unlimited',
{ type: 'button', class: `dl-chipbtn${!p.quota_gb ? ' on' : ''}`, click: () => page.patch({ quota_gb: '' }, _('No data limit')) },
_('Unlimited'),
),
);
presets.push(
@@ -174,15 +183,15 @@ function dataTile(page: PersonPage): HTMLElement {
step: 'any',
value: p.quota_gb ? String(p.quota_gb) : '',
}) as HTMLInputElement;
const row = liveField('Data limit (GB)', inp, () => quotaHelp(inp.value, p.quota_period === 'month'));
const row = liveField(_('Data limit (GB)'), inp, () => quotaHelp(inp.value, p.quota_period === 'month'));
modal(
'Data limit',
_('Data limit'),
[row],
[
cancelButton(),
' ',
button(
'Save',
_('Save'),
async () => {
const h = row.help();
if (h.bad) {
@@ -190,7 +199,10 @@ function dataTile(page: PersonPage): HTMLElement {
return;
}
const v = inp.value.trim();
if (await page.patch({ quota_gb: v }, v && Number(v) > 0 ? `Data limit ${v} GB` : 'No data limit')) closeModal();
if (
await page.patch({ quota_gb: v }, v && Number(v) > 0 ? fmt(_('Data limit %s GB'), num(Number(v))) : _('No data limit'))
)
closeModal();
},
'positive',
),
@@ -199,38 +211,44 @@ function dataTile(page: PersonPage): HTMLElement {
setTimeout(() => inp.select(), 50);
},
},
'Custom',
_('Custom'),
),
);
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Data'), period]),
E('div', { class: 'dl-tile2-label' }, [E('span', {}, _('Data')), period]),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, [
bytes(used),
p.quota_limit ? E('span', { class: 'dl-faint' }, ` of ${bytes(p.quota_limit)}`) : E('span', { class: 'dl-faint' }, ' · no limit'),
p.quota_limit
? E('span', { class: 'dl-faint' }, ` ${fmt(_('of %s'), bytes(p.quota_limit))}`)
: E('span', { class: 'dl-faint' }, ` · ${_('no limit')}`),
]),
p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, 'resets on the 1st') : '',
p.quota_period === 'month' ? E('span', { class: 'dl-sub' }, _('resets on the 1st')) : '',
]),
p.quota_limit ? bar : '',
E('div', { class: 'dl-chips-row' }, presets),
p.quota_gb && p.quota_period === 'month'
? E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, p.bonus_gb ? `Includes +${p.bonus_gb} GB extra this month` : 'Need a little more this month?'),
E(
'span',
{ class: 'dl-muted' },
p.bonus_gb ? fmt(_('Includes +%s GB extra this month'), num(p.bonus_gb)) : _('Need a little more this month?'),
),
E(
'a',
{
href: '#',
click: (ev: Event) => {
ev.preventDefault();
void page.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, '+10 GB this month');
void page.patch({ bonus_gb: String((p.bonus_gb || 0) + 10) }, _('+10 GB this month'));
},
},
'+10 GB this month',
_('+10 GB this month'),
),
])
: '',
E('div', { class: 'dl-tile2-foot' }, [
E('span', { class: 'dl-muted' }, `${bytes(p.total[0] + p.total[1])} in total`),
E('span', { class: 'dl-muted' }, fmt(_('%s in total'), bytes(p.total[0] + p.total[1]))),
E(
'button',
{
@@ -238,7 +256,7 @@ function dataTile(page: PersonPage): HTMLElement {
class: 'dl-linkbtn danger',
click: () => resetUsageDialog('person', p.id, p.name, () => setTimeout(() => page.refresh(), 300)),
},
'Reset usage',
_('Reset usage'),
),
]),
]);
@@ -253,15 +271,15 @@ function hoursTile(page: PersonPage): HTMLElement {
const p = page.p;
const hoursOn = !!p.hours;
const [h1, h2] = (p.hours || '07:00-23:00').split('-');
const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1, 'aria-label': 'From' }) as HTMLInputElement;
const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2, 'aria-label': 'To' }) as HTMLInputElement;
const times = E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, 'to'), to]);
const from = E('input', { type: 'time', class: 'cbi-input-text', value: h1, 'aria-label': _('From') }) as HTMLInputElement;
const to = E('input', { type: 'time', class: 'cbi-input-text', value: h2, 'aria-label': _('To') }) as HTMLInputElement;
const times = E('div', { class: 'dl-tile2-row' }, [from, E('span', { class: 'dl-faint' }, _('to', 'time range')), to]);
const commit = () => {
const v = `${from.value}-${to.value}`;
if (v === p.hours) return;
if (!TIME.test(from.value) || !TIME.test(to.value)) return notify('Enter both times, like 07:00 and 23:00.', 'warning');
if (from.value === to.value) return notify('The start and the end must differ.', 'warning');
void page.patch({ hours: v }, `Allowed ${from.value}–${to.value}`);
if (!TIME.test(from.value) || !TIME.test(to.value)) return notify(_('Enter both times, like 07:00 and 23:00.'), 'warning');
if (from.value === to.value) return notify(_('The start and the end must differ.'), 'warning');
void page.patch({ hours: v }, fmt(_('Allowed %s–%s'), from.value, to.value));
};
times.addEventListener('focusout', (ev: FocusEvent) => {
if (!times.contains(ev.relatedTarget as Node | null)) commit();
@@ -280,23 +298,23 @@ function hoursTile(page: PersonPage): HTMLElement {
role: 'switch',
'aria-checked': hoursOn ? 'true' : 'false',
class: `dl-switch${hoursOn ? ' on' : ''}`,
'aria-label': 'Limit hours',
'aria-label': _('Limit hours'),
// Turning on shows the times to set; nothing is enforced until they are saved.
click: () => {
if (hoursOn) return page.patch({ hours: '' }, 'Any time');
if (hoursOn) return page.patch({ hours: '' }, _('Any time'));
sw.classList.add('on');
sw.setAttribute('aria-checked', 'true');
label.textContent = 'Set the hours, then press Enter';
label.textContent = _('Set the hours, then press Enter');
tile.appendChild(times);
from.focus();
},
},
E('i'),
);
const label = E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time');
const label = E('span', {}, hoursOn ? fmt(_('%s – %s (router time)'), h1, h2) : _('Any time'));
const tile = E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-row' }, [
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-tile2-label' }, 'Allowed hours'), label]),
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-tile2-label' }, _('Allowed hours')), label]),
sw,
]),
hoursOn ? times : '',
@@ -309,19 +327,27 @@ export function limitsPart(page: PersonPage): HTMLElement {
const access = seg(
(['internet', 'lan', 'both'] as const).map((a) => [
a,
[icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'), a === 'internet' ? 'Internet' : a === 'lan' ? 'Home' : 'Both'],
[
icon(a === 'internet' ? 'globe' : a === 'lan' ? 'home' : 'shield'),
a === 'internet' ? _('Internet') : a === 'lan' ? _('Home') : _('Both'),
],
]),
p.access,
{ label: 'Access', cls: 'wide', optimistic: false, onChange: (a) => page.patch({ access: a }, `Access: ${ACCESS_LABEL[a]}`) },
{
label: _('Access'),
cls: 'wide',
optimistic: false,
onChange: (a) => page.patch({ access: a }, fmt(_('Access: %s'), accessLabel(a))),
},
);
// Heading above the card, like "Devices", so both columns line up (as on the portal).
return E('section', { class: 'dl-devsec', 'aria-label': 'Access and limits' }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, 'Access & limits')]),
return E('section', { class: 'dl-devsec', 'aria-label': _('Access and limits') }, [
E('div', { class: 'dl-panel-head' }, [E('h3', {}, _('Access & limits'))]),
E('div', { class: 'dl-panel' }, [
E('div', { class: 'dl-stack gap8' }, [
E('span', { class: 'dl-tile2-label' }, 'Can reach'),
E('span', { class: 'dl-tile2-label' }, _('Can reach')),
access,
E('span', { class: 'dl-sub' }, ACCESS_TEXT[p.access]),
E('span', { class: 'dl-sub' }, accessText(p.access)),
p.access === 'lan' && page.st.services.length ? servicesPicker(page) : '',
homeAccess(p) ? netsPicker(page) : '',
p.access === 'lan' ? dnsPicker(page) : '',
+51 -32
View File
@@ -8,6 +8,7 @@ import { dropdown } from '../../ui/menu';
import { attachTip } from '../../ui/tooltip';
import { icon } from '../../../shared/icons';
import { ago, initials } from '../../../shared/format';
import { fill, fmt, plural } from '../../../shared/i18n';
import { circleDialog, circleDot, homeAccess } from '../../access';
import type { PersonPage } from './index';
@@ -19,8 +20,8 @@ export function dnsPicker(page: PersonPage): HTMLElement {
const p = page.p;
const choice = seg(
[
['device', 'Device’s own DNS'],
['home', 'Home names'],
['device', _('Device’s own DNS')],
['home', _('Home names')],
],
p.dns_mode,
{
@@ -30,7 +31,9 @@ export function dnsPicker(page: PersonPage): HTMLElement {
onChange: (v) =>
page.patch(
{ dns_mode: v },
v === 'home' ? 'Home names on — devices need their configuration again' : 'Device DNS — devices need their configuration again',
v === 'home'
? _('Home names on - devices need their configuration again')
: _('Device DNS - devices need their configuration again'),
),
},
);
@@ -41,15 +44,19 @@ export function dnsPicker(page: PersonPage): HTMLElement {
'span',
{ class: 'dl-sub' },
p.dns_mode === 'home'
? [
'Names like ',
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
' work. Internet names are resolved at home, so they depend on the tunnel',
fb
? [' (', E('span', { class: 'dl-mono' }, fb), ' takes over when it is down).']
: ' — with no fallback set, they stop when it is down.',
]
: 'Internet keeps working exactly as without the VPN. Reach home devices by IP address.',
? fb
? fill(
_('Names like %s work. Internet names are resolved at home, so they depend on the tunnel (%s takes over when it is down).'),
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
E('span', { class: 'dl-mono' }, fb),
)
: fill(
_(
'Names like %s work. Internet names are resolved at home, so they depend on the tunnel - with no fallback set, they stop when it is down.',
),
E('span', { class: 'dl-mono' }, `nas.${page.st.settings.domain}`),
)
: _('Internet keeps working exactly as without the VPN. Reach home devices by IP address.'),
),
]);
}
@@ -72,11 +79,11 @@ export function netsPicker(page: PersonPage): HTMLElement | '' {
() => {
const next = new Set(picked);
if (!next.delete(h.dev)) next.add(h.dev);
if (!next.size) return notify('Keep at least one network, or choose Internet only.', 'warning', 5000);
if (!next.size) return notify(_('Keep at least one network, or choose Internet only.'), 'warning', 5000);
const list = next.size === all.length ? [] : [...next];
void page.patch(
{ home_nets: list },
list.length ? `${p.name} reaches ${list.join(', ')}` : `${p.name} reaches every home network`,
list.length ? fmt(_('%s reaches %s'), p.name, list.join(', ')) : fmt(_('%s reaches every home network'), p.name),
);
},
{ title: h.nets.join(', ') },
@@ -87,8 +94,8 @@ export function netsPicker(page: PersonPage): HTMLElement | '' {
'span',
{ class: 'dl-sub' },
p.home_nets?.length
? `Home networks ${p.name} reaches. Networks added to the server later stay out.`
: `Home networks ${p.name} reaches: all of them. Untick one to keep ${p.name} out of it.`,
? fmt(_('Home networks %s reaches. Networks added to the server later stay out.'), p.name)
: fmt(_('Home networks %s reaches: all of them. Untick one to keep %s out of it.'), p.name, p.name),
),
]);
}
@@ -108,7 +115,7 @@ export function servicesPicker(page: PersonPage): HTMLElement {
// A copy: the chips show the saved choice until the router has it (a failed save changes nothing).
const next = new Set(chosen);
if (!next.delete(sv.id)) next.add(sv.id);
void page.patch({ services: [...next] }, next.size ? 'Home services updated' : 'Whole home network');
void page.patch({ services: [...next] }, next.size ? _('Home services updated') : _('Whole home network'));
},
{ title: `${sv.address}${sv.ports.length ? ` · ${sv.ports.join(', ')}` : ''}` },
),
@@ -117,7 +124,7 @@ export function servicesPicker(page: PersonPage): HTMLElement {
E(
'span',
{ class: 'dl-sub' },
chosen.size ? 'Only the selected services at home.' : 'Whole home network. Pick services to narrow it down.',
chosen.size ? _('Only the selected services at home.') : _('Whole home network. Pick services to narrow it down.'),
),
]);
}
@@ -141,20 +148,22 @@ export function circleTile(page: PersonPage): HTMLElement | '' {
...circles.map((c) => ({
label: c.name,
icon: circleDot(c),
run: () => c.id !== p.circle && page.patch({ circle: c.id }, `${p.name} is in ${c.name}`),
run: () => c.id !== p.circle && page.patch({ circle: c.id }, fmt(_('%s is in %s'), p.name, c.name)),
})),
p.circle ? { label: 'No circle', icon: icon('x'), run: () => page.patch({ circle: '' }, `${p.name} is in no circle`) } : null,
{ label: 'New circle', icon: icon('plus'), run: () => circleDialog(st, p.server, null, () => page.refresh()) },
p.circle
? { label: _('No circle'), icon: icon('x'), run: () => page.patch({ circle: '' }, fmt(_('%s is in no circle'), p.name)) }
: null,
{ label: _('New circle'), icon: icon('plus'), run: () => circleDialog(st, p.server, null, () => page.refresh()) },
]),
},
'Change',
_('Change'),
);
// As the other tiles: the name is the value; who is in it as avatars.
const people = ci ? st.people.filter((x) => x.circle === ci.id && homeAccess(x)) : [p];
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, [E('span', {}, 'Devices see each other'), change]),
E('div', { class: 'dl-tile2-label' }, [E('span', {}, _('Devices see each other')), change]),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, ci ? ci.name : 'No circle'),
E('span', { class: 'dl-tile2-value' }, ci ? ci.name : _('No circle')),
E(
'span',
{ class: 'dl-avstack', title: people.map((x) => x.name).join(', ') },
@@ -164,7 +173,11 @@ export function circleTile(page: PersonPage): HTMLElement | '' {
E(
'span',
{ class: 'dl-sub' },
!ci ? `Only ${p.name}'s own devices` : mates.length ? [p.name, ...mates].join(', ') : `Nobody else in ${ci.name} yet`,
!ci
? fmt(_("Only %s's own devices"), p.name)
: mates.length
? [p.name, ...mates].join(', ')
: fmt(_('Nobody else in %s yet'), ci.name),
),
]);
}
@@ -180,11 +193,17 @@ export function devTile(page: PersonPage): HTMLElement {
const over = i >= p.device_limit;
const slot = E('i', { class: over ? 'over' : d ? 'used' : '' });
attachTip(slot, () => [
E('div', { class: 'dl-tip-title' }, d ? `${d.name}${over ? ' · over the limit' : ''}` : 'Free slot'),
E('div', { class: 'dl-tip-title' }, d ? `${d.name}${over ? ` · ${_('over the limit')}` : ''}` : _('Free slot')),
E(
'div',
{ class: 'dl-muted' },
d ? (d.online ? 'Connected' : d.handshake ? `Last seen ${ago(d.handshake, now)}` : 'Not set up yet') : 'They can add a device here',
d
? d.online
? _('Connected')
: d.handshake
? fmt(_('Last seen %s'), ago(d.handshake, now))
: _('Not set up yet')
: _('They can add a device here'),
),
]);
slots.appendChild(slot);
@@ -194,7 +213,7 @@ export function devTile(page: PersonPage): HTMLElement {
'button',
{
type: 'button',
'aria-label': 'Allow fewer devices',
'aria-label': _('Allow fewer devices'),
disabled: p.device_limit <= floor ? 'disabled' : null,
click: () => page.patch({ device_limit: String(p.device_limit - 1) }),
},
@@ -202,11 +221,11 @@ export function devTile(page: PersonPage): HTMLElement {
);
if (p.device_limit <= floor && p.devices.length > 1)
attachTip(minus, () => [
E('div', { class: 'dl-tip-title' }, `${p.devices.length} devices in use`),
E('div', { class: 'dl-muted' }, 'Remove a device first to lower the limit'),
E('div', { class: 'dl-tip-title' }, plural(p.devices.length, '%s device in use', '%s devices in use')),
E('div', { class: 'dl-muted' }, _('Remove a device first to lower the limit')),
]);
return E('div', { class: 'dl-tile2' }, [
E('div', { class: 'dl-tile2-label' }, 'Devices'),
E('div', { class: 'dl-tile2-label' }, _('Devices')),
E('div', { class: 'dl-tile2-row' }, [
E('span', { class: 'dl-tile2-value' }, [String(p.devices.length), E('span', { class: 'dl-faint' }, ` / ${p.device_limit}`)]),
E('div', { class: 'dl-stepper' }, [
@@ -215,7 +234,7 @@ export function devTile(page: PersonPage): HTMLElement {
'button',
{
type: 'button',
'aria-label': 'Allow more devices',
'aria-label': _('Allow more devices'),
disabled: p.device_limit >= 32 ? 'disabled' : null,
click: () => page.patch({ device_limit: String(p.device_limit + 1) }),
},
+156 -116
View File
@@ -16,6 +16,7 @@ import { card, firstBad, group, liveRow, needRow, row } from '../ui/layout';
import { dnsHelp, endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
import { icon } from '../../shared/icons';
import { ago, duration } from '../../shared/format';
import { fmt, locale, plural } from '../../shared/i18n';
import { accessCards } from '../interfaces';
import { checkAccess, whoReaches } from '../access';
import { defaultMethod, methodPicker } from '../disguise';
@@ -27,13 +28,10 @@ import { PeoplePage } from './people';
/** `awg` is the server's core section (named after its core; the key stays for old links). */
type Section = 'overview' | 'people' | 'connection' | 'access' | 'awg';
const SECTIONS: [Section, string][] = [
['overview', 'Overview'],
['people', 'People'],
['connection', 'Connection'],
['access', 'Access'],
['awg', ''],
];
const SECTIONS: Section[] = ['overview', 'people', 'connection', 'access', 'awg'];
/** A section's tab; the core's own is named after the core. */
const sectionLabel = (k: Exclude<Section, 'awg'>): string =>
({ overview: _('Overview'), people: _('People'), connection: _('Connection'), access: _('Access') })[k];
/** Section names from before the regrouping, for old links. */
const OLD_SECTIONS: Record<string, Section> = {
general: 'connection',
@@ -82,7 +80,7 @@ export class ServerPage {
const q = new URLSearchParams(location.search);
const raw = q.get('section') ?? '';
const want = (OLD_SECTIONS[raw] ?? raw) as Section;
if (SECTIONS.some(([k]) => k === want)) this.section = want;
if (SECTIONS.includes(want)) this.section = want;
this.srvId = (st.servers.find((x) => x.id === q.get('server')) ?? st.servers[0]).id;
dom.content(this.root, [this.tabsEl, this.headEl, this.secEl, this.bodyEl]);
this.paint();
@@ -146,7 +144,7 @@ export class ServerPage {
const srv = this.current();
dom.content(
this.tabsEl,
E('div', { class: 'dl-srvtabs', role: 'tablist', 'aria-label': 'Servers' }, [
E('div', { class: 'dl-srvtabs', role: 'tablist', 'aria-label': _('Servers') }, [
...this.st.servers.map((x) =>
E(
'button',
@@ -164,7 +162,7 @@ export class ServerPage {
[E('i', { class: `dot ${!x.enabled ? 'warn' : x.up ? 'ok' : 'bad'}` }), E('b', {}, x.name)],
),
),
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), 'Add server']),
E('button', { type: 'button', class: 'dl-srvtab add', click: () => this.addServer() }, [icon('plus'), _('Add server')]),
]),
);
}
@@ -175,8 +173,8 @@ export class ServerPage {
this.secEl,
E(
'div',
{ class: 'dl-seg dl-srvsections', role: 'tablist', 'aria-label': 'Server' },
SECTIONS.map(([k, t]) =>
{ class: 'dl-seg dl-srvsections', role: 'tablist', 'aria-label': _('Server') },
SECTIONS.map((k) =>
E(
'button',
{
@@ -187,7 +185,7 @@ export class ServerPage {
'aria-selected': k === this.section ? 'true' : 'false',
click: () => this.showSection(k),
},
k === 'awg' ? core.label : t,
k === 'awg' ? core.label : sectionLabel(k),
),
),
),
@@ -241,7 +239,7 @@ export class ServerPage {
void pp.update();
return pp.el;
}
const holder = E('div', {}, E('p', { class: 'dl-muted' }, 'Loading people…'));
const holder = E('div', {}, E('p', { class: 'dl-muted' }, _('Loading people…')));
const page = (this.pp[srv.id] ??= new PeoplePage());
page
.embed(st, srv.id)
@@ -252,7 +250,7 @@ export class ServerPage {
.catch((e) => {
// Try again on the next visit instead of keeping a broken page.
delete this.pp[srv.id];
dom.content(holder, E('p', { class: 'dl-muted' }, `Couldn't show people: ${errorText(e)}`));
dom.content(holder, E('p', { class: 'dl-muted' }, fmt(_("Couldn't show people: %s"), errorText(e))));
});
return holder;
},
@@ -273,8 +271,8 @@ export class ServerPage {
const actions = E('div', { class: 'dl-actions' }, [
!srv.enabled
? button(
[icon('play'), ' Turn on'],
() => this.save(srv, { enabled: '1' }, 'Server turned on'),
[icon('play'), ` ${_('Turn on')}`],
() => this.save(srv, { enabled: '1' }, _('Server turned on')),
// White, as the other main actions (Add person).
'add',
)
@@ -288,7 +286,7 @@ export class ServerPage {
'span',
// Off on purpose is a warning (yellow), not a failure (red).
{ class: `dl-pill ${!srv.enabled ? 'warn' : srv.up ? 'ok' : 'bad'}` },
!srv.enabled ? 'Turned off' : srv.up ? 'Running' : srv.blocked ? 'Can’t start' : 'Not running',
!srv.enabled ? _('Turned off') : srv.up ? _('Running') : srv.blocked ? _('Can’t start') : _('Not running'),
),
E('span', { class: 'dl-spacer' }),
actions,
@@ -296,78 +294,82 @@ export class ServerPage {
E('div', { class: 'dl-addrbar' }, [
E(
'button',
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address', click: () => copyText(addr, 'Address copied') },
{ type: 'button', class: 'dl-addrbar-seg main', title: _('Copy address'), click: () => copyText(addr, _('Address copied')) },
[icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')],
),
part(coreOf(srv).id === 'awg' ? 'amneziawg' : 'tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
srv.up ? part('clock', [`up ${duration(srv.uptime)}`]) : '',
srv.up ? part('clock', [fmt(_('up %s'), duration(srv.uptime))]) : '',
]),
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
srv.blocked ? E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, `${srv.name} ${srv.blocked}.`)]) : '',
srv.blocked ? E('div', { class: 'dl-note warn' }, [icon('alert'), E('span', {}, srv.blocked)]) : '',
]);
}
async save(srv: Server, values: Record<string, unknown>, ok = 'Saved') {
async save(srv: Server, values: Record<string, unknown>, ok = _('Saved')) {
if (await attempt(() => api.serverUpdate(srv.id, values), ok)) await this.refresh();
}
/** The name, where devices find the router, DNS; then the danger zone. */
connection(srv: Server): HTMLElement {
const name = input(srv.name, { placeholder: 'Home' });
const name = input(srv.name, { placeholder: _('Home') });
const endpoint = input(srv.endpoint, { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text dl-mono' });
const dns = input(srv.dns.join(', '), { placeholder: _('This router (recommended)'), class: 'cbi-input-text dl-mono' });
const people = this.st.people.filter((p) => p.server === srv.id).length;
const toggle = button(
[icon(srv.enabled ? 'pause' : 'play'), srv.enabled ? ' Turn off' : ' Turn on'],
[icon(srv.enabled ? 'pause' : 'play'), ` ${srv.enabled ? _('Turn off') : _('Turn on')}`],
async () => {
if (
srv.enabled &&
!(await confirmDialog(
`Turn off ${srv.name}?`,
`The tunnel stops and ${people} ${people === 1 ? 'person is' : 'people are'} disconnected until you turn it back on. Nothing is deleted.`,
'Turn off',
fmt(_('Turn off %s?'), srv.name),
plural(
people,
'The tunnel stops and %s person is disconnected until you turn it back on. Nothing is deleted.',
'The tunnel stops and %s people are disconnected until you turn it back on. Nothing is deleted.',
),
_('Turn off'),
true,
))
)
return;
await this.save(srv, { enabled: srv.enabled ? '0' : '1' }, srv.enabled ? 'Server turned off' : 'Server turned on');
await this.save(srv, { enabled: srv.enabled ? '0' : '1' }, srv.enabled ? _('Server turned off') : _('Server turned on'));
},
srv.enabled ? 'negative' : 'positive',
);
const portalHost = this.st.settings.portal_host;
const nameRow = liveRow('Name', name, () => nameHelp(name.value, [], 'Shown to people in their portal and apps.'));
const nameRow = liveRow(_('Name'), name, () => nameHelp(name.value, [], _('Shown to people in their portal and apps.')));
// Where the address points is checked on the router as it is typed (debounced).
const ep = endpointProbe(
() => ({ host: endpoint.value, port: srv.port, id: srv.id }),
(h, id, port) => api.endpointProbe(h, id, port),
() => epRow.refresh(),
{ empty: portalHost ? `Empty = the portal’s address (${portalHost}).` : 'Empty = the portal’s address.' },
{ empty: portalHost ? fmt(_('Empty = the portal’s address (%s).'), portalHost) : _('Empty = the portal’s address.') },
);
const epRow = liveRow('Public address', endpoint, ep.help);
const epRow = liveRow(_('Public address'), endpoint, ep.help);
endpoint.addEventListener('input', ep.schedule);
ep.schedule();
const reached = srv.reached
? `Reached from the internet ${ago(srv.reached, this.st.now)}.`
: 'Never reached from the internet yet — test with a phone on mobile data.';
const dnsRow = liveRow('DNS for devices', dns, () => dnsHelp(dns.value, srv.address));
? fmt(_('Reached from the internet %s.'), ago(srv.reached, this.st.now))
: _('Never reached from the internet yet - test with a phone on mobile data.');
const dnsRow = liveRow(_('DNS for devices'), dns, () => dnsHelp(dns.value, srv.address));
return E('div', { class: 'dl-stack gap16' }, [
card(
'Connection',
_('Connection'),
[
E('p', { class: 'dl-muted' }, 'The name people see, where devices find the router, and DNS. The port is on AmneziaWG.'),
group('router', 'Server', 'What people see', [nameRow]),
E('p', { class: 'dl-muted' }, _('The name people see, where devices find the router, and DNS. The port is on AmneziaWG.')),
group('router', _('Server'), _('What people see'), [nameRow]),
group(
'globe',
'Devices connect to',
'A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)',
_('Devices connect to'),
_('A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)'),
[epRow, E('div', { class: `dl-sub ${srv.reached ? 'ok' : 'warn'}` }, reached)],
),
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [dnsRow]),
group('file', _('For every device'), _('Changing it marks devices “Update config” until they import again'), [dnsRow]),
],
[
E('span'),
button(
'Save',
_('Save'),
() => {
const bad = firstBad([nameRow, epRow, dnsRow]);
if (bad) {
@@ -381,49 +383,58 @@ export class ServerPage {
],
),
card(
'Danger zone',
_('Danger zone'),
[
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, srv.enabled ? 'Turn off this server' : 'This server is off'),
E('span', { class: 'dl-setrow-label' }, srv.enabled ? _('Turn off this server') : _('This server is off')),
E(
'span',
{ class: 'dl-sub' },
srv.enabled
? 'Stops the tunnel and disconnects everyone on it. Settings and people are kept.'
: 'Nobody can connect. Turn it on to bring the tunnel back.',
? _('Stops the tunnel and disconnects everyone on it. Settings and people are kept.')
: _('Nobody can connect. Turn it on to bring the tunnel back.'),
),
]),
E('div', { class: 'dl-setrow-ctl' }, toggle),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Change the tunnel network'),
E('span', { class: 'dl-setrow-label' }, _('Change the tunnel network')),
E(
'span',
{ class: 'dl-sub' },
`Devices have ${rangeOf(srv.subnet)}.x addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.`,
fmt(
_(
'Devices have %s addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.',
),
`${rangeOf(srv.subnet)}.x`,
),
),
]),
E(
'div',
{ class: 'dl-setrow-ctl' },
button([icon('edit'), ' Change'], () => this.changeSubnet(srv), 'negative'),
button([icon('edit'), ` ${_('Change')}`], () => this.changeSubnet(srv), 'negative'),
),
]),
E('div', { class: 'dl-setrow' }, [
E('div', { class: 'dl-stack' }, [
E('span', { class: 'dl-setrow-label' }, 'Remove server'),
E('span', { class: 'dl-setrow-label' }, _('Remove server')),
E(
'span',
{ class: 'dl-sub' },
`Removes the tunnel, its firewall rules and ${people} ${people === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`,
plural(
people,
'Removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.',
'Removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first.',
),
),
]),
E(
'div',
{ class: 'dl-setrow-ctl' },
button([icon('trash'), ' Remove'], () => this.remove(srv), 'negative'),
button([icon('trash'), ` ${_('Remove')}`], () => this.remove(srv), 'negative'),
),
]),
],
@@ -483,24 +494,28 @@ export class ServerPage {
const nets = taken.networks ?? [];
const devices = this.st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
const range = input(rangeOf(srv.subnet), { class: 'cbi-input-text dl-mono dl-w-range' });
const rangeRow = liveRow('Address range', range, () => rangeHelp(range.value, nets, ''));
const rangeRow = liveRow(_('Address range'), range, () => rangeHelp(range.value, nets, ''));
modal(
'Change the tunnel network',
_('Change the tunnel network'),
[
rangeRow,
E(
'p',
{ class: 'dl-muted' },
devices
? `${devices} device${devices === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).`
: 'No devices on this server yet: nothing else changes.',
? plural(
devices,
'%s device gets a new address and stops connecting until it imports its configuration again (from their personal link or from you).',
'%s devices get new addresses and stop connecting until they import their configuration again (from their personal link or from you).',
)
: _('No devices on this server yet: nothing else changes.'),
),
],
[
cancelButton(),
' ',
button(
'Change',
_('Change'),
async () => {
const h = rangeRow.help();
if (h.bad) {
@@ -512,9 +527,9 @@ export class ServerPage {
closeModal();
return;
}
if (await attempt(() => api.serverUpdate(srv.id, { subnet }), 'Tunnel network changed')) {
if (await attempt(() => api.serverUpdate(srv.id, { subnet }), _('Tunnel network changed'))) {
closeModal();
if (devices) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
if (devices) notify(_('Devices are marked “Update config” until they import again.'), 'info', 6000);
await this.refresh();
}
},
@@ -528,22 +543,26 @@ export class ServerPage {
async remove(srv: Server) {
const people = this.st.people.filter((p) => p.server === srv.id);
modal(
`Remove ${srv.name}?`,
fmt(_('Remove %s?'), srv.name),
[
E(
'p',
{},
`This removes the tunnel, its firewall rules and ${people.length} ${people.length === 1 ? 'person' : 'people'} with all their devices. A backup is made first.`,
plural(
people.length,
'This removes the tunnel, its firewall rules and %s person with all their devices. A backup is made first.',
'This removes the tunnel, its firewall rules and %s people with all their devices. A backup is made first.',
),
),
],
[
cancelButton(),
' ',
button(
'Remove',
_('Remove'),
async () => {
closeModal();
if (await attempt(() => api.serverDelete(srv.id), 'Server removed'))
if (await attempt(() => api.serverDelete(srv.id), _('Server removed')))
setTimeout(() => {
location.href = url();
}, 800);
@@ -584,13 +603,15 @@ export class ServerPage {
portHelp(
state.port,
d.udp_taken ?? [],
`Opened on the WAN firewall automatically.${state.port === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
state.port === 4500
? `${_('Opened on the WAN firewall automatically.')} ${_('4500 is IPsec’s port: most networks let it through.')}`
: _('Opened on the WAN firewall automatically.'),
);
const FROM: Record<string, string> = {
ddns: 'From your DDNS name.',
cert: 'From your Let’s Encrypt certificate.',
wan: 'Your WAN address now — it may change; a DDNS name is better.',
portal: 'The portal’s address.',
ddns: _('From your DDNS name.'),
cert: _('From your Let’s Encrypt certificate.'),
wan: _('Your WAN address now - it may change; a DDNS name is better.'),
portal: _('The portal’s address.'),
};
const ep = endpointProbe(
() => ({ host: state.endpoint, port: state.port }),
@@ -605,10 +626,14 @@ export class ServerPage {
? needRow(
'alert',
'warn',
d.wan_kind === 'cgnat' ? 'Your router has no public address (CGNAT)' : `Your router is behind another router (WAN ${d.wan_ip})`,
d.wan_kind === 'cgnat'
? '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.'
: 'Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.',
? _('Your router has no public address (CGNAT)')
: fmt(_('Your router is behind another router (WAN %s)'), d.wan_ip),
d.wan_kind === 'cgnat'
? _(
'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.',
)
: _('Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.'),
'',
)
: '';
@@ -616,7 +641,11 @@ export class ServerPage {
d.awg_state?.tools && d.awg_state.handler === false
? E('div', { class: 'dl-note warn' }, [
icon('alert'),
E('span', {}, 'Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
E(
'span',
{},
_('Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
),
])
: '';
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
@@ -636,27 +665,33 @@ export class ServerPage {
type Page = { id: string; title: string; render: () => Node; check?: () => string | null };
const serverPage: Page = {
id: 'server',
title: 'Server',
title: _('Server'),
render: () =>
E('div', { class: 'dl-wizard-groups' }, [
E(
'p',
{ class: 'dl-muted' },
extra
? '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.'
: 'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
? _(
'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.',
)
: _(
'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
),
),
group('router', 'Server', 'What people see', [
liveRow('Name', field('name'), () => nameHelp(state.name, [], 'Shown to people in their portal and apps.')),
group('router', _('Server'), _('What people see'), [
liveRow(_('Name'), field('name'), () => nameHelp(state.name, [], _('Shown to people in their portal and apps.'))),
]),
group(
'globe',
'Devices connect to',
'A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT',
_('Devices connect to'),
_(
'A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT',
),
[
(() => {
const el = field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
epRow = liveRow('Public address', el, ep.help);
epRow = liveRow(_('Public address'), el, ep.help);
el.addEventListener('input', ep.schedule);
ep.schedule();
return epRow;
@@ -668,9 +703,9 @@ export class ServerPage {
]),
check: () => {
const n = nameHelp(state.name);
if (n.bad) return `Name: ${n.text}`;
if (n.bad) return fmt(_('Name: %s'), n.text);
const h = hostHelp(state.endpoint, state.port);
return h.bad ? `Public address: ${h.text}` : null;
return h.bad ? fmt(_('Public address: %s'), h.text) : null;
},
};
const awgPage: Page = {
@@ -678,50 +713,50 @@ export class ServerPage {
title: 'AmneziaWG',
render: () =>
E('div', { class: 'dl-wizard-groups' }, [
group('globe', 'Listening', 'Where devices reach AmneziaWG from the internet', [
liveRow('UDP port', field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), portHelpNow),
group('globe', _('Listening'), _('Where devices reach AmneziaWG from the internet'), [
liveRow(_('UDP port'), field('port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' }), portHelpNow),
]),
group('network', 'Tunnel network', 'Addresses devices get inside the tunnel', [
group('network', _('Tunnel network'), _('Addresses devices get inside the tunnel'), [
(() => {
const el = field('range', {
class: 'cbi-input-text dl-w-range dl-mono',
'aria-label': 'First three numbers of the device addresses',
'aria-label': _('First three numbers of the device addresses'),
});
return liveRow(
'Device addresses',
_('Device addresses'),
el,
rangeHelpNow,
E('span', { class: 'dl-suffixed' }, [el, E('span', { class: 'dl-mono' }, '.x')]),
);
})(),
]),
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
group('shield', _('Disguise'), _('So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard'), [
methodPicker(d.awg, state.preset, (m) => (state.preset = m), undefined, d.awg_state?.tools !== false),
]),
]),
check: () => {
const p = portHelpNow();
if (p.bad) return `UDP port: ${p.text}`;
if (p.bad) return fmt(_('UDP port: %s'), p.text);
const r = rangeHelpNow();
return r.bad ? `Device addresses: ${r.text}` : null;
return r.bad ? fmt(_('Device addresses: %s'), r.text) : null;
},
};
const portalPage: Page = {
id: 'portal',
title: 'Portal',
title: _('Portal'),
render: () => {
const portalPort = field('portal_port', { inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
const portRow = liveRow('Listening port', portalPort, portalHelpNow);
const portRow = liveRow(_('Listening port'), portalPort, portalHelpNow);
portRow.hidden = !state.portal;
// Off | On, Off first: the same segmented control as in Settings.
const onOff = seg(
[
['off', 'Off'],
['on', 'On'],
['off', _('Off')],
['on', _('On')],
],
state.portal ? 'on' : 'off',
{
label: 'Personal portal',
label: _('Personal portal'),
onChange: (v) => {
state.portal = v === 'on';
portRow.hidden = !state.portal;
@@ -729,15 +764,17 @@ export class ServerPage {
},
);
return E('div', { class: 'dl-wizard-groups' }, [
group('home', 'Internet like a home device', 'How devices reach the internet', [
group('home', _('Internet like a home device'), _('How devices reach the internet'), [
row(
'Through the home network',
sw(state.lan_like, 'Internet like a home device', (v) => (state.lan_like = v)),
'Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.',
_('Through the home network'),
sw(state.lan_like, _('Internet like a home device'), (v) => (state.lan_like = v)),
_(
'Whatever handles home traffic on this router (proxies, filters, DNS) handles theirs too. Change it later under Servers → Access.',
),
),
]),
group('link', 'Personal portal', 'A page where each person adds their own devices with their personal link', [
row('Portal', onOff, 'Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.'),
group('link', _('Personal portal'), _('A page where each person adds their own devices with their personal link'), [
row(_('Portal'), onOff, _('Off: only you add devices, from LuCI. On: people manage their devices within the limits you set.')),
portRow,
]),
]);
@@ -745,7 +782,7 @@ export class ServerPage {
check: () => {
if (!state.portal) return null;
const h = portalHelpNow();
return h.bad ? `Portal port: ${h.text}` : null;
return h.bad ? fmt(_('Portal port: %s'), h.text) : null;
},
};
const pages = (): Page[] => [serverPage, awgPage, extra ? null : portalPage].filter((x): x is Page => x != null);
@@ -757,9 +794,12 @@ export class ServerPage {
needRow(
'shield',
'bad',
'AmneziaWG isn’t installed',
`The tunnel needs ${missing.join(' and ')}. Install the build made for this firmware, then create the server.`,
button('Install', () => installAwg(() => location.reload()), 'positive'),
_('AmneziaWG isn’t installed'),
fmt(
_('The tunnel needs %s. Install the build made for this firmware, then create the server.'),
new Intl.ListFormat(locale(), { type: 'conjunction' }).format(missing),
),
button(_('Install'), () => installAwg(() => location.reload()), 'positive'),
),
])
: aw && !aw.loaded
@@ -767,9 +807,9 @@ export class ServerPage {
needRow(
'shield',
'warn',
'AmneziaWG’s kernel module doesn’t load on this firmware',
'Try another build in Components, or update OpenWrt. The server can’t start until it loads.',
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/updates') }, 'Open Components'),
_('AmneziaWG’s kernel module doesn’t load on this firmware'),
_('Try another build in Components, or update OpenWrt. The server can’t start until it loads.'),
E('a', { class: 'cbi-button cbi-button-neutral', href: L.url('admin/network/dawnline/updates') }, _('Open Components')),
),
])
: '';
@@ -778,7 +818,7 @@ export class ServerPage {
const ps = pages();
if (step >= ps.length) step = ps.length - 1;
dom.content(root, [
E('h2', {}, extra ? 'Add a server' : 'Set up Dawnline'),
E('h2', {}, extra ? _('Add a server') : _('Set up Dawnline')),
awgNotice,
E(
'div',
@@ -793,17 +833,17 @@ export class ServerPage {
E('div', { class: 'dl-panel' }, ps[step].render()),
E('div', { class: 'dl-actions' }, [
step > 0
? button('Back', () => {
? button(_('Back'), () => {
step--;
paint();
})
: onCancel
? button('Cancel', onCancel)
? button(_('Cancel'), onCancel)
: '',
E('span', { class: 'dl-spacer' }),
step < ps.length - 1
? button(
'Next',
_('Next'),
() => {
const err = ps[step].check?.();
if (err) {
@@ -816,7 +856,7 @@ export class ServerPage {
'positive',
)
: button(
'Create server',
_('Create server'),
async () => {
for (const pg of ps) {
const err = pg.check?.();
@@ -843,11 +883,11 @@ export class ServerPage {
extra ? undefined : state.portal,
extra ? undefined : state.portal_port,
),
'Server created',
_('Server created'),
);
if (!r) return;
// A network restart drops the connection to LuCI for a few seconds.
if (r.network_restart) notify('Restarting the network so it knows AmneziaWG: back in a few seconds');
if (r.network_restart) notify(_('Restarting the network so it knows AmneziaWG: back in a few seconds'));
setTimeout(
() => {
location.href = url(r.id);
@@ -856,7 +896,7 @@ export class ServerPage {
);
},
'positive',
{ disabled: missing.length > 0, title: missing.length ? 'Install AmneziaWG first' : null },
{ disabled: missing.length > 0, title: missing.length ? _('Install AmneziaWG first') : null },
),
]),
]);
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more