From f8130e39a83a4244830488b0ae9dbf341e12fcf8 Mon Sep 17 00:00:00 2001 From: Aemeath <35622087+tickcount@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:46:58 +0300 Subject: [PATCH] Dawnline 0.18.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add V2RayTun to a device's set-up on Android: its awg:// link as a code and to copy, in the portal and in the admin (phones, tablets and other devices), with the server's IP, which its Android app needs; not with the Maximum disguise. Its Windows app is ready but stays off until it gives the tunnel the server's DNS. - Portal: show V2RayTun's Telegram channel beside Google Play. - Make WireGuard part of AmneziaWG's choice when the disguise is off: the same file and code, both apps named in the steps, WireGuard's store a tap away; a router still picks its package. - Portal: Reconnect asks again what the device is and about LAN Bypass, and LAN Bypass switches from a device's ⋯ menu, in a group of its own between the copy actions and Rename, Reconnect, Remove (the keys stay; the device takes its updated configuration). - Turn LAN Bypass on by default for new devices, in the portal and the admin. - Portal: an app's name too long for the picker fades at its edge and glides to its end on hover or tap; two store buttons stack where they do not fit side by side; the month chart's "Today" stays inside its axis. - Write to the router's system log by level (Settings → Logs & history → System log: errors, warnings, normal, verbose): the service starting and stopping, every apply with its time, network, firewall, nftables and peer changes, changed settings and portal errors, in English whatever the admin's language, with keys masked. - Activity: say what a device's change on the portal was (LAN Bypass on or off, its type). - Demo: build again after a force-pushed main instead of failing on the commit that is gone. --- DESIGN.md | 27 ++-- README.md | 14 +- README_ru.md | 15 +- package/luci-app-dawnline/Makefile | 2 +- package/luci-app-dawnline/po/ru/dawnline.po | 101 ++++++++++++++ .../po/templates/dawnline.pot | 101 ++++++++++++++ .../root/etc/init.d/dawnline | 38 +++++- .../luci-app-dawnline/root/usr/bin/dawnline | 4 +- .../root/usr/libexec/dawnline/agent | 17 ++- .../root/usr/libexec/dawnline/heartbeat | 2 +- .../root/usr/libexec/dawnline/postupdate | 6 +- .../root/usr/share/ucode/dawnline/apply.uc | 74 ++++++++-- .../root/usr/share/ucode/dawnline/awg.uc | 30 +++- .../root/usr/share/ucode/dawnline/core.uc | 20 +++ .../root/usr/share/ucode/dawnline/devices.uc | 49 +++++-- .../root/usr/share/ucode/dawnline/fw.uc | 32 ++++- .../root/usr/share/ucode/dawnline/live.uc | 45 +++++- .../root/usr/share/ucode/dawnline/lookup.uc | 12 ++ .../root/usr/share/ucode/dawnline/loop.uc | 18 ++- .../root/usr/share/ucode/dawnline/migrate.uc | 4 +- .../root/usr/share/ucode/dawnline/netifd.uc | 20 ++- .../root/usr/share/ucode/dawnline/nft.uc | 70 +++++++++- .../root/usr/share/ucode/dawnline/portal.uc | 42 +++++- .../root/usr/share/ucode/dawnline/resolver.uc | 9 +- .../usr/share/ucode/dawnline/rpc/people.uc | 9 +- .../usr/share/ucode/dawnline/rpc/settings.uc | 18 ++- .../root/usr/share/ucode/dawnline/schema.uc | 3 + .../root/usr/share/ucode/dawnline/util.uc | 98 ++++++++++++- tests/ucode/core.test.uc | 12 ++ tests/ucode/devices.test.uc | 21 ++- tests/ucode/live.test.uc | 12 ++ tests/ucode/nft.test.uc | 6 + tests/ucode/schema.test.uc | 2 + tests/ucode/util.test.uc | 15 ++ web/package-lock.json | 4 +- web/package.json | 2 +- web/src/admin/cores/awg.ts | 100 +++++++++++--- web/src/admin/cores/common.ts | 9 +- web/src/admin/device.ts | 6 +- web/src/admin/events/model.ts | 27 +++- web/src/admin/events/render.ts | 8 ++ web/src/admin/pages/person/devices.ts | 2 +- web/src/admin/pages/settings/logs.ts | 22 ++- web/src/portal/demo/data.ts | 4 +- web/src/portal/demo/router.ts | 15 +- web/src/portal/flows/add.ts | 115 ++-------------- web/src/portal/flows/device-actions.ts | 106 ++++++++++---- web/src/portal/flows/device-form.ts | 129 ++++++++++++++++++ web/src/portal/flows/setup-parts.ts | 129 ++++++++++++++---- web/src/portal/flows/setup-view.ts | 35 +++-- web/src/portal/i18n/portal.pot | 115 ++++++++++++++-- web/src/portal/i18n/ru.po | 115 ++++++++++++++-- web/src/portal/page/access.ts | 26 ++-- web/src/portal/page/devices.ts | 6 +- web/src/portal/setup.ts | 114 ++++++++++++++-- web/src/portal/styles/controls.css | 52 ++++++- web/src/portal/styles/setup.css | 6 + web/src/portal/ui/seg.ts | 103 +++++++++++++- web/src/shared/awglink.ts | 60 ++++++++ web/src/shared/flags.ts | 13 ++ web/src/shared/icons.ts | 6 + web/src/shared/types.ts | 2 + web/tests/events.test.ts | 8 ++ web/tests/setup.test.ts | 115 +++++++++++++++- web/vercel.json | 2 +- 65 files changed, 2066 insertions(+), 338 deletions(-) create mode 100644 web/src/portal/flows/device-form.ts create mode 100644 web/src/shared/awglink.ts create mode 100644 web/src/shared/flags.ts diff --git a/DESIGN.md b/DESIGN.md index 5150487..f37726d 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -544,7 +544,7 @@ Glass icons (`ui/glass.ts`) draw a tinted back shape, the same shape blurred beh | `t-grey` | `#cfcfcd` → `#5a5a59` | `#a9a9a7` → `#3d3d3c` | Device cards (default), access rows, Add | | `t-blue` | `#a6d9ff` → `#1d84e6` | `#7cc4ff` → `#0a6fd6` | This device, first device, kinds, reach tiles that are on, the LAN Bypass row when on, lock | | `t-green` | `#a8f29c` → `#30d158` | `#82e070` → `#30d158` | "Everything works" (demo) | -| `t-orange` | `#ffc08f` → `#ff8d28` | *same as dark* | Warn notices, Reconnect question | +| `t-orange` | `#ffc08f` → `#ff8d28` | *same as dark* | Warn notices | | `t-red` | `#ffadad` → `#ff383c` | `#ff9090` → `#ff383c` | Bad notices, Remove question | Frosted pane: dark `--gi-a .58 / --gi-b .14` white with a `.5` rim and no edge stroke. Light uses a `.72 / .5` grey pane, a `.9` rim and an `rgba(0,0,0,.11)` edge, with dark detail strokes. @@ -779,7 +779,8 @@ The ⋯ menu, the pick pills' popups and the page code card are one kind of thin | Variant | Fill / text | Weight | Use | |---|---|---|---| -| `accent` | accent / white | 600 | The one primary action: Add this device, Reconnect, Open securely, Download (router) | +| `accent` | accent / white | 600 | The one primary action: Add this device, Open securely, Download (router) | +| `warn` | warn / `#241300` | 600 | Reconnect (its sheet): the colour Reconnect has in the ⋯ menu; dark ink, white on it reads at 2.3:1 | | `tint` | accent 13% / accent | 600 | A card's **Connect** (quiet primary) | | `soft` | knob / text | 500 | Cancel, "Add it from the device", Show key, Copy, Start over | | `red` | bad / white | 600 | Remove | @@ -869,7 +870,7 @@ A longer reason sits in `title` and, for a screen reader, in hidden text right a | Row | Head | Body | |---|---|---| | **What it reaches** (shield, home or globe glass) | Title only | Two **reach tiles** (radius 16, `field`, padding `12 12 12 14`, glass 28, title 14/20 500, sub 12/16; a 20 px round mark at the top right: ok-soft check or knob minus, the tile dimmed when off). Then a sentence with the hostname pattern in mono, and **name chips** (32 high, radius 10, mono 13, the domain part in `text-3`, a copy icon 14). | -| **Data this month** (chart glass) | A 16 px **ring** (track `--bar`, arc accent, warn ≥ 90%, bad ≥ 100%) and "38.6 GB / 100 GB"; hidden while open | The **month**: one bar per day (flex, gap 3, 64 high, radius 2.5, min 3; days to come at 45% bar; today accent), an axis 11 px `text-3` with "Today" in accent under its bar (the month's ends hide when it comes close), the total line (`bad` when out), a 6 px **meter** (same tone thresholds), and a `.desc`. A picked day (*Reading the bars*) puts its down and up in place of the total and "21 Oct · +62%" (its date and how it compares with the month's other days; today "so far") in place of what is left, instantly. With a limit not reached, a line under the meter (12/16 `text-2`, warn when it fills within a week): the pace lately (the devices' last 7 days) and when the limit fills at it, or what a monthly one reaches by the reset (`shared/pace.ts`). | +| **Data this month** (chart glass) | A 16 px **ring** (track `--bar`, arc accent, warn ≥ 90%, bad ≥ 100%) and "38.6 GB / 100 GB"; hidden while open | The **month**: one bar per day (flex, gap 3, 64 high, radius 2.5, min 3; days to come at 45% bar; today accent), an axis 11 px `text-3` with "Today" in accent under its bar, kept inside the axis (each of the month's ends hides where "Today" comes within 6 px of it, measured: the words' widths follow the language), the total line (`bad` when out), a 6 px **meter** (same tone thresholds), and a `.desc`. A picked day (*Reading the bars*) puts its down and up in place of the total and "21 Oct · +62%" (its date and how it compares with the month's other days; today "so far") in place of what is left, instantly. With a limit not reached, a line under the meter (12/16 `text-2`, warn when it fills within a week): the pace lately (the devices' last 7 days) and when the limit fills at it, or what a monthly one reaches by the reset (`shared/pace.ts`). | | **Access until** (calendar glass) | "30 Nov" plus "42 days" in ok, warn when soon, or "ended" in bad | The **until block** (`field`, radius 16, padding `14 16`): the days left as a 36/40 600 number (warn when soon), "days left", the end date in `text-3`, and a **calendar** of the weeks to the end. 7 columns of 10 px cells with gap 5 and radius 3: past at text 5%, left at text 16%, today in accent, the last day ringed 1.5 px accent; warn colours when soon. Under it the **hours bar**: 8 px track, the allowed window in ok 70%, a 2 × 16 "now" marker (`text`, warn when outside, with a 2 px field ring), and axis 00/06/12/18/24 at 10 px, then how long the window still runs ("3h 20m left") or, outside it in warn, when it opens (12/16 `text-2`). With nothing to open, the row is still. | A repaint keeps the rows on the page and changes what they hold in place, the same row open (see *Motion → Repaint choreography*). @@ -906,13 +907,15 @@ A repaint keeps the rows on the page and changes what they hold in place, the sa - **Tooltip:** one 26 px pill in toast colours under the keys. It appears after 420 ms of hover, then follows the pointer (or Tab) from key to key at once, gliding from where it stands, and says "Copied" after a copy. Back on a key while it still fades out, it turns back from there. -**Question view** (`.ask`: Reconnect, Remove): +**Question view** (`.ask`: Remove): - left-aligned, as iOS asks now, with 24 px top padding; - a 64 px glass icon in the action's tone, a 20/28 500 question and a 15/21 `text-2` paragraph; -- two equal buttons: **Cancel** (soft) and the action (accent for Reconnect, red for Remove); +- two equal buttons: **Cancel** (soft) and the action (red for Remove); - no × beside them. +**Reconnect view** (`flows/device-actions.ts`): Add a device without its name. The head ("Reconnect Phone"), what happens as its subline, the kinds with what it is now ringed, the LAN Bypass row as it stands, and a `warn` block **Reconnect** (refresh icon) where the name field would be, 12 px under the row. × stays. + **Secure view:** centred lock glass, an accent "Open securely" button and a short note. ### ⋯ Menu · `ui/menu.ts` @@ -921,7 +924,7 @@ Apple's iOS 26 menu (Figma kit, "Menu – iPhone"), made compact: smaller type a **Surface:** a dropdown (see *Dropdowns*): at least 210 wide, radius 24, padding `6 0`. -**Rows**, 6 px in, in groups (copy actions, then Rename, Reconnect, Remove): 8 px above and below the words (34 high, 50 with a line under the label), radius 18 (concentric); the icon 14 px in from the rounded edge, more than the 10 px from it to the words, so it doesn't crowd the curve; 12 px at the right end: a 16 px icon, a 14 px 400 label (line 18) and an 11.5 px subtitle under it where the item has one (the address it copies, tabular figures), 1 px apart. Reconnect `warn`, Remove destructive. +**Rows**, 6 px in, in groups (copy actions; LAN Bypass; then Rename, Reconnect, Remove): 8 px above and below the words (34 high, 50 with a line under the label), radius 18 (concentric); the icon 14 px in from the rounded edge, more than the 10 px from it to the words, so it doesn't crowd the curve; 12 px at the right end: a 16 px icon, a 14 px 400 label (line 18) and an 11.5 px subtitle under it where the item has one (the address it copies, tabular figures; On or Off under LAN Bypass), 1 px apart. Reconnect `warn`, Remove destructive. **Separators** between groups: 13 px high, their 1 px line 16 px in from the edge. @@ -937,12 +940,14 @@ Apple's iOS 26 menu (Figma kit, "Menu – iPhone"), made compact: smaller type a ### App picker · `ui/seg.ts` -- **Track:** 48 high, radius 16, `field`, padding `0 4`. +- **Track:** 48 high, radius 16, `field`, padding `0 4`. The sheet opens on AmneziaWG, the first item (or the app the device was set up with). +- **WireGuard has no item of its own** except for a router (its own package): with the disguise off it takes AmneziaWG's file and code through the same menus, so AmneziaWG's item is both. The words name both ("In AmneziaWG or WireGuard:", "Open AmneziaWG or WireGuard", "import … in AmneziaWG or WireGuard"), a hint line under AmneziaWG's store says WireGuard works too (its name links to its store), and the share badge's small line says "Straight into the app" (two names do not fit it). On Linux a last step gives wireguard-tools' `wg-quick`. - **Items:** icons only (20 px) at 56 px each. The picked item takes the remaining width (`flex-grow`) and shows its name. - **Pill:** 40 px, radius 12. It stretches like skiper21's tabs: the leading edge reaches the new item first and the trailing edge follows. At rest it sits on its item by layout alone (4 px and the items before it on the left, the items after it on the right, each 56 or 44 px), so the sheet changing width carries it along with nothing watching. - **Item colours:** idle `text-3`, hover `text-2`, picked `text`. +- **A name too long for its place** (four apps on a phone): it fades to nothing at the edge it runs past (an 18 px alpha mask, the right edge at its start). Under the pointer, or with the keyboard's focus, it glides to its end a beat later (240 ms) at 40 px/s, eased at both ends, the fade sliding to the left edge (320 ms, `--fade-l`/`--fade-r` as registered properties); it glides back as the pointer leaves, from where it stands. On touch a tap on the picked item glides it there and back. Another pick puts every name back at its start. -### Kinds picker · `flows/add.ts` +### Kinds picker · `flows/device-form.ts` (Add a device, Reconnect) - **Tiles:** four in a grid (`--n` columns, gap 8): PC, Mobile, Router, Other. Each is 56 high, radius 14, `field`. - **Icons and labels:** a 26 px blue glass icon, greyscale at 55% opacity until picked. The label sits under the tile at 12/16 500. @@ -966,7 +971,7 @@ One choice with a switch (Add a device's **LAN Bypass**). A line that unfolds un - Two lines: top 12/16 `text-2`, main 15/20 500. - A 16 px trailing mark: chevron for an action, "open" for a page in a new tab. - `.primary` (the one thing to tap in a step): the icon tile is accent-soft / accent. -- `.badges2`: two side by side, no trailing mark. +- `.badges2`: two side by side, no trailing mark, while each has 150 px, room for its words on one line (a store's name never wraps); narrower, one under the other. - Inside an inset row: knob 65% over field, hover `knob`, one step above the row. ### Set-up sheet · `flows/setup-view.ts` @@ -977,7 +982,7 @@ One choice with a switch (Add a device's **LAN Bypass**). A line that unfolds un **"How to" path:** `Open AmneziaWG › + › Import Tunnel(s) from File…` in 13 px `text-2`, the app's own words in `text` 500. -**Scan line:** "In WireGuard: + › Create from QR code". Where iOS and Android name a step differently, that word alternates every 3 s, with the or Android mark beside it. +**Scan line:** "In AmneziaWG: + › Create from QR code" ("In AmneziaWG or WireGuard:" with the disguise off). Where iOS and Android name a step differently, that word alternates every 3 s, with the or Android mark beside it. **The way:** a picture of the connection, with no buttons. @@ -1477,7 +1482,7 @@ CSS hover and press transitions (`scale(.8–.98)`, colours, the switch) are not - **Short, plain and whole.** "Your devices can't connect until it's resumed." A sentence that adds to a title never repeats it. Full rules for strings and Russian: `rules/i18n.md`. - **Buttons are verbs, with no ellipsis:** Connect, Update, Add device, Reconnect, Remove, Cancel, Open securely, Show key, Copy. - **Statuses are short and fit one line.** The full wording goes in the tooltip: "Settings changed, update needed". -- **Other apps are quoted word for word, in each language:** "+ › Insert › Continue" for AmneziaVPN, "Import Tunnel(s) from File…" for WireGuard. +- **Other apps are quoted word for word, in each language:** "+ › Insert › Continue" for AmneziaVPN, "Import Tunnel(s) from File…" for WireGuard, "+ › Import config from Clipboard" for V2RayTun on Android, "+ › Import from clipboard" on Windows. - **Honest warnings sit where the choice is made**, said once: one line where space is short, the why in `title`. - **Numbers, sizes and dates** follow the page's language. - **The language pill switches in place.** diff --git a/README.md b/README.md index 5baf904..a70d46a 100644 --- a/README.md +++ b/README.md @@ -315,8 +315,10 @@ By hand: Settings › Remove Dawnline from this router
-AmneziaVPN or AmneziaWG on phones and computers, and plain WireGuard when the -disguise is off. The portal shows each person the app for their system and how +AmneziaVPN or AmneziaWG on phones and computers, V2RayTun on Android (its +`awg://` link; not with the Maximum disguise, which it cannot +run yet), +and plain WireGuard when the disguise is off. The portal shows each person the app for their system and how to add the connection in it. @@ -378,6 +380,14 @@ are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access changes reach the tunnel with `awg syncconf`, without restarting the interface; `dawnline log` on the router shows the service log. +Everything service-related also goes to the router's system log, one line per +event with its syslog priority: `logread -e dawnline` shows +`[info] [service] starting`, `[info] [apply] configuration applied in 310 ms · …`, +tunnels and the portal going down and back, crashes with what syslog knew about +them, every settings change (`admin changed settings · domain: lan → home`) and +people's and devices' changes. Settings → Logs & history → System log picks the +level: errors, warnings, normal or verbose (each step of a start and an apply). + ## 🧰 Development ``` diff --git a/README_ru.md b/README_ru.md index 5cddf5a..85b87e7 100644 --- a/README_ru.md +++ b/README_ru.md @@ -318,8 +318,10 @@ sh /tmp/dawnline-uninstall.sh --dry-run
-AmneziaVPN или AmneziaWG на телефонах и компьютерах, а обычный WireGuard, если -маскировка выключена. Портал показывает каждому приложение для его системы и +AmneziaVPN или AmneziaWG на телефонах и компьютерах, V2RayTun на Android (по +ссылке `awg://`; кроме максимальной маскировки, её он пока не +умеет), а +обычный WireGuard, если маскировка выключена. Портал показывает каждому приложение для его системы и как добавить в нём подключение. @@ -382,6 +384,15 @@ AmneziaVPN или AmneziaWG на телефонах и компьютерах, чаще раза в час. Изменения доступа доходят до туннеля через `awg syncconf`, без перезапуска интерфейса; `dawnline log` на роутере показывает журнал служб. +Всё, что касается служб, попадает и в системный журнал роутера, строкой на +событие с приоритетом syslog: `logread -e dawnline` покажет +`[info] [service] starting`, `[info] [apply] configuration applied in 310 ms · …`, +падения и восстановление туннелей и портала, сбои с тем, что о них знал syslog, +каждое изменение настроек (`admin changed settings · domain: lan → home`) и +изменения людей и устройств. Уровень выбирается в «Настройки → Журналы и +история → Системный журнал»: ошибки, предупреждения, обычный или подробный +(каждый шаг запуска и применения настроек). + ## 🧰 Разработка ``` diff --git a/package/luci-app-dawnline/Makefile b/package/luci-app-dawnline/Makefile index 0136f7f..bfcc232 100644 --- a/package/luci-app-dawnline/Makefile +++ b/package/luci-app-dawnline/Makefile @@ -6,7 +6,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=luci-app-dawnline -PKG_VERSION:=0.17.0 +PKG_VERSION:=0.18.0 PKG_RELEASE:=1 PKG_LICENSE:=MIT # po//dawnline.po becomes luci-i18n-dawnline- (luci.mk), released diff --git a/package/luci-app-dawnline/po/ru/dawnline.po b/package/luci-app-dawnline/po/ru/dawnline.po index 9e91f85..ee1167f 100644 --- a/package/luci-app-dawnline/po/ru/dawnline.po +++ b/package/luci-app-dawnline/po/ru/dawnline.po @@ -389,6 +389,10 @@ msgstr "Интерфейса %s нет." msgid "%s does not overlap other networks." msgstr "%s не пересекается с другими сетями." +#: web/src/admin/cores/awg.ts +msgid "%s does not resolve right now, and V2RayTun on Android connects by IP address only." +msgstr "Сейчас не удаётся узнать IP-адрес %s, а V2RayTun на Android подключается только по IP-адресу." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc msgid "%s does not resolve." msgstr "%s не разрешается в IP-адрес." @@ -1087,6 +1091,10 @@ msgstr "%s: %s из 4" msgid "%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or ." msgstr "%s: тег <%s> не примут приложения AmneziaWG: используйте с чётным числом шестнадцатеричных цифр, , или с N от 1 до 1000 либо ." +#: web/src/admin/events/model.ts +msgid "%s: automatic" +msgstr "%s: автоматически" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "%s: the device's own network handles it." msgstr "%s: этот трафик идёт через собственную сеть устройства." @@ -2182,6 +2190,10 @@ msgstr "Выберите свободный порт от 1 до 65535 (кром msgid "Choose a server on their page" msgstr "Выберите сервер на странице человека" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc +msgid "Choose a system log level: errors, warnings, normal or verbose." +msgstr "Выберите уровень системного журнала: ошибки, предупреждения, обычный или подробный." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "Choose another interface name in the server settings." msgstr "Выберите другое имя интерфейса в настройках сервера." @@ -2653,6 +2665,10 @@ msgstr "Устройство %s: настройки изменены" msgid "Device %s changed network %s" msgstr "Устройство %s сменило сеть %s" +#: web/src/admin/events/render.ts +msgid "Device %s changed on the portal" +msgstr "Устройство %s: настройки изменены через портал" + #: web/src/admin/events/render.ts msgid "Device %s connected" msgstr "Устройство %s подключилось" @@ -3081,6 +3097,10 @@ msgstr "Укажите оба времени, например 07:00 и 23:00." msgid "Error: %s" msgstr "Ошибка: %s" +#: web/src/admin/pages/settings/logs.ts +msgid "Errors only" +msgstr "Только ошибки" + #: web/src/admin/pages/settings/logs.ts msgid "Every 10 min" msgstr "Каждые 10 мин" @@ -3527,6 +3547,21 @@ msgstr "Импортировать" msgid "Import JSON" msgstr "Импорт JSON" +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Import config from Clipboard" +msgstr "Импорт из буфера обмена" + +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Import config from QRcode" +msgstr "Импорт из QR-кода" + +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Import from clipboard" +msgstr "Импорт из буфера обмена" + #: web/src/admin/pages/settings/backups.ts msgid "Import?" msgstr "Импортировать?" @@ -3928,6 +3963,14 @@ msgstr "Не удалось создать ключ." msgid "LAN Bypass" msgstr "Обход локальной сети" +#: web/src/admin/events/model.ts +msgid "LAN Bypass off" +msgstr "обход локальной сети выкл." + +#: web/src/admin/events/model.ts +msgid "LAN Bypass on" +msgstr "обход локальной сети вкл." + #: web/src/admin/widgets/tiles.ts msgid "Last 30 days" msgstr "За 30 дней" @@ -3975,6 +4018,7 @@ msgstr "Сертификат Let’s Encrypt для портала" msgid "Limit hours" msgstr "Ограничить часы" +#: web/src/admin/cores/awg.ts #: web/src/admin/invite.ts msgid "Link copied" msgstr "Ссылка скопирована" @@ -4651,6 +4695,10 @@ msgstr "Бессрочно" msgid "None: without the tunnel those devices have no DNS." msgstr "Нет: без туннеля у этих устройств не будет DNS." +#: web/src/admin/pages/settings/logs.ts +msgid "Normal" +msgstr "Обычный" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc msgid "Not a Dawnline export." msgstr "Файл не является экспортом Dawnline." @@ -5162,6 +5210,10 @@ msgstr "%s: добавлено устройство %s" msgid "Person %s added device %s on their portal" msgstr "%s: добавлено устройство %s через портал" +#: web/src/admin/events/render.ts +msgid "Person %s changed device %s on their portal" +msgstr "Пользователь %s изменил настройки устройства %s в личном портале" + #: web/src/admin/events/render.ts msgid "Person %s issued new keys for device %s on their portal" msgstr "%s: выпущены новые ключи для устройства %s через портал" @@ -6314,6 +6366,10 @@ msgstr "Переход на AmneziaWG %s" msgid "System" msgstr "Система" +#: web/src/admin/pages/settings/logs.ts +msgid "System log" +msgstr "Системный журнал" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/updater #: web/src/admin/pages/components/activity.ts #: web/src/admin/pages/settings/updates.ts @@ -6502,6 +6558,10 @@ msgstr "Модуль ядра не загружается: %s Переустан msgid "The latest release is %s" msgstr "Последний релиз - %s" +#: web/src/admin/cores/awg.ts +msgid "The link has the server’s IP address, not its name: if the address changes, set the device up again." +msgstr "В ссылке IP-адрес сервера, а не его имя: если адрес сменится, настройте устройство заново." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc msgid "The link is up but not attached to %s." msgstr "Домашний маршрут поднят, но не подключён к %s." @@ -6872,6 +6932,11 @@ msgstr "Пробуем зеркало %s" msgid "Tunnel" msgstr "Туннель" +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Tunnel" +msgstr "Туннель" + #: web/src/admin/pages/overview.ts msgid "Tunnel %s is down." msgstr "Туннель %s не работает." @@ -7002,6 +7067,10 @@ msgstr "Неизвестный город" msgid "Unknown component %s" msgstr "Неизвестный компонент: %s" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Unknown device type." +msgstr "Неизвестный тип устройства." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc @@ -7270,10 +7339,22 @@ msgstr "Используется самоподписанный сертифик msgid "Using a self-signed certificate: browsers will show a warning. ACME can get a free Let’s Encrypt one." msgstr "Используется самоподписанный сертификат: браузеры покажут предупреждение. Через ACME можно получить бесплатный сертификат Let’s Encrypt." +#: web/src/admin/cores/awg.ts +msgid "V2RayTun on Android: %s, or copy the link and %s." +msgstr "V2RayTun на Android: %s или скопируйте ссылку и %s." + +#: web/src/admin/cores/awg.ts +msgid "V2RayTun on Windows: %s, then set its mode to %s and connect. That mode needs administrator rights: the app offers to restart with them." +msgstr "V2RayTun на Windows: %s, затем выберите режим «%s» и подключитесь. Для этого режима нужны права администратора: приложение предложит перезапуститься с ними." + #: web/src/admin/interfaces.ts msgid "VPN & tunnels" msgstr "VPN и туннели" +#: web/src/admin/pages/settings/logs.ts +msgid "Verbose (debug)" +msgstr "Подробный (отладка)" + #: web/src/admin/pages/components/hero.ts msgid "Versions" msgstr "Версии" @@ -7315,6 +7396,10 @@ msgstr "Внимание: не удалось сохранить %s: %s" msgid "Warning: the installed build is no longer published, nothing to keep for rollback" msgstr "Внимание: установленная сборка больше не публикуется, сохранить для отката нечего" +#: web/src/admin/pages/settings/logs.ts +msgid "Warnings and errors" +msgstr "Предупреждения и ошибки" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/agent #: web/src/admin/pages/diagnostics/health.ts msgid "Watchdog" @@ -7344,6 +7429,10 @@ msgstr "Раз в неделю" msgid "Went offline" msgstr "Вышло из сети" +#: web/src/admin/pages/settings/logs.ts +msgid "What Dawnline writes to the router’s system log (logread -e dawnline). Verbose adds each step of a start and of applying settings." +msgstr "Что Dawnline пишет в системный журнал роутера (logread -e dawnline). Подробный добавляет каждый шаг запуска и применения настроек." + #: web/src/admin/pages/server.ts #: web/src/admin/pages/settings/portal.ts msgid "What people see" @@ -8150,6 +8239,10 @@ msgstr "сохранить доступ" msgid "keep-alive" msgstr "keep-alive" +#: web/src/admin/events/model.ts +msgid "keep-alive %s s" +msgstr "keep-alive %s с" + #: web/src/admin/events/model.ts msgid "kept in memory only (lost on reboot)" msgstr "только в памяти (пропадают при перезагрузке)" @@ -8582,6 +8675,14 @@ msgstr "сегодня %s" msgid "tunnel network" msgstr "сеть туннеля" +#: web/src/admin/events/model.ts +msgid "type" +msgstr "тип" + +#: web/src/admin/events/model.ts +msgid "type: %s" +msgstr "тип: %s" + #: web/src/admin/pages/people.ts #: web/src/admin/pages/settings/portal.ts msgid "until %s" diff --git a/package/luci-app-dawnline/po/templates/dawnline.pot b/package/luci-app-dawnline/po/templates/dawnline.pot index 8c95e41..1354ebd 100644 --- a/package/luci-app-dawnline/po/templates/dawnline.pot +++ b/package/luci-app-dawnline/po/templates/dawnline.pot @@ -363,6 +363,10 @@ msgstr "" msgid "%s does not overlap other networks." msgstr "" +#: web/src/admin/cores/awg.ts +msgid "%s does not resolve right now, and V2RayTun on Android connects by IP address only." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc msgid "%s does not resolve." msgstr "" @@ -1035,6 +1039,10 @@ msgstr "" msgid "%s: <%s> is not a tag AmneziaWG apps accept: use with an even number of hex digits, , or with N from 1 to 1000, or ." msgstr "" +#: web/src/admin/events/model.ts +msgid "%s: automatic" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/access.uc msgid "%s: the device's own network handles it." msgstr "" @@ -2124,6 +2132,10 @@ msgstr "" msgid "Choose a server on their page" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc +msgid "Choose a system log level: errors, warnings, normal or verbose." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "Choose another interface name in the server settings." msgstr "" @@ -2595,6 +2607,10 @@ msgstr "" msgid "Device %s changed network %s" msgstr "" +#: web/src/admin/events/render.ts +msgid "Device %s changed on the portal" +msgstr "" + #: web/src/admin/events/render.ts msgid "Device %s connected" msgstr "" @@ -3023,6 +3039,10 @@ msgstr "" msgid "Error: %s" msgstr "" +#: web/src/admin/pages/settings/logs.ts +msgid "Errors only" +msgstr "" + #: web/src/admin/pages/settings/logs.ts msgid "Every 10 min" msgstr "" @@ -3469,6 +3489,21 @@ msgstr "" msgid "Import JSON" msgstr "" +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Import config from Clipboard" +msgstr "" + +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Import config from QRcode" +msgstr "" + +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Import from clipboard" +msgstr "" + #: web/src/admin/pages/settings/backups.ts msgid "Import?" msgstr "" @@ -3870,6 +3905,14 @@ msgstr "" msgid "LAN Bypass" msgstr "" +#: web/src/admin/events/model.ts +msgid "LAN Bypass off" +msgstr "" + +#: web/src/admin/events/model.ts +msgid "LAN Bypass on" +msgstr "" + #: web/src/admin/widgets/tiles.ts msgid "Last 30 days" msgstr "" @@ -3917,6 +3960,7 @@ msgstr "" msgid "Limit hours" msgstr "" +#: web/src/admin/cores/awg.ts #: web/src/admin/invite.ts msgid "Link copied" msgstr "" @@ -4592,6 +4636,10 @@ msgstr "" msgid "None: without the tunnel those devices have no DNS." msgstr "" +#: web/src/admin/pages/settings/logs.ts +msgid "Normal" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/backup.uc msgid "Not a Dawnline export." msgstr "" @@ -5102,6 +5150,10 @@ msgstr "" msgid "Person %s added device %s on their portal" msgstr "" +#: web/src/admin/events/render.ts +msgid "Person %s changed device %s on their portal" +msgstr "" + #: web/src/admin/events/render.ts msgid "Person %s issued new keys for device %s on their portal" msgstr "" @@ -6249,6 +6301,10 @@ msgstr "" msgid "System" msgstr "" +#: web/src/admin/pages/settings/logs.ts +msgid "System log" +msgstr "" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/updater #: web/src/admin/pages/components/activity.ts #: web/src/admin/pages/settings/updates.ts @@ -6437,6 +6493,10 @@ msgstr "" msgid "The latest release is %s" msgstr "" +#: web/src/admin/cores/awg.ts +msgid "The link has the server’s IP address, not its name: if the address changes, set the device up again." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/health.uc msgid "The link is up but not attached to %s." msgstr "" @@ -6804,6 +6864,11 @@ msgstr "" msgid "Tunnel" msgstr "" +#: web/src/admin/cores/awg.ts +msgctxt "V2RayTun app" +msgid "Tunnel" +msgstr "" + #: web/src/admin/pages/overview.ts msgid "Tunnel %s is down." msgstr "" @@ -6934,6 +6999,10 @@ msgstr "" msgid "Unknown component %s" msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Unknown device type." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc @@ -7200,10 +7269,22 @@ msgstr "" msgid "Using a self-signed certificate: browsers will show a warning. ACME can get a free Let’s Encrypt one." msgstr "" +#: web/src/admin/cores/awg.ts +msgid "V2RayTun on Android: %s, or copy the link and %s." +msgstr "" + +#: web/src/admin/cores/awg.ts +msgid "V2RayTun on Windows: %s, then set its mode to %s and connect. That mode needs administrator rights: the app offers to restart with them." +msgstr "" + #: web/src/admin/interfaces.ts msgid "VPN & tunnels" msgstr "" +#: web/src/admin/pages/settings/logs.ts +msgid "Verbose (debug)" +msgstr "" + #: web/src/admin/pages/components/hero.ts msgid "Versions" msgstr "" @@ -7245,6 +7326,10 @@ msgstr "" msgid "Warning: the installed build is no longer published, nothing to keep for rollback" msgstr "" +#: web/src/admin/pages/settings/logs.ts +msgid "Warnings and errors" +msgstr "" + #: package/luci-app-dawnline/root/usr/libexec/dawnline/agent #: web/src/admin/pages/diagnostics/health.ts msgid "Watchdog" @@ -7274,6 +7359,10 @@ msgstr "" msgid "Went offline" msgstr "" +#: web/src/admin/pages/settings/logs.ts +msgid "What Dawnline writes to the router’s system log (logread -e dawnline). Verbose adds each step of a start and of applying settings." +msgstr "" + #: web/src/admin/pages/server.ts #: web/src/admin/pages/settings/portal.ts msgid "What people see" @@ -8077,6 +8166,10 @@ msgstr "" msgid "keep-alive" msgstr "" +#: web/src/admin/events/model.ts +msgid "keep-alive %s s" +msgstr "" + #: web/src/admin/events/model.ts msgid "kept in memory only (lost on reboot)" msgstr "" @@ -8508,6 +8601,14 @@ msgstr "" msgid "tunnel network" msgstr "" +#: web/src/admin/events/model.ts +msgid "type" +msgstr "" + +#: web/src/admin/events/model.ts +msgid "type: %s" +msgstr "" + #: web/src/admin/pages/people.ts #: web/src/admin/pages/settings/portal.ts msgid "until %s" diff --git a/package/luci-app-dawnline/root/etc/init.d/dawnline b/package/luci-app-dawnline/root/etc/init.d/dawnline index e77db6f..25891e0 100755 --- a/package/luci-app-dawnline/root/etc/init.d/dawnline +++ b/package/luci-app-dawnline/root/etc/init.d/dawnline @@ -8,15 +8,33 @@ USE_PROCD=1 PORTAL_ROOT=/usr/share/dawnline/portal/www +# A line in syslog as dawnline.util syslog() writes them: "dawnline: [info] [service] …" at the +# matching priority, when the admin's level (settings.log_level: error|warn|info|debug) takes it. +log() { + local lvl="$1" want rank prio + shift + want="$(uci -q get dawnline.settings.log_level)" + case "$lvl" in error) rank=0 prio=err ;; warn) rank=1 prio=warning ;; debug) rank=3 prio=debug ;; *) rank=2 prio=info ;; esac + case "$want" in error) want=0 ;; warn) want=1 ;; debug) want=3 ;; *) want=2 ;; esac + [ "$rank" -le "$want" ] || return 0 + logger -t dawnline -p "daemon.$prio" "[$lvl] [service] $*" +} + start_portal() { local enabled port certs cert key hport http config_get_bool enabled settings portal_enabled 0 - [ "$enabled" = 1 ] || return 0 + if [ "$enabled" != 1 ]; then + log info "personal portal is off" + return 0 + fi config_get port settings portal_port 8443 certs="$(/usr/bin/dawnline portal-cert 2>/dev/null)" cert="${certs% *}" key="${certs#* }" - [ -f "$cert" ] && [ -f "$key" ] || return 0 + if ! [ -f "$cert" ] || ! [ -f "$key" ]; then + log warn "personal portal not started: no certificate (${cert:-none}): choose one in Settings, or save the portal settings again" + return 0 + fi # IP addresses in links get plain HTTP on the next port (names stay HTTPS-only). hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)" [ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport" @@ -34,23 +52,30 @@ start_portal() { procd_set_param file "$cert" procd_set_param respawn 3600 5 0 procd_close_instance + log info "personal portal on port $port (HTTPS${hport:+, plain HTTP on $hport for links with an IP address}) · certificate $cert$(openssl x509 -enddate -noout -in "$cert" 2>/dev/null | sed 's/^notAfter=/ until /') · $procs processes" } # Plain DNS for Home-only tunnel devices (config written by `dawnline apply`). start_resolver() { - [ -f /var/etc/dawnline-dns.conf ] || return 0 + if ! [ -f /var/etc/dawnline-dns.conf ]; then + log debug "no DNS for Home-only devices (nobody needs it)" + return 0 + fi procd_open_instance dns procd_set_param command /usr/libexec/dawnline/resolver procd_set_param file /var/etc/dawnline-dns.conf # A new config kills it (dawnline.resolver): back within a second, not five. procd_set_param respawn 3600 1 0 procd_close_instance + log info "DNS for Home-only devices started (/var/etc/dawnline-dns.conf)" } start_service() { config_load dawnline mkdir -p /var/run/dawnline - /usr/bin/dawnline apply >/dev/null 2>&1 + log info "starting" + # The apply writes its own lines: what it came to and how long it took (each step at debug). + /usr/bin/dawnline apply >/dev/null 2>&1 || log error "applying the configuration failed: run \"dawnline apply\" to see why" procd_open_instance agent procd_set_param command /usr/libexec/dawnline/agent @@ -60,10 +85,12 @@ start_service() { start_portal start_resolver + log info "started" } # Noted for the service log: the next agent start is a restart, not a crash or a boot. stop_service() { + log info "stopping" mkdir -p /var/run/dawnline date +%s > /var/run/dawnline/agent.stopped # Copies procd doesn't know about (started by hand, or left by an older version) go too. @@ -71,7 +98,8 @@ stop_service() { } reload_service() { - /usr/bin/dawnline apply >/dev/null 2>&1 + log info "reloading: settings changed" + /usr/bin/dawnline apply >/dev/null 2>&1 || log error "applying the configuration failed: run \"dawnline apply\" to see why" start } diff --git a/package/luci-app-dawnline/root/usr/bin/dawnline b/package/luci-app-dawnline/root/usr/bin/dawnline index 026db4d..b4e8198 100755 --- a/package/luci-app-dawnline/root/usr/bin/dawnline +++ b/package/luci-app-dawnline/root/usr/bin/dawnline @@ -15,7 +15,7 @@ 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 + VERSION, slog, syslog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR } from 'dawnline.util'; /** Options that take no value. */ @@ -338,5 +338,7 @@ try { } catch (e) { warn(`dawnline: ${e.message}\n`); + // Run from the init script or cron, stderr goes nowhere: syslog keeps why. + syslog('error', 'cli', `dawnline ${cmd} failed: ${e.message}`); exit(1); } diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent index 710ba75..71e06a3 100755 --- a/package/luci-app-dawnline/root/usr/libexec/dawnline/agent +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/agent @@ -17,7 +17,7 @@ import * as uloop from 'uloop'; import { open, readfile, writefile, stat, unlink } from 'fs'; import { - read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION + read_json, write_json, ensure_dir, sh_out, q, uniq, slog, syslog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as live from 'dawnline.live'; @@ -641,8 +641,9 @@ function nightly_backup() { let st = read_json(`${DATA_DIR}/backup-state.json`, {}); if (sum && sum != st.auto) { try { - backup.backup_create('auto'); + let b = backup.backup_create('auto'); write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600); + syslog('info', 'backup', `nightly backup saved${b ? ': ' + b : ''}`); } catch (e) { // Tried again tomorrow; meanwhile the admin should know (a full flash, mostly). @@ -794,9 +795,11 @@ function step(i, s, fn) { delete step_err[i]; } catch (e) { - system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`); + // A new error goes to the service log (and from there to syslog); a repeat, or a quiet step's, to syslog alone. if (!s.quiet && step_err[i] != e.message) slog('dawnline', 'error', sprintf(L_('failed: %s'), e.message), e.stacktrace?.[0]?.context, s.who); + else + syslog('error', 'agent', `${s.who}: ${e.message}`); step_err[i] = e.message; } } @@ -835,7 +838,14 @@ function tick() { }); } +// Once: a signal ends the loop and calls it, and so does the line after uloop.run(). +let stopping = false; + function shutdown() { + if (stopping) + return; + stopping = true; + syslog('info', 'agent', 'stopping · saving the counters and the logs'); live.save_usage(usage, true); live.persist_events(); geo.flush(); @@ -876,6 +886,7 @@ else if (live.uptime() < 600) slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline'); else slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline'); +syslog('debug', 'agent', sprintf('watching connections every %d ms, checking the rest every %d ms', WATCH, TICK)); // A module Dawnline did not install has no record of its kernel: without one // Health cannot tell a firmware upgrade from a missing module. builds.adopt(); diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat b/package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat index a72c3d1..22b61d2 100755 --- a/package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat @@ -29,4 +29,4 @@ else detail="It never completed a check."; fi msg="stopped responding — restarted" mkdir -p /var/run/dawnline printf '{"ts":%s,"src":"dawnline","level":"repair","who":"Dawnline","msg":"%s","detail":"%s"}\n' "$now" "$msg" "$detail" >> /var/run/dawnline/service.log -logger -t dawnline "Dawnline $msg" +logger -t dawnline -p daemon.warning "[warn] [agent] Dawnline $msg - $detail" diff --git a/package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate b/package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate index 8c06693..f7619d1 100755 --- a/package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate +++ b/package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate @@ -31,13 +31,13 @@ while [ "$i" -lt 12 ]; do up && exit 0 done -logger -t dawnline "update to $to failed its check: luci.dawnline or the agent is not up" +logger -t dawnline -p daemon.err "[error] [update] update to $to failed its check: luci.dawnline or the agent is not up" set -- for f in "$KEEP"/*.ipk "$KEEP"/*.apk; do [ -f "$f" ] && set -- "$@" "$f" done if [ "$#" -eq 0 ]; then - logger -t dawnline "no previous version is kept: nothing to roll back to" + logger -t dawnline -p daemon.err "[error] [update] no previous version is kept: nothing to roll back to" exit 1 fi if command -v apk >/dev/null 2>&1; then @@ -50,5 +50,5 @@ fi mkdir -p "$RUN" # The restored agent reports it in the service log on its start. echo "$to" > "$RUN/update-rolled-back" -logger -t dawnline "rolled back from $to to the kept version" +logger -t dawnline -p daemon.warning "[warn] [update] rolled back from $to to the kept version" exit 0 diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc index 413a4fd..48286d3 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/apply.uc @@ -13,7 +13,7 @@ // (dawnline.store) is never taken while 'apply' is held. import { readfile, writefile, stat, unlink } from 'fs'; -import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util'; +import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, syslog, log_on, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; import * as loop from 'dawnline.loop'; @@ -54,8 +54,10 @@ export function sync_hosts(m) { let body = length(lines) ? join('\n', lines) + '\n' : ''; // dnsmasq runs as its own user; rpcd's umask would leave the file 0600. let readable = ((stat(HOSTS_FILE)?.perm?.other_read) ?? false); - if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable)) + if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable)) { + syslog('debug', 'dns', `${HOSTS_FILE}: unchanged · ${length(lines)} names`); return false; + } ensure_dir('/tmp/hosts'); if (body == '') unlink(HOSTS_FILE); @@ -63,6 +65,7 @@ export function sync_hosts(m) { writefile(HOSTS_FILE, body); system(`chmod 644 ${HOSTS_FILE}`); } + syslog('info', 'dns', body == '' ? `${HOSTS_FILE}: removed (no device names)` : `${HOSTS_FILE}: ${length(lines)} names written (*.${m.settings.domain}) · killall -HUP dnsmasq`); system('killall -HUP dnsmasq 2>/dev/null'); return true; }; @@ -154,6 +157,21 @@ function sync_warning(m, table, peers) { return length(out) ? join(' ', [ ...out, _('Open Diagnostics → Health.') ]) : null; } +/** + * The same as sync_warning for syslog: in English whatever the admin's + * language (a log is read by anyone, searched and sent on), with what nft or + * awg said. Null when all went in. + */ +function sync_facts(m, table, peers) { + let out = []; + if (table != null) + push(out, `access rules ${nft.present() ? 'not updated, the previous ones stay' : 'not loaded, no device loaded'}: ${table}`); + for (let id, r in peers) + if (r != 'ok' && r != 'down') + push(out, `${m.servers[id]?.name ?? id}: devices not loaded: ${r}`); + return length(out) ? join(' · ', out) : null; +} + /* * With the lock held: access sets first, then devices into the tunnels. * Fail closed: without the table the firewall would let every loaded device @@ -226,24 +244,60 @@ export function sync_loop(m, usage, force) { /* ---------- entry points ---------- */ -/** Full reconcile: router configuration + runtime state. */ +/** Milliseconds on the monotonic clock, for how long an apply's steps take. */ +function ms() { + let c = clock(true); + return c[0] * 1000 + c[1] / 1000000; +} + +/** + * Full reconcile: router configuration + runtime state. In syslog: what it + * came to, with how long it took (info; warn when it did not fully take), and + * each step with its result at the debug level. + */ export function apply(opts) { opts ??= {}; + let t0 = ms(); + let debug = log_on('debug'); + // One step, timed; `show` picks what of its result goes in the line (never the model: it holds keys). + let step = (name, fn, show) => { + let t = ms(); + let out = fn(); + let what = show ? show(out) : out; + if (debug) + syslog('debug', 'apply', sprintf('%s done in %d ms%s', name, ms() - t, + what == null ? '' : ` · ${type(what) == 'string' ? what : sprintf('%J', what)}`)); + return out; + }; + if (debug) + syslog('debug', 'apply', 'applying the configuration'); migrate.run(); let r = with_lock('apply', () => { let m = core.load(); let usage = core.load_usage(); - let network = netifd.sync(m); - let firewall = fw.sync(m); - let lp = loop.ensure(m, true); - loop.sync_resolver(m); - fw.sync_reply_routes(m); - let s = locked_sync(m, usage, true); + let changed = (x) => x ? 'changed' : 'unchanged'; + let network = step('network (netifd)', () => netifd.sync(m), changed); + let firewall = step('firewall (fw4)', () => fw.sync(m), changed); + let lp = step('internet like a home device', () => loop.ensure(m, true)); + step('resolver for Home-only devices', () => { loop.sync_resolver(m); }); + step('reply routes', () => { fw.sync_reply_routes(m); }); + let s = step('access rules and devices', () => locked_sync(m, usage, true), (x) => ({ table: x.table, peers: x.peers })); ensure_dir(RUN_DIR); write_file(NET_SIG, net_signature(m), 0o644); - return { network, firewall, lp, peers: s.peers, warning: s.warning }; + return { network, firewall, lp, peers: s.peers, warning: s.warning, facts: sync_facts(m, s.table, s.peers), + counts: [ length(keys(m.servers)), length(keys(m.people)), length(keys(m.devices)) ] }; }); loop.remember(r.lp); + let n = (k, one, many) => `${k} ${k == 1 ? one : many}`; + let took = sprintf('configuration applied in %d ms · %s, %s, %s', ms() - t0, + n(r.counts[0], 'server', 'servers'), n(r.counts[1], 'person', 'people'), n(r.counts[2], 'device', 'devices')); + // Syslog in English (sync_facts, loop.error_note); the admin's answer carries the words in their language. + if (r.facts) + syslog('warn', 'apply', `${took} · ${r.facts}`); + else + syslog('info', 'apply', took); + if (r.lp.error) + syslog('warn', 'apply', `internet like a home device: ${type(r.lp.error) == 'object' ? loop.error_note(r.lp.error) : r.lp.error}`); 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 }; }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc index 4d1680e..5ab73e4 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc @@ -8,7 +8,7 @@ import { readfile, stat, unlink } from 'fs'; import { q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, tunnel_name, ensure_dir, write_file, read_json, write_json, lock, unlock, - slog, iface_status, DATA_DIR, RUN_DIR + slog, syslog, some_of, iface_status, DATA_DIR, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; @@ -763,32 +763,58 @@ export function peer_diff(devs, dmp, ifname) { }; /** Push the peer list of every server to the kernel without restarting it. */ +// Each tunnel's peers as last loaded ({ ifname: [ "Person · Device (address)" ] }), so a log line can say who came and went. +const PEERS_SEEN = `${RUN_DIR}/peers-seen.json`; + export function sync_peers(m, states) { ensure_dir(RUN_DIR); let res = {}; + let seen = read_json(PEERS_SEEN, {}), now = {}; for (let id, srv in m.servers) { // Only Dawnline's own interfaces: never another tunnel of the same name (core.tunnels). if (!srv.enabled || !length(core.tunnels(srv))) continue; if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) { res[id] = 'down'; + syslog('debug', 'awg', `interface ${srv.ifname} (${srv.name}): down, no devices to load`); continue; } let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ]; + let who = []; for (let d in tunnel_devices(m, id, states)) { push(lines, '[Peer]', `PublicKey = ${d.public_key}`); if (d.preshared_key) push(lines, `PresharedKey = ${d.preshared_key}`); push(lines, `AllowedIPs = ${d.address}/32`, ''); + push(who, `${m.people[d.person]?.name ?? d.person} · ${d.name} (${d.address})`); } let f = `${RUN_DIR}/${srv.ifname}.conf`; write_file(f, join('\n', lines)); let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`); unlink(f); res[id] = r.code == 0 ? 'ok' : trim(r.out); - if (r.code != 0) + if (r.code != 0) { slog('awg', 'error', L_("couldn't load devices into the tunnel"), trim(r.out), srv.name); + continue; + } + // Who came in and who left since the last load: info; the same peers: debug. + now[srv.ifname] = who; + let was = seen[srv.ifname]; + let head = `interface ${srv.ifname} (${srv.name}): awg syncconf · listen port ${srv.port} · ${length(who)} ${length(who) == 1 ? 'peer' : 'peers'}`; + // The first load since the router started (or since the tunnel came up): how many, the names at debug. + if (was == null) { + syslog('info', 'awg', `${head} loaded`); + syslog('debug', 'awg', `interface ${srv.ifname}: ${join(', ', who)}`); + continue; + } + let add = filter(who, (x) => index(was, x) < 0), del = filter(was, (x) => index(who, x) < 0); + if (length(add) || length(del)) + syslog('info', 'awg', `${head}${length(add) ? ' · added ' + some_of(add) : ''}${length(del) ? ' · removed ' + some_of(del) : ''}`); + else + syslog('debug', 'awg', `${head}, unchanged`); } + if (sprintf('%J', now) != sprintf('%J', seen)) + write_json(PEERS_SEEN, now, 0o600); return res; }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc index c4ea77f..44656a9 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc @@ -90,6 +90,8 @@ export function load(c) { hostnames: g('hostnames'), domain: g('domain'), log_connections: g('log_connections'), + // What goes to syslog (dawnline.util syslog). + log_level: g('log_level'), // Repair tunnels and services on its own (the agent, every minute). watchdog: g('watchdog'), // Second DNS for "home names" devices, used by the device when the tunnel is down. @@ -789,6 +791,24 @@ export function set_device_link(c, m, id, a) { return changed; }; +/** + * Change what a device is (one of KINDS): true when it changed, false when it + * already was. Its configuration follows (device_mtu: phones and tablets take + * smaller packets); nothing on the router changes. + */ +export function set_device_kind(c, m, id, kind) { + let d = m.devices[id]; + if (!d) + fail(_('Unknown device.')); + if (index(KINDS, kind) < 0) + fail(_('Unknown device type.')); + if (kind == d.kind) + return false; + c.set(CONFIG, id, 'kind', kind); + d.kind = kind; + return true; +}; + export function delete_device(c, m, id) { let d = m.devices[id]; if (!d) diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc index 56499ea..71b1b09 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc @@ -29,6 +29,22 @@ export function need_awg() { } }; +/** + * What a device_changed event says changed: each option with its new value + * ("lan_bypass=on", "mtu=1400", "keepalive=auto": '' is the server's again, + * "kind=phone"), so the activity log can say what it became. + */ +function change_detail(names, ch) { + return join(', ', map(names, (k) => { + if (k == 'lan_bypass') + return `lan_bypass=${ch.lan_bypass === true ? 'on' : 'off'}`; + if (k == 'kind') + return `kind=${ch.kind}`; + let v = trim(`${ch[k] ?? ''}`); + return `${k}=${v == '' ? 'auto' : v}`; + })); +} + /** The device `id` as `opts` may touch it (inside a transaction's model). */ function own(m, id, opts) { let d = m.devices[id]; @@ -58,9 +74,11 @@ export function add(person, name, kind, opts) { /** * Rename and/or turn a device off or on, or change how it connects (`ch` = * { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see - * core.set_device_link); only the admin turns devices off or changes the - * rest. Returns the runtime sync ({} after a change of the link values alone: - * they are in the device's configuration, nothing on the router changes). + * core.set_device_link); only the admin turns devices off or sets the MTU and + * keep-alive, the portal may switch LAN Bypass (the device then takes its + * updated configuration, keys unchanged). Returns the runtime sync ({} after a + * change of the link values alone: they are in the device's configuration, + * nothing on the router changes). */ export function update(id, ch, opts) { opts ??= {}; @@ -68,7 +86,7 @@ export function update(id, ch, opts) { if (ch.disabled != null && by != 'admin') die(_('Only the admin can turn devices off.')); let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null; - if (link && by != 'admin') + if ((ch.mtu != null || ch.keepalive != null) && by != 'admin') die(_('Only the admin can change how a device connects.')); let linked = []; let d0 = store.transact((c, m) => { @@ -91,9 +109,9 @@ export function update(id, ch, opts) { live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by }); else if (ch.name != null && ch.name != d0.name) live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by }); - // The option names, as person_changed lists a person's. + // The options with what they became (change_detail). if (length(linked)) - live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: join(', ', linked), by }); + live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: change_detail(linked, ch), by }); return r; }; @@ -106,10 +124,19 @@ export function update(id, ch, opts) { function rotate(id, opts) { opts ??= {}; let by = opts.by ?? 'admin'; - store.transact((c, m) => { - own(m, id, opts); + let changed = []; + let person = store.transact((c, m) => { + let d = own(m, id, opts); + if (opts.kind != null && core.set_device_kind(c, m, id, opts.kind)) + push(changed, 'kind'); + if (opts.lan_bypass != null) + push(changed, ...core.set_device_link(c, m, id, { lan_bypass: opts.lan_bypass === true })); core.rotate_device(c, m, id, awg.new_keys()); + return d.person; }); + if (length(changed)) + live.add_event({ type: 'device_changed', person, device: id, by, + detail: change_detail(changed, { kind: opts.kind, lan_bypass: opts.lan_bypass === true }) }); // The device a portal page came through would lose its tunnel before the // answer gets out: load the new key a moment after answering. let s = null; @@ -132,8 +159,10 @@ function rotate(id, opts) { * the admin changed; the portal's Reconnect and the admin's New keys): new * keys, so the configuration it holds stops working with the sync, and it * counts as not set up until it connects with the new one. The usage keeps - * the old keys' last handshake: awg.handshake_since hides it. Returns the new - * configuration (with `warning` when the sync did not fully take). + * the old keys' last handshake: awg.handshake_since hides it. `opts.kind` and + * `opts.lan_bypass` (the portal's Reconnect: what it is, LAN Bypass) change + * with the keys, in the same write. Returns the new configuration (with + * `warning` when the sync did not fully take). */ export function reconnect(id, opts) { opts ??= {}; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc index 5fc9dbe..1578e73 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/fw.uc @@ -5,7 +5,7 @@ // named dawnline_* are ever changed. import { readfile, unlink } from 'fs'; -import { q, sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util'; +import { sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, syslog, opts_text, RUN_DIR } from 'dawnline.util'; import { cursor } from 'uci'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; @@ -33,12 +33,21 @@ export function sync(m, dry) { let c = cursor(); c.load('firewall'); let changed = false, want = {}; + // What changed, section by section, for syslog once it is saved (a dry run says nothing). + let notes = []; let sec = (name, stype, opts) => { want[name] = true; - changed = uci_section(c, 'firewall', name, stype) || changed; + let created = uci_section(c, 'firewall', name, stype), diff = {}; for (let k, v in opts) - changed = uci_put(c, 'firewall', name, k, v) || changed; + if (uci_put(c, 'firewall', name, k, v)) + diff[k] = v; + if (created || length(keys(diff))) { + changed = true; + push(notes, [ 'info', `${stype} ${name}: ${created ? 'created' : 'updated'} · ${opts_text(created ? opts : diff)}` ]); + } + else + push(notes, [ 'debug', `${stype} ${name}: unchanged` ]); }; let snap = net.snapshot(true); @@ -130,17 +139,20 @@ export function sync(m, dry) { push(stale, s['.name']); }); for (let s in stale) { + push(notes, [ 'info', `${c.get('firewall', s) ?? 'section'} ${s}: removed` ]); c.delete('firewall', s); changed = true; } if (dry) return changed; + for (let n in notes) + syslog(n[0], 'firewall', n[1]); if (changed) { c.commit('firewall'); ack_config([ 'firewall' ]); + syslog('info', 'firewall', 'fw4 -q reload'); system('fw4 -q reload'); - system("logger -t dawnline 'firewall updated'"); } return changed; }; @@ -268,18 +280,24 @@ export function sync_reply_routes(m) { } let s = reply_script(m, proxy_diverts()); if (s == '') { - if (reply_loaded()) + if (reply_loaded()) { + syslog('info', 'nftables', `table inet ${REPLY_TABLE}: removed (no proxy to keep Dawnline's answers out of)`); system(`nft delete table inet ${REPLY_TABLE} 2>/dev/null`); + } unlink(REPLY_SIG); return; } - if (s == readfile(REPLY_SIG) && reply_loaded()) + if (s == readfile(REPLY_SIG) && reply_loaded()) { + syslog('debug', 'nftables', `table inet ${REPLY_TABLE}: unchanged`); return; + } let err = nft.load(`table inet ${REPLY_TABLE}\ndelete table inet ${REPLY_TABLE}\n${s}`); if (err) { unlink(REPLY_SIG); - system(`logger -t dawnline -p user.err ${q('reply table: ' + err)}`); + syslog('error', 'nftables', `table inet ${REPLY_TABLE}: loading failed · ${err}`); return; } + syslog('info', 'nftables', `table inet ${REPLY_TABLE}: loaded · ${length(match(s, /\n/g) ?? []) + 1} lines (Dawnline's own answers kept out of proxies)`); + syslog('debug', 'nftables', `table inet ${REPLY_TABLE}: ${s}`); write_file(REPLY_SIG, s, 0o644); }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc index 5726ec9..f8983b7 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/live.uc @@ -7,7 +7,7 @@ import { readfile, stat, unlink } from 'fs'; import { cursor } from 'uci'; import { - ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq, + ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq, syslog, iface_status as util_iface_status, RUN_DIR, DATA_DIR } from 'dawnline.util'; import * as awg from 'dawnline.awg'; @@ -422,13 +422,51 @@ function with_names(e, c) { return e; } +// Events about someone's connection, not about the system: they stay out of syslog +// (the activity log has them). Connects, roams, a device's link trouble and its end. +const NOT_SYSTEM = [ 'connect', 'disconnect', 'roam', 'device_failing', 'device_recovered' ]; + +/** + * An activity event at its syslog level, or null when it stays out (a + * connection: syslog says what the system does). People and their devices + * (what changes the tunnels and the rules) are info, problems warn and their + * end ("…_up") info. + */ +export function event_level(e) { + let cat = category_of(e.type); + if (cat == 'connections' || index(NOT_SYSTEM, e.type) >= 0) + return null; + if (cat == 'problems' && !match(e.type, /_up$/)) + return 'warn'; + return 'info'; +}; + +/** An activity event as a syslog line: "Myata · Phone device changed · kind=phone, lan_bypass=on (portal)". */ +export function event_line(e) { + let who = join(' · ', filter([ e.pname ?? e.person, e.dname ?? e.device ], (x) => x != null && x != '')); + return join(' ', filter([ who, replace(e.type ?? 'event', /_/g, ' '), e.detail ? `· ${e.detail}` : '', e.by ? `(${e.by})` : '' ], (x) => x != '')); +}; + +/** The system's events to syslog, whatever the activity log records (its categories are the admin's choice for the page). */ +function syslog_events(list, c) { + for (let e in list) { + let lvl = event_level(e); + if (lvl) + syslog(lvl, category_of(e.type), event_line(with_names(e, c))); + } +} + export function add_events(list, pol) { pol ??= policy(); - list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0); + list ??= []; if (!length(list)) return; let c = cursor(); c.load('dawnline'); + syslog_events(list, c); + list = filter(list, (e) => index(pol.categories, category_of(e.type)) >= 0); + if (!length(list)) + return; let l = lock('events'); let ev = load_events(); let ts = time(); @@ -451,6 +489,9 @@ export function add_event(e) { * and device (when it has one) within `window` s. */ export function add_event_merged(e, window) { + let c0 = cursor(); + c0.load('dawnline'); + syslog_events([ { ...e } ], c0); let pol = policy(); if (index(pol.categories, category_of(e.type)) < 0) return; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc index fda9b9f..453505b 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/lookup.uc @@ -84,6 +84,18 @@ export function resolve(host) { return resolve_all([ host ])[host] ?? []; }; +/** + * The address to give an app that takes no name for the server (V2RayTun's + * Android core hands the endpoint over as it is): IPv4 first, as a phone on + * mobile data may have no IPv6. The host itself when it is an IP; null when + * the name does not resolve. + */ +export function host_ip(host) { + let ips = resolve(host); + let v4 = filter(ips, (x) => ip2int(x) != null); + return v4[0] ?? ips[0] ?? null; +}; + /** The IPv4 address of a netifd interface (a zone name for older configs). */ export function wan_ipv4(zone) { let st = live.iface_status(zone == 'wan' ? 'wan' : zone); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc index b288d90..a51d5cc 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/loop.uc @@ -39,7 +39,7 @@ import { readfile, writefile, readlink, stat, unlink } from 'fs'; import { cursor } from 'uci'; import { - sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR + sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, syslog, syslog_lines, RUN_DIR } from 'dawnline.util'; import * as net from 'dawnline.net'; import * as core from 'dawnline.core'; @@ -60,12 +60,20 @@ function log(msg, level, detail) { slog('dawnline', level ?? 'info', msg, detail, WHO); } +/** + * Run the commands that set the path up or take it down, each in syslog as + * it is given ("$ ip netns add dawnline"), a failure with what it said. + * Only called when something changes (ensure() returns early otherwise). + */ function run(cmds) { let errs = []; + syslog_lines('info', 'loop', join('\n', cmds), '$ '); for (let c in cmds) { let r = sh(c); - if (r.code != 0) + if (r.code != 0) { push(errs, `${c}: ${trim(r.out)}`); + syslog('error', 'loop', `failed: ${c} · ${trim(r.out)}`); + } } return errs; } @@ -232,8 +240,8 @@ function pick_table(saved) { * { 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) { +/** A reason from plan() for the service log and syslog: English, like every log line. */ +export function error_note(e) { if (e.code == 'no_lan') return L_('No LAN detected.'); if (e.code == 'not_bridge') @@ -245,7 +253,7 @@ function error_note(e) { 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 diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc index 77b73f9..c23529d 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc @@ -5,7 +5,7 @@ import { cursor } from 'uci'; import { stat, unlink } from 'fs'; -import { q, slog } from 'dawnline.util'; +import { slog, syslog } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as store from 'dawnline.store'; import { L_ } from 'dawnline.i18n'; @@ -47,7 +47,7 @@ export function uhttpd() { c.delete('uhttpd', 'main', 'error_page'); c.commit('uhttpd'); system('/etc/init.d/uhttpd reload >/dev/null 2>&1'); - system(`logger -t dawnline ${q('portal removed from the LuCI web server')}`); + syslog('info', 'portal', 'portal removed from the LuCI web server'); } if (stat(LAN_CGI)) unlink(LAN_CGI); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc index caeb9da..0247ab3 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/netifd.uc @@ -8,7 +8,7 @@ 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 { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, syslog, opts_text, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as awg from 'dawnline.awg'; import { L_ } from 'dawnline.i18n'; @@ -95,10 +95,17 @@ export function sync(m) { if (!tools) continue; // Per server: with several, each changed one has to be brought up again. - let mine = uci_section(c, 'network', ifn, 'interface'); + let created = uci_section(c, 'network', ifn, 'interface'); + let mine = created, diff = {}; for (let k, v in options(srv)) - if (uci_put(c, 'network', ifn, k, v)) + if (uci_put(c, 'network', ifn, k, v)) { mine = true; + diff[k] = v; + } + if (mine) + syslog('info', 'network', `interface ${ifn} (${srv.name}): ${created ? 'created' : 'updated'} · ${opts_text(diff)}`); + else + syslog('debug', 'network', `interface ${ifn} (${srv.name}): unchanged · ${opts_text(options(srv))}`); // The markers are saved, but netifd does not read them: a renamed server // keeps its tunnel and every session in it. if (uci_put(c, 'network', ifn, '_dawnline', id)) @@ -127,6 +134,7 @@ export function sync(m) { }); for (let ifn in stale) { iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn); + syslog('info', 'network', `interface ${ifn} (${c.get('network', ifn, '_dawnline_name') ?? 'a removed server'}): removed, ifdown ${ifn}`); system(`ifdown ${q(ifn)} 2>/dev/null`); c.delete('network', ifn); changed = true; @@ -138,12 +146,14 @@ export function sync(m) { } // Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload). if (length(touched) || length(stale)) { + syslog('info', 'network', 'ubus call network reload'); system('ubus call network reload'); for (let ifn in touched) - if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled) + if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled) { + syslog('info', 'network', `ifup ${ifn}`); system(`ifup ${q(ifn)}`); + } // Each tunnel's own line (restarting, turned off, removed) comes from hotplug. - system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`); } return changed; }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc index 55c1cbd..aa9e14b 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/nft.uc @@ -5,7 +5,7 @@ // changes often (update, one atomic transaction). import { unlink } from 'fs'; -import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util'; +import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, read_json, write_json, syslog, syslog_lines, some_of, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as net from 'dawnline.net'; import * as loop from 'dawnline.loop'; @@ -14,6 +14,55 @@ import * as loop from 'dawnline.loop'; export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ]; /** The sets whose members change at run time (update replaces them together). */ const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ]; +// The sets' members as last loaded, so a log line can say what changed. +const SETS_SEEN = `${RUN_DIR}/nft-sets.json`; + +/** What a table script holds: its chains, its sets and the rules in its chains (for a log line). */ +export function shape(t) { + let n = { chains: 0, sets: 0, rules: 0 }, in_chain = false; + for (let l in split(t ?? '', '\n')) { + l = trim(l); + if (substr(l, 0, 6) == 'chain ') { + n.chains++; + in_chain = true; + } + else if (substr(l, 0, 4) == 'set ') + n.sets++; + else if (in_chain && l == '}') + in_chain = false; + else if (in_chain && l != '' && substr(l, 0, 5) != 'type ' && substr(l, 0, 7) != 'policy ' && substr(l, 0, 1) != '#') + n.rules++; + } + return n; +}; + +/** + * The sets in syslog: info with each set that changed ("inet_ok 3 → 4: +10.8.0.5"), + * debug when none did; remembered for the next time. + */ +function log_sets(sets, how) { + let first = read_json(SETS_SEEN, null) == null; + let was = read_json(SETS_SEEN, {}), now = {}, diff = []; + for (let name in SETS) { + let a = uniq(was[name] ?? []), b = uniq(sets[name] ?? []); + now[name] = b; + let add = filter(b, (x) => index(a, x) < 0), del = filter(a, (x) => index(b, x) < 0); + if (length(add) || length(del)) + push(diff, `${name} ${length(a)} → ${length(b)}${length(add) ? ': +' + some_of(add) : ''}${length(del) ? (length(add) ? ' ' : ': ') + '-' + some_of(del) : ''}`); + } + write_json(SETS_SEEN, now, 0o600); + // The first load since the router started: how many in each set (the members at debug). + if (first) { + syslog('info', 'nftables', `table inet dawnline: ${how} · ${join(', ', map(SETS, (n) => `${n} ${length(now[n])}`))}`); + for (let n in SETS) + if (length(now[n])) + syslog('debug', 'nftables', `set ${n}: ${join(' ', now[n])}`); + } + else if (length(diff)) + syslog('info', 'nftables', `table inet dawnline: ${how} · ${join('; ', diff)}`); + else + syslog('debug', 'nftables', `table inet dawnline: ${how} · sets unchanged (${join(', ', map(SETS, (n) => `${n} ${length(now[n])}`))})`); +} function ip4(a) { return ip2int(a ?? '') != null; @@ -260,7 +309,17 @@ export function render(m, sets, ctx) { /** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */ export function rebuild(m, sets) { - return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets)); + let t = table(m, sets); + let err = load('table inet dawnline\ndelete table inet dawnline\n' + t); + if (err) { + syslog('error', 'nftables', `table inet dawnline: rebuild failed · ${err}`); + return err; + } + let n = shape(t); + syslog('info', 'nftables', sprintf('table inet dawnline: rebuilt · %d chains, %d sets, %d rules', n.chains, n.sets, n.rules)); + syslog_lines('debug', 'nftables', t, 'nft: '); + log_sets(sets, 'sets loaded with the table'); + return null; }; /** @@ -276,7 +335,12 @@ export function update(sets) { if (length(members)) s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`; } - return load(s); + let err = load(s); + if (err) + syslog('warn', 'nftables', `table inet dawnline: set update failed, rebuilding · ${err}`); + else + log_sets(sets, 'sets updated'); + return err; }; /** Is the table loaded (watchdog). */ diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc index 0920997..39ce6f1 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc @@ -5,7 +5,7 @@ // GET //api/state // POST //api/devices { name, kind, public_key?, lan_bypass? } // GET //api/devices//config -// POST //api/devices/ { action: rename|rotate|delete, name? } +// POST //api/devices/ { action: rename|reconnect|bypass|delete, name?, kind?, lan_bypass?, on? } // // The personal link is the key: every request carries its code, there are // no sessions. Without a valid code every path answers the same bare 404 — @@ -33,10 +33,11 @@ // that answers anything not shaped like a link (its not_found() twin). import { stat, readfile } from 'fs'; -import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util'; +import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, syslog, VERSION, RUN_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as awg from 'dawnline.awg'; import * as live from 'dawnline.live'; +import * as lookup from 'dawnline.lookup'; import * as view from 'dawnline.view'; import * as schema from 'dawnline.schema'; import * as devices from 'dawnline.devices'; @@ -423,6 +424,17 @@ function api_state(r) { send_json(r, '200 OK', state(r)); } +/** + * A configuration as the portal sends it: with the server's address as an IP + * too (amnezia.host_ip, lookup.host_ip()), for V2RayTun on Android, which + * takes no name for AmneziaWG. Lookups are cached for minutes (lookup.uc). + */ +function with_ip(cfg) { + if (cfg?.amnezia) + cfg.amnezia.host_ip = lookup.host_ip(cfg.amnezia.host); + return cfg; +} + function api_add(r) { need_open(r); need_https(r); @@ -433,7 +445,7 @@ function api_add(r) { // lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off. let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true })); reload(r); - send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) }); + send_json(r, '200 OK', { id: res.id, config: with_ip(res.config), state: state(r) }); } function api_config(r, id) { @@ -441,7 +453,7 @@ function api_config(r, id) { need_open(r); need_https(r); awg.mark_issued(r.m, d.id); - send_json(r, '200 OK', awg.client_config(r.m, d)); + send_json(r, '200 OK', with_ip(awg.client_config(r.m, d))); } /** POST /devices/ { action }: what each action does; the answer carries the new state. */ @@ -455,8 +467,20 @@ const ACTIONS = { need_https(r); if (!devices.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 }; + // What it is and LAN Bypass may change with the keys (the sheet asks again); left out, they stay. + let kind = type(b.kind) == 'string' ? b.kind : null; + let bypass = type(b.lan_bypass) == 'bool' ? b.lan_bypass : null; + let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer, + kind, lan_bypass: bypass })); + return { config: with_ip(config) }; + }, + // LAN Bypass on or off, keys unchanged: the device takes its updated configuration (the set-up sheet opens on it). + bypass: (r, d, b) => { + need_https(r); + if (type(b.on) != 'bool') + fail(r, '400 Bad Request', _('Unknown action.')); + guard(r, () => devices.update(d.id, { lan_bypass: b.on }, { by: 'portal', person: r.person.id })); + return {}; }, 'delete': (r, d, b) => { guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id })); @@ -590,7 +614,11 @@ export function serve(io) { handle(io); } catch (e) { - if (e.message != DONE) + if (e.message != DONE) { + // What broke and where; the path without its first part (the person's link code is a secret). + let path = replace(split(io.env.REQUEST_URI ?? '', '?')[0], /^\/[^\/]*/, '/'); + syslog('error', 'portal', `${io.env.REQUEST_METHOD ?? '?'} ${path}: 500 · ${e.message}${e.stacktrace?.[0]?.context ? ' · ' + replace(e.stacktrace[0].context, /[\r\n\t]+/g, ' ') : ''}`); io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`); + } } }; diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc index 169e14b..ad7e37a 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/resolver.uc @@ -6,7 +6,7 @@ import { readfile, writefile, stat } from 'fs'; import { cursor } from 'uci'; -import { ensure_dir, iface_status, uniq } from 'dawnline.util'; +import { ensure_dir, iface_status, uniq, syslog, syslog_lines } from 'dawnline.util'; import * as net from 'dawnline.net'; import * as core from 'dawnline.core'; @@ -90,10 +90,15 @@ export function sync(m, target, lan) { for (let d in lan_domain(m)) push(lines, `server=/${d}/${lan}`); let conf = join('\n', lines) + '\n'; - if ((readfile(CONF) ?? '') == conf) + let where = target.mode == 'ns' ? `${target.address}:${target.port} in the netns` : length(ifs) ? `port ${target.port} on ${join(', ', ifs)}` : 'loopback only (no tunnel on)'; + if ((readfile(CONF) ?? '') == conf) { + syslog('debug', 'dns', `resolver for Home-only devices: unchanged · ${where}`); return false; + } writefile(CONF, conf); system(`chmod 644 ${CONF}`); + syslog('info', 'dns', `resolver for Home-only devices: ${CONF} written · ${where} · upstream ${join(' ', wan_dns()) || 'none'}${lan ? ` · home names via ${lan}` : ''}; restarting it`); + syslog_lines('debug', 'dns', conf, 'dnsmasq: '); let pid = trim(readfile(PID) ?? ''); if (match(pid, /^[0-9]+$/)) system(`kill ${pid} 2>/dev/null`); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc index 77be170..ae189a9 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/people.uc @@ -8,6 +8,7 @@ import * as view from 'dawnline.view'; import * as awg from 'dawnline.awg'; import * as store from 'dawnline.store'; import * as devices from 'dawnline.devices'; +import * as lookup from 'dawnline.lookup'; import { wrap, str, clamp_days } from 'dawnline.rpc.common'; import { _ } from 'dawnline.i18n'; @@ -155,7 +156,13 @@ function device_config(a) { die(_('Unknown device.')); if (a.issue === true) awg.mark_issued(m, d.id); - return awg.client_config(m, d); + let cfg = awg.client_config(m, d); + // V2RayTun on Android takes the server by its IP (the admin's set-up shows its link for phones, tablets and + // other devices): only where it can connect at all, and AmneziaWG 3.1 (Maximum) is beyond it. + let srv = m.servers[m.people[d.person]?.server]; + if (cfg && d.kind != 'router' && d.kind != 'computer' && srv?.preset != 'max') + cfg.amnezia.host_ip = lookup.host_ip(cfg.amnezia.host); + return cfg; } /** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */ diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc index de9bf30..25e05f5 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/rpc/settings.uc @@ -2,7 +2,7 @@ // history, updates). What may be saved is dawnline.schema's. import { stat } from 'fs'; -import { q, sh_out, admin_log, RUN_DIR, DATA_DIR } from 'dawnline.util'; +import { q, sh_out, admin_log, syslog, RUN_DIR, DATA_DIR } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as live from 'dawnline.live'; import * as apply from 'dawnline.apply'; @@ -96,16 +96,25 @@ function settings_update(a) { die(_('Nothing to save.')); let res = store.transact((c, m) => { let restart = false; + // What each key was and became, as uci holds them (for syslog: every change, not only those worth a line). + let diff = []; + let note = (k, to) => { + let from = c.get(core.CONFIG, 'settings', k); + if (!same(to, from)) + push(diff, { k, from, to }); + }; c.set(core.CONFIG, 'settings', 'settings'); for (let k, val in v) { if (k == 'log_category') { let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0); + note(k, length(lst) ? lst : [ '' ]); c.set(core.CONFIG, 'settings', 'log_category', length(lst) ? lst : [ '' ]); // Superseded by the category list. c.delete(core.CONFIG, 'settings', 'log_connections'); continue; } let nv = schema.validate(k, val); + note(k, nv); if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k))) restart = true; if (nv == null) @@ -114,8 +123,13 @@ function settings_update(a) { c.set(core.CONFIG, 'settings', k, nv); } check_portal(core.load(c), m); - return { restart, was: m.settings }; + return { restart, was: m.settings, diff }; }); + // Every setting that changed, in syslog: "admin changed settings · log_keep_days: 30 → 90, domain: lan → home". + if (length(res.diff)) { + let val = (x) => x == null || x == '' ? 'default' : type(x) == 'array' ? join(' ', filter(x, (y) => y != '')) || 'none' : `${x}`; + syslog('info', 'settings', `admin changed settings · ${join(', ', map(res.diff, (d) => `${d.k}: ${val(d.from)} → ${val(d.to)}`))}`); + } let s = null; if (res.restart) system('/etc/init.d/dawnline reload >/dev/null 2>&1'); diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc index 71f5c0e..436af89 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc @@ -127,6 +127,8 @@ export const SETTINGS = { geo_enabled: { type: 'bool', dflt: false }, geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ] }, log_connections: { type: 'bool', dflt: true }, + // What goes to syslog (dawnline.util syslog): error | warn | info | debug (each step of a start or an apply). + log_level: { type: 'enum', dflt: 'info', values: [ 'error', 'warn', 'info', 'debug' ] }, watchdog: { type: 'bool', dflt: true }, log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999 }, log_max: { type: 'int', dflt: 2000, min: 100, max: 20000 }, @@ -158,6 +160,7 @@ function messages() { 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_level: _('Choose a system log level: errors, warnings, normal or verbose.'), 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.'), diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc index 31eae30..4e77696 100644 --- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc +++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc @@ -5,7 +5,7 @@ import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; import { _ } from 'dawnline.i18n'; -export const VERSION = '0.17.0'; +export const VERSION = '0.18.0'; /** GitHub repository with Dawnline releases (updates and the installer). */ export const REPO = 'tickcount/luci-app-dawnline'; export const RUN_DIR = '/var/run/dawnline'; @@ -226,6 +226,96 @@ export function ack_config(confs) { writefile(md5f, join('\n', lines) + '\n'); }; +/* ---------- syslog ---------- */ + +/* + * Every line Dawnline puts in syslog, as podkop and sing-box do it: + * dawnline: [info] [awg] Home started · accepting connections on port 51820 + * with the matching priority (daemon.err, .warning, .info, .debug), so + * `logread -e dawnline` or a remote syslog filters by level. The admin's + * level (settings.log_level) decides what goes out: error | warn | info + * (the default) | debug (each step of a start or an apply). + */ +const LOG_RANK = { error: 0, warn: 1, info: 2, debug: 3 }; +const LOG_PRIO = { error: 'err', warn: 'warning', info: 'info', debug: 'debug' }; +const LOG_LEVEL_RE = regexp("option log_level '?(error|warn|info|debug)'?"); +// The level as last read, and the config file's mtime it was read at (a long-running agent sees a change). +let log_cfg = { mtime: -1, level: 'info' }; + +/** The admin's syslog level (settings.log_level): error | warn | info | debug; info when not set. */ +export function log_level() { + let mt = stat('/etc/config/dawnline')?.mtime ?? 0; + if (mt != log_cfg.mtime) { + let m = match(readfile('/etc/config/dawnline') ?? '', LOG_LEVEL_RE); + log_cfg = { mtime: mt, level: m?.[1] ?? 'info' }; + } + return log_cfg.level; +}; + +/** Does a line at `level` go out at the admin's level? */ +export function log_on(level) { + return (LOG_RANK[level] ?? 2) <= LOG_RANK[log_level()]; +}; + +// A line break or a tab with the blanks around it: one space in a syslog line (compiled once, syslog runs often). +const LOG_BREAK = /[ \t\r\n]*[\t\r\n][ \t\r\n]*/g; + +/** One syslog line's words: "[level] [src] line", on one line, at most 1000 characters. */ +export function syslog_line(level, src, line) { + let one = replace(trim(`${line ?? ''}`), LOG_BREAK, ' '); + return substr(`[${LOG_RANK[level] != null ? level : 'info'}] [${src ?? 'dawnline'}] ${one}`, 0, 1000); +}; + +/** + * A line in syslog at `level` (error | warn | info | debug) from `src` + * (dawnline, awg, portal, apply, agent, service, settings, people, …), when + * the admin's level takes it. Nothing is kept anywhere else: what the admin UI + * shows goes through slog() below, which calls this too. + */ +export function syslog(level, src, line) { + if (!log_on(level)) + return; + system(`logger -t dawnline -p daemon.${LOG_PRIO[level] ?? 'info'} ${q(syslog_line(level, src, line))}`); +}; + +// Option names whose values never go in a log line: private, preshared and header-protection keys. +const SECRET_OPT = /(private|preshared|protection)_?key/; + +/** + * Options as a log line's words: "listen_port=51820, addresses=10.8.0.1/24, + * private_key=***" (arrays joined with spaces, null as "-", secrets masked). + */ +export function opts_text(o) { + let out = []; + for (let k, v in o ?? {}) { + let s = v == null ? '-' : type(v) == 'array' ? join(' ', v) : `${v}`; + push(out, `${k}=${match(k, SECRET_OPT) ? '***' : s}`); + } + return join(', ', out); +}; + +/** + * A block of text in syslog, a line per line (an nft script, a peer list), + * each "[level] [src] ": one logger for all of them. + */ +export function syslog_lines(level, src, text, prefix) { + if (!log_on(level) || trim(`${text ?? ''}`) == '') + return; + let p = popen(`logger -t dawnline -p daemon.${LOG_PRIO[level] ?? 'info'}`, 'w'); + if (!p) + return; + for (let l in split(`${text ?? ''}`, '\n')) + if (trim(l) != '') + p.write(syslog_line(level, src, `${prefix ?? ''}${trim(l)}`) + '\n'); + p.close(); +}; + +/** A list in a log line: the first `n` (10) and how many more ("a, b, c and 12 more"). */ +export function some_of(list, n) { + n ??= 10; + return length(list) <= n ? join(', ', list) : `${join(', ', slice(list, 0, n))} and ${length(list) - n} more`; +}; + /* ---------- service log ---------- */ /* @@ -257,7 +347,11 @@ export function slog(src, level, msg, detail, who, extra) { f.close(); } let line = e.by == 'admin' ? join(' ', filter([ 'admin', msg, e.kind, who, e.note ? '· ' + e.note : null ], (x) => x)) : who ? `${who} ${msg}` : msg; - system(`logger -t dawnline${level == 'error' ? ' -p user.err' : ''} ${q(line)}`); + // Problems carry what went wrong (the service log's detail: an error's text, the syslog lines around a crash). + let lvl = { error: 'error', repair: 'warn', down: 'warn' }[level] ?? 'info'; + if (e.detail && lvl != 'info') + line += ` · ${substr(replace(e.detail, /[\r\n\t]+/g, ' | '), 0, 400)}`; + syslog(lvl, src, line); }; /** A change the admin made in LuCI, for the service log. */ diff --git a/tests/ucode/core.test.uc b/tests/ucode/core.test.uc index ae66ae0..a7fdc6c 100644 --- a/tests/ucode/core.test.uc +++ b/tests/ucode/core.test.uc @@ -154,6 +154,18 @@ function recorder() { return { w, c: { set: (cfg, s, k, v) => { w[`${s}.${k}`] = v; }, delete: (cfg, s, k) => { w[`${s}.${k}`] = null; } } }; } +test('set_device_kind', () => { + let mm = { devices: { d: { id: 'd', kind: 'phone' } } }; + let r = recorder(); + eq(core.set_device_kind(r.c, mm, 'd', 'tablet'), true, 'changed'); + eq([ r.w, mm.devices.d.kind ], [ { 'd.kind': 'tablet' }, 'tablet' ], 'written, and the model follows'); + r = recorder(); + eq(core.set_device_kind(r.c, mm, 'd', 'tablet'), false, 'the same kind changes nothing'); + eq(r.w, {}, 'nothing written'); + throws(() => core.set_device_kind(r.c, mm, 'd', 'toaster'), /^Unknown device type\.$/, 'not a kind'); + throws(() => core.set_device_kind(r.c, mm, 'x', 'phone'), /^Unknown device\.$/, 'unknown device'); +}); + test('set_device_link', () => { let mm = { devices: { d: { id: 'd', mtu: 0, keepalive: null, lan_bypass: false } } }; let r = recorder(); diff --git a/tests/ucode/devices.test.uc b/tests/ucode/devices.test.uc index a32315a..2aa7c2d 100644 --- a/tests/ucode/devices.test.uc +++ b/tests/ucode/devices.test.uc @@ -4,14 +4,16 @@ // sync's nft and awg steps fail harmlessly in the container. /etc/config/dawnline // and the issued and reconnect marks are put back after. import { readfile, writefile, unlink } from 'fs'; -import { DATA_DIR, ensure_dir } from 'dawnline.util'; +import { DATA_DIR, RUN_DIR, ensure_dir } from 'dawnline.util'; import * as core from 'dawnline.core'; import * as awg from 'dawnline.awg'; import * as people from 'dawnline.rpc.people'; +import * as devices from 'dawnline.devices'; const CONFIG = '/etc/config/dawnline'; const ISSUED = `${DATA_DIR}/issued.json`; const RECONNECT = `${DATA_DIR}/reconnect.json`; +const EVENTS = `${RUN_DIR}/events.json`; // fn(), then the files as they were, whatever fn did. function kept(paths, fn) { @@ -65,3 +67,20 @@ test('device_rotate: New keys set the device up again', () => { }); eq(core.load().devices.alice_phone.private_key, '', 'the fixture is back'); }); + +test('portal: Reconnect changes what it is and LAN Bypass with the keys; LAN Bypass alone keeps them', () => { + ensure_dir(RUN_DIR); + kept([ CONFIG, ISSUED, RECONNECT, EVENTS ], () => { + let mine = { by: 'portal', person: 'alice' }; + devices.reconnect('alice_phone', { ...mine, kind: 'tablet', lan_bypass: true }); + let d = core.load().devices.alice_phone; + eq([ d.kind, d.lan_bypass ], [ 'tablet', true ], 'changed in the same write as the keys'); + let keys = d.public_key; + devices.update('alice_phone', { lan_bypass: false }, mine); + d = core.load().devices.alice_phone; + eq([ d.lan_bypass, d.public_key ], [ false, keys ], 'LAN Bypass off, the keys as they were'); + throws(() => devices.update('alice_phone', { mtu: '1400' }, mine), /^Only the admin can change how a device connects\.$/, "the MTU stays the admin's"); + throws(() => devices.reconnect('alice_phone', { ...mine, kind: 'toaster' }), /^Unknown device type\.$/, 'not a kind'); + throws(() => devices.update('alice_phone', { lan_bypass: true }, { by: 'portal', person: 'bob' }), /^Device not found\.$/, "another person's device"); + }); +}); diff --git a/tests/ucode/live.test.uc b/tests/ucode/live.test.uc index bc438cc..fbd46a5 100644 --- a/tests/ucode/live.test.uc +++ b/tests/ucode/live.test.uc @@ -180,3 +180,15 @@ test('add_event_merged: per device', () => { eq(live.category_of('device_recovered'), 'problems', 'and so is its end'); had == null ? unlink(path) : writefile(path, had); }); + +test('event_level and event_line: the system\'s events in syslog', () => { + eq(live.event_level({ type: 'connect' }), null, 'a connection stays out of syslog'); + eq(live.event_level({ type: 'roam' }), null, 'so does a device moving networks'); + eq(live.event_level({ type: 'device_failing' }), null, "and a device's link trouble"); + eq(live.event_level({ type: 'device_changed' }), 'info', 'people and devices are info'); + eq(live.event_level({ type: 'server_down' }), 'warn', 'a problem is warn'); + eq(live.event_level({ type: 'server_up' }), 'info', 'its end is info'); + eq(live.event_line({ type: 'device_changed', pname: 'Myata', dname: 'Phone', detail: 'kind=phone, lan_bypass=on', by: 'portal' }), + 'Myata · Phone device changed · kind=phone, lan_bypass=on (portal)', 'names, what, detail, by whom'); + eq(live.event_line({ type: 'paused', person: 'p1' }), 'p1 paused', 'the id where there is no name'); +}); diff --git a/tests/ucode/nft.test.uc b/tests/ucode/nft.test.uc index 6843570..0e0b417 100644 --- a/tests/ucode/nft.test.uc +++ b/tests/ucode/nft.test.uc @@ -47,3 +47,9 @@ test('render: the table as it was', () => { m.devices.b1.lan_bypass = true; eq(render(m), golden, 'a device that keeps its own local network out of the tunnel changes nothing here'); }); + +test('shape: chains, sets and rules of a table script', () => { + let t = 'table inet dawnline {\n\tset inet_ok {\n\t\ttype ipv4_addr\n\t}\n\tchain forward {\n\t\ttype filter hook forward priority 0; policy accept;\n\t\tiifname "dawn0" ip saddr @inet_ok accept\n\t\t# a note\n\t\tiifname "dawn0" drop\n\t}\n}\n'; + eq(nft.shape(t), { chains: 1, sets: 1, rules: 2 }, 'the hook line, the policy and a comment are no rules'); + eq(nft.shape(''), { chains: 0, sets: 0, rules: 0 }, 'nothing'); +}); diff --git a/tests/ucode/schema.test.uc b/tests/ucode/schema.test.uc index f2af829..f502867 100644 --- a/tests/ucode/schema.test.uc +++ b/tests/ucode/schema.test.uc @@ -26,6 +26,8 @@ test('validate: int', () => { test('validate: enum', () => { eq(schema.validate('geo_provider', 'ipapi.co'), 'ipapi.co', 'known'); throws(() => schema.validate('geo_provider', 'maxmind'), /Unknown location service/, 'unknown'); + eq(schema.validate('log_level', 'debug'), 'debug', 'a syslog level'); + throws(() => schema.validate('log_level', 'trace'), /system log level/, 'not a syslog level'); eq(schema.validate('update_interval', '7d'), '7d', 'interval from dawnline.updates'); throws(() => schema.validate('update_interval', '2d'), /6h, 12h, 1d or 7d/, 'unknown interval'); }); diff --git a/tests/ucode/util.test.uc b/tests/ucode/util.test.uc index fcf7d21..27d014b 100644 --- a/tests/ucode/util.test.uc +++ b/tests/ucode/util.test.uc @@ -318,3 +318,18 @@ test('host_label, tunnel_name, slugify: dashes trimmed without a regex', () => { } same(null); }); + +test('syslog_line', () => { + eq(util.syslog_line('warn', 'awg', 'Home stopped unexpectedly'), '[warn] [awg] Home stopped unexpectedly', 'level, source, words'); + eq(util.syslog_line('error', 'apply', 'failed:\n no table\tthere'), '[error] [apply] failed: no table there', 'one line'); + eq(util.syslog_line('loud', null, 'x'), '[info] [dawnline] x', 'an unknown level is info, no source is dawnline'); + eq(length(util.syslog_line('info', 'x', replace(sprintf('%1500s', ''), ' ', 'y'))), 1000, 'at most 1000 characters'); +}); + +test('opts_text: options in a log line, keys masked', () => { + eq(util.opts_text({ listen_port: 51820, addresses: [ '10.8.0.1/24' ], private_key: 'abc=', mtu: null }), + 'listen_port=51820, addresses=10.8.0.1/24, private_key=***, mtu=-', 'values, lists, a secret, nothing'); + eq(util.opts_text({ preshared_key: 'x', awg_header_protection_key: 'y', public_key: 'z' }), + 'preshared_key=***, awg_header_protection_key=***, public_key=z', 'a public key is no secret'); + eq(util.opts_text(null), '', 'none'); +}); diff --git a/web/package-lock.json b/web/package-lock.json index 7273658..04014ba 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "dawnline-web", - "version": "0.17.0", + "version": "0.18.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dawnline-web", - "version": "0.17.0", + "version": "0.18.0", "license": "MIT", "dependencies": { "qrcode-generator": "2.0.4" diff --git a/web/package.json b/web/package.json index 5e18a4a..7e54e4a 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "dawnline-web", - "version": "0.17.0", + "version": "0.18.0", "private": true, "license": "MIT", "type": "module", diff --git a/web/src/admin/cores/awg.ts b/web/src/admin/cores/awg.ts index 41f16b3..5176b5a 100644 --- a/web/src/admin/cores/awg.ts +++ b/web/src/admin/cores/awg.ts @@ -1,8 +1,8 @@ // The AmneziaWG core in the admin: how a device connects (.conf, AmneziaVPN -// key, QR), the disguise and its parameters, and the core's own settings on +// key, QR, V2RayTun's link), the disguise and its parameters, and the core's own settings on // Server → AmneziaWG. Plain WireGuard is AmneziaWG with the disguise off. -import type { AwgConfig, Server, Status } from '../../shared/types'; +import type { AwgConfig, Kind, Server, Status } from '../../shared/types'; import { E } from '../e'; import { api } from '../api'; import { button } from '../ui/button'; @@ -14,10 +14,12 @@ import { callout, card, firstBad, group, liveRow, row } from '../ui/layout'; import { qrCode } from '../ui/qr'; import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck'; import { vpnKey } from '../../shared/vpnkey'; +import { awgLink, v2rFits } from '../../shared/awglink'; +import { V2R_WINDOWS } from '../../shared/flags'; 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'; +import { coreHead, type ConnectView, type Core, type CoreCtx } from './common'; /** `.conf` names of the disguise parameters, in file order. */ const CONF: [string, string][] = [ @@ -219,8 +221,71 @@ export function plainWg(cfg: AwgConfig): boolean { return Object.entries(o).every(([k, v]) => v == null || v === '' || v === (neutral[k] ?? '0')); } -/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */ -async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise { +/** + * V2RayTun's way in: the connection as its awg:// link (shared/awglink.ts; + * the app's own words are in portal/setup.ts, with where they come from). A + * computer runs it on Windows, whose core looks the server's name up itself: + * the link keeps the name. That one is off for now (shared/flags.ts + * V2R_WINDOWS: its core leaves the server's DNS unused). Anything else is + * taken for Android, whose core takes no name: the link has the server's IP + * (amnezia.host_ip, from device_config). + */ +function v2rPane(cfg: AwgConfig, kind: Kind): HTMLElement { + const win = kind === 'computer'; + const host = cfg.amnezia.host.replace(/^\[(.*)\]$/, '$1'); + const ip = win ? null : (cfg.amnezia.host_ip ?? null); + const link = awgLink(cfg.conf, cfg.server, ip); + const box = E('div', { class: 'dl-linkbox' }, [ + E('span', { class: 'dl-mono', title: link }, link), + button(_('Copy'), () => copyText(link, _('Link copied'))), + ]); + if (win) + return E('div', { class: 'dl-stack gap8' }, [ + box, + E( + 'span', + { class: 'dl-sub' }, + fmt( + _( + 'V2RayTun on Windows: %s, then set its mode to %s and connect. That mode needs administrator rights: the app offers to restart with them.', + ), + ['+', _('Import from clipboard', 'V2RayTun app')].join(' → '), + _('Tunnel', 'V2RayTun app'), + ), + ), + ]); + return E('div', { class: 'dl-qr-pane' }, [ + qrCode(link), + E( + 'span', + { class: 'dl-sub' }, + fmt( + _('V2RayTun on Android: %s, or copy the link and %s.'), + ['+', _('Import config from QRcode', 'V2RayTun app')].join(' → '), + ['+', _('Import config from Clipboard', 'V2RayTun app')].join(' → '), + ), + ), + box, + // Honest about what the IP costs, and about a name that gives none. + ip && ip !== host + ? E( + 'div', + { class: 'dl-hint' }, + _('The link has the server’s IP address, not its name: if the address changes, set the device up again.'), + ) + : !ip + ? callout('warn', fmt(_('%s does not resolve right now, and V2RayTun on Android connects by IP address only.'), host)) + : '', + ]); +} + +/** + * File / key / QR / V2RayTun switcher for a client configuration of a device + * of this kind; opens on the file unless asked otherwise. V2RayTun is left out + * for a router, for a computer while V2R_WINDOWS is off (shared/flags.ts) and + * for AmneziaWG 3.1 (the Maximum disguise), which it lacks. + */ +async function connectBlock(cfg: AwgConfig, kind: Kind, initial: ConnectView = 'file'): Promise { if (!cfg.has_private_key) return E( 'div', @@ -228,7 +293,7 @@ async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'fi _('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 Node> = { + const panes: Partial Node>> = { qr: () => E('div', { class: 'dl-qr-pane' }, [ qrCode(cfg.conf), @@ -252,19 +317,22 @@ async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'fi ]), file: () => fileCard(cfg), }; - const body = E('div', { class: 'dl-connect-body' }); - const seg = E('div', { class: 'dl-seg' }); - const show = (id: string) => { - seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id)); - dom.content(body, panes[id]()); - }; - for (const [id, label] of [ + if (kind !== 'router' && (kind !== 'computer' || V2R_WINDOWS) && v2rFits(cfg.conf)) panes.v2r = () => v2rPane(cfg, kind); + const labels: [ConnectView, string][] = [ ['file', _('File')], ['key', _('Key')], ['qr', _('QR code')], - ]) - seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label)); - show(initial); + ['v2r', 'V2RayTun'], + ]; + const body = E('div', { class: 'dl-connect-body' }); + const seg = E('div', { class: 'dl-seg' }); + const show = (id: ConnectView) => { + seg.querySelectorAll('button').forEach((b) => b.classList.toggle('on', b.dataset.id === id)); + dom.content(body, panes[id]!()); + }; + for (const [id, label] of labels) + if (panes[id]) seg.appendChild(E('button', { type: 'button', 'data-id': id, click: () => show(id) }, label)); + show(panes[initial] ? initial : 'file'); return E('div', { class: 'dl-stack gap12' }, [seg, body]); } diff --git a/web/src/admin/cores/common.ts b/web/src/admin/cores/common.ts index 86f7e5c..8c7a79c 100644 --- a/web/src/admin/cores/common.ts +++ b/web/src/admin/cores/common.ts @@ -1,9 +1,12 @@ // What every tunnel core gives the admin (cores/index.ts holds the registry), // what a core's settings card gets from the Server page, and that card's head. -import type { ClientConfig, Server, Status } from '../../shared/types'; +import type { ClientConfig, Kind, Server, Status } from '../../shared/types'; import { E } from '../e'; +/** The ways a device takes its configuration, as the set-up switcher names them. */ +export type ConnectView = 'file' | 'key' | 'qr' | 'v2r'; + /** What the Server page hands a core's settings card. */ export interface CoreCtx { st: Status; @@ -21,8 +24,8 @@ export interface Core { settingsCard(ctx: CoreCtx, srv: Server): HTMLElement; /** Overview: how the tunnel looks on the wire (the disguise tile). */ overviewTile(srv: Server): HTMLElement; - /** How a device connects: file / key / QR. */ - connectBlock(cfg: ClientConfig, initial?: 'file' | 'key' | 'qr'): Promise; + /** How a device of this kind connects: file / key / QR / V2RayTun's link, opening on `initial`. */ + connectBlock(cfg: ClientConfig, kind: Kind, initial?: ConnectView): Promise; /** What a QR code for the device carries. */ qrText(cfg: ClientConfig): string; /** The key the device's app imports (⋯ → Copy key), with the menu label. */ diff --git a/web/src/admin/device.ts b/web/src/admin/device.ts index 2caaf18..0343a7f 100644 --- a/web/src/admin/device.ts +++ b/web/src/admin/device.ts @@ -189,7 +189,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) { let today = o.today ?? isoDay(new Date()); let srv = o.server; // Phones and tablets are set up by scanning; computers and routers by a file. - const block = (c: ClientConfig) => core.connectBlock(c, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file'); + const block = (c: ClientConfig) => core.connectBlock(c, dev.kind, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file'); // An older configuration on the device: the new one waits for a click (the inline QR code is itself a delivery). // `relinked`: its MTU or keep-alive was just changed here, which outdates the configuration on screen even where // the router keeps no record of what the device got (never "stale" then, e.g. after a JSON import). @@ -665,8 +665,8 @@ export function addDevice(person: Person, o: DeviceOpts) { ), ), ); - // LAN Bypass: off unless chosen (the person chooses it on the portal, the admin here). - const bypass = sw(false, _('LAN Bypass')); + // LAN Bypass: on unless turned off (the person chooses it on the portal, the admin here). + const bypass = sw(true, _('LAN Bypass')); const over = person.devices.length >= person.device_limit; modal( fmt(_('Add a device for %s'), person.name), diff --git a/web/src/admin/events/model.ts b/web/src/admin/events/model.ts index 99d7220..423d3ea 100644 --- a/web/src/admin/events/model.ts +++ b/web/src/admin/events/model.ts @@ -1,7 +1,8 @@ // The activity log's vocabulary: categories, who did what, problems, retention. // No DOM and no RPC here (see ./render for rows). -import type { LogEvent } from '../../shared/types'; +import type { Kind, LogEvent } from '../../shared/types'; +import { kindLabel } from '../../shared/format'; import type { LogCategory, LogsInfo, ServiceLogEntry } from '../api'; import { fmt, known, plural } from '../../shared/i18n'; import { LOG_TEMPLATES } from './log-templates'; @@ -136,13 +137,25 @@ export function changedText(detail: string): string { .join(', '); } -/** A device's settings a device_changed event lists (its link options, "mtu, keepalive"); anything else as written. */ +/** + * A device's settings a device_changed event lists: each with what it became + * ("lan_bypass=on", "kind=phone", "mtu=1400", "keepalive=auto": the server's), + * or by name alone as events before 0.18 have them ("mtu, keepalive"); + * anything else as written. + */ export function deviceChangedText(detail: string): string { - const f: Record = { mtu: 'MTU', keepalive: _('keep-alive'), lan_bypass: _('LAN Bypass') }; - return detail - .split(', ') - .map((k) => f[k] ?? k) - .join(', '); + const f: Record = { mtu: 'MTU', keepalive: _('keep-alive'), lan_bypass: _('LAN Bypass'), kind: _('type') }; + const one = (part: string): string => { + const at = part.indexOf('='); + if (at < 0) return f[part] ?? part; + const k = part.slice(0, at); + const v = part.slice(at + 1); + if (k === 'lan_bypass') return v === 'on' ? _('LAN Bypass on') : _('LAN Bypass off'); + if (k === 'kind') return fmt(_('type: %s'), ['computer', 'phone', 'tablet', 'router', 'other'].includes(v) ? kindLabel(v as Kind) : v); + if (v === 'auto') return fmt(_('%s: automatic'), f[k] ?? k); + return k === 'keepalive' ? fmt(_('keep-alive %s s'), v) : `${f[k] ?? k} ${v}`; + }; + return detail.split(', ').map(one).join(', '); } /** diff --git a/web/src/admin/events/render.ts b/web/src/admin/events/render.ts index f4cf70e..88ea063 100644 --- a/web/src/admin/events/render.ts +++ b/web/src/admin/events/render.ts @@ -179,6 +179,14 @@ export function eventText(st: Pick, e: LogEvent, personId?: st ]; if (detail === 'turned off') return say(_('Device %s turned off'), wd); if (detail === 'turned on') return say(_('Device %s turned on'), wd); + // On the portal: LAN Bypass from its ⋯ menu, what it is and LAN Bypass with Reconnect. + if (by === 'portal') + return [ + ...(scoped + ? say(_('Device %s changed on the portal'), b(dev || _('a device'))) + : say(_('Person %s changed device %s on their portal'), b(who), b(dev || _('a device')))), + ...(detail ? [m(` · ${deviceChangedText(detail)}`)] : []), + ]; return [...say(_('Device %s changed'), wd), ...(detail ? [m(` · ${deviceChangedText(detail)}`)] : [])]; case 'device_keys': return scoped diff --git a/web/src/admin/pages/person/devices.ts b/web/src/admin/pages/person/devices.ts index 9900cd7..1ad8a5d 100644 --- a/web/src/admin/pages/person/devices.ts +++ b/web/src/admin/pages/person/devices.ts @@ -19,7 +19,7 @@ import type { PersonPage } from './index'; async function showDeviceQr(page: PersonPage, d: Device) { const cfg = await attempt(() => api.deviceConfig(d.id, true)); if (!cfg) return; - modal(fmt(_('Set up %s'), d.name), [await page.core.connectBlock(cfg, 'qr')], [cancelButton(_('Close'))]); + modal(fmt(_('Set up %s'), d.name), [await page.core.connectBlock(cfg, d.kind, 'qr')], [cancelButton(_('Close'))]); } async function downloadConfig(page: PersonPage, d: Device) { diff --git a/web/src/admin/pages/settings/logs.ts b/web/src/admin/pages/settings/logs.ts index 4db9662..6532927 100644 --- a/web/src/admin/pages/settings/logs.ts +++ b/web/src/admin/pages/settings/logs.ts @@ -1,4 +1,5 @@ -// Settings → Logs & history: retention, what is recorded, and the stored data. +// Settings → Logs & history: retention, what is recorded, what goes to the +// router's system log, and the stored data. import { E } from '../../e'; import { api } from '../../api'; @@ -67,6 +68,17 @@ export function logsCard(host: SettingsHost): HTMLElement { String(p.usage_months), _('Monthly traffic'), ); + // The router's system log (logread): dawnline.util syslog() writes at these levels. + const level = select( + [ + ['error', _('Errors only')], + ['warn', _('Warnings and errors')], + ['info', _('Normal')], + ['debug', _('Verbose (debug)')], + ], + String(host.d.effective.log_level ?? 'info'), + _('System log'), + ); const cats = multiSelect( CATEGORIES.map((c): [string, Node] => [ c, @@ -111,6 +123,13 @@ export function logsCard(host: SettingsHost): HTMLElement { persist, _('The log lives in memory and is copied to flash. Memory only saves flash writes but is lost on reboot.'), ), + row( + _('System log'), + level, + _( + 'What Dawnline writes to the router’s system log (logread -e dawnline). Verbose adds each step of a start and of applying settings.', + ), + ), row(_('Daily traffic'), days, _('Per-day history behind the charts.')), row(_('Monthly traffic'), months, _('Per-month totals; data limits use the current month.')), E('h4', { class: 'dl-setsub' }, _('Stored data')), @@ -173,6 +192,7 @@ export function logsCard(host: SettingsHost): HTMLElement { usage_keep_days: days.value, usage_keep_months: months.value, log_category: cats.value(), + log_level: level.value, }, _('Saved'), 'logs', diff --git a/web/src/portal/demo/data.ts b/web/src/portal/demo/data.ts index 9956032..acaedfa 100644 --- a/web/src/portal/demo/data.ts +++ b/web/src/portal/demo/data.ts @@ -62,6 +62,8 @@ export interface DemoDevice { created: number; by: 'admin' | 'portal'; stale: boolean; + /** LAN Bypass (unset: off). */ + bypass?: boolean; /** A set-up state the visitor picked in the sheet (way-pick.ts), held until they pick another; none: as it comes. */ way?: DemoWay; /** When it was picked: the knocks' or the handshake's time. */ @@ -168,7 +170,7 @@ function device(d: DemoDevice, t: number, st: Person['state']): Device { hostname: `${label(d.name)}.user.lan`, browser_key: false, config_stale: d.stale, - lan_bypass: false, + lan_bypass: !!d.bypass, mtu: 0, keepalive: null, // The server's for its kind, as the router works it out (the portal never shows it). diff --git a/web/src/portal/demo/router.ts b/web/src/portal/demo/router.ts index 94d7f28..24c624b 100644 --- a/web/src/portal/demo/router.ts +++ b/web/src/portal/demo/router.ts @@ -1,5 +1,5 @@ // The demo's router: portal.uc's API (state, add a device, its settings, -// rename / reconnect / remove) answered from the demo's own devices, which it +// rename / reconnect / LAN Bypass / remove) answered from the demo's own devices, which it // keeps per visitor. The refusals are the router's (paused, ended, plain HTTP, // no free slot, a name taken). Nothing is installed and no tunnel exists: the // keys are random and the server's address never resolves. The page state @@ -158,6 +158,7 @@ export function createRouter(o: RouterOpts) { created: clock(), by: 'portal', stale: false, + bypass: b.lan_bypass === true, }; db.devs.push(d); issued = d.id; @@ -182,12 +183,24 @@ export function createRouter(o: RouterOpts) { if (b.action === 'rename') d.name = checkName(b.name, d); else if (b.action === 'reconnect') { needHttps(); + // What it is and LAN Bypass change with the keys, as on the router. + if (typeof b.kind === 'string') { + if (!KINDS.includes(b.kind as Kind)) refuse(400, 'Unknown device type.'); + d.kind = b.kind as Kind; + } + if (typeof b.lan_bypass === 'boolean') d.bypass = b.lan_bypass; // New keys: the old handshake no longer counts, the device connects again once set up. d.hs = 0; d.stale = false; d.connectAt = soon(); issued = d.id; extra = { config: config(d) }; + } else if (b.action === 'bypass') { + needHttps(); + if (typeof b.on !== 'boolean') refuse(400, 'Unknown action.'); + // The keys stay; the configuration it holds is out of date until it takes the updated one. + d.bypass = b.on as boolean; + d.stale = true; } else if (b.action === 'delete') db.devs = db.devs.filter((x) => x !== d); else refuse(400, 'Unknown action.'); return { ok: true, ...extra, state: state() }; diff --git a/web/src/portal/flows/add.ts b/web/src/portal/flows/add.ts index 4272af2..21a00de 100644 --- a/web/src/portal/flows/add.ts +++ b/web/src/portal/flows/add.ts @@ -1,40 +1,29 @@ // Adding a device: what it is (four kinds; phones and tablets are one choice, // the same apps and the same smaller packets), whether the local network it is -// on stays reachable while connected (LAN Bypass, off unless they turn it on; -// it stays as chosen: the admin's drawer shows it, neither page changes it) -// and its name, guessed from the browser when it is this device; then straight -// on to its set-up. Or the page opens on the device itself, from a code, ready -// to add it there. +// on stays reachable while connected (LAN Bypass, on unless they turn it off; +// Reconnect and the card's ⋯ menu change it later: device-actions.ts) and its +// name, guessed from the browser when it is this device; then straight on to +// its set-up. Or the page opens on the device itself, from a code, ready to add +// it there. The kinds and the switch are device-form.ts. import type { ClientConfig, Kind } from '../../shared/types'; -import { defaultName, fitName, netsLabel, pickLabel, pickOf, PICKS, type KindPick } from '../../shared/format'; +import { defaultName, fitName, pickOf, PICKS, type KindPick } from '../../shared/format'; import { guardDeviceName } from '../../shared/name-guard'; import { shake } from '../../shared/shake'; import { fmt, num, plural } from '../../shared/i18n'; import { ApiError, call } from '../api'; import { h, ic } from '../dom'; -import { SMOOTH, play } from '../motion'; import { addLink } from '../setup'; import { pageUrl, repaint, setState, state, type State } from '../state'; import { smoothCaret } from '../ui/caret'; import { linkRow, qrBox } from '../ui/codes'; import { once, toast } from '../ui/feedback'; import { badLine } from '../ui/bad-line'; -import { glass } from '../ui/glass'; import { go, head, openSheet, sub, type View } from '../ui/sheet'; import { secureFirst, showSecure } from './secure'; +import { IPAD, UA, guessKind, kindOf, kindTiles, lanSwitch } from './device-form'; import { continueSetup } from './setup-view'; -// Best guess at the device this page is open on (the browser never tells its real name). -const UA = navigator.userAgent; -const IPAD = /iPad/.test(UA) || (/Macintosh/.test(UA) && navigator.maxTouchPoints > 1); - -function guessKind(): Kind { - if (IPAD || /Tablet/i.test(UA) || (/Android/.test(UA) && !/Mobile/.test(UA))) return 'tablet'; - if (/Android|iPhone|Mobile/i.test(UA)) return 'phone'; - return 'computer'; -} - /** Samsung model codes → names people know (S and A series; the code stays in brackets). */ const GALAXY: [RegExp, string][] = [ [/^SM-S93/, 'Galaxy S25'], @@ -77,9 +66,6 @@ function guessName(kind: Kind): string { return defaultName(kind); } -// Mobile is a tablet when this page is open on one (see KindPick). -const kindOf = (p: KindPick): Kind => (p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone'); - /** * What they chose so far, kept outside the view: Back from "Open on the device" * builds the view again, and it comes back as they left it. `name`: what they @@ -91,33 +77,6 @@ interface Draft { name?: string; } -/** - * A line in a block opens or folds away: height, opacity and blur on SMOOTH, as the set-up steps fold, from - * where it is on screen (flicking the switch never snaps). The block's 1 px gap goes with it. - */ -function foldLine(el: HTMLElement, open: boolean) { - const cs = getComputedStyle(el); - const from = el.hidden - ? { h: 0, o: 0, b: 4, m: -1 } - : { - h: el.getBoundingClientRect().height, - o: +cs.opacity, - b: +(cs.filter.match(/blur\(([\d.]+)px\)/)?.[1] ?? 0), - m: parseFloat(cs.marginTop) || 0, - }; - el.getAnimations().forEach((a) => a.cancel()); - el.hidden = false; - el.style.overflow = 'hidden'; - const to = open ? { h: el.scrollHeight, o: 1, b: 0, m: 0 } : { h: 0, o: 0, b: 4, m: -1 }; - const frame = (v: typeof from) => ({ height: `${v.h}px`, opacity: v.o, filter: v.b ? `blur(${v.b}px)` : 'none', marginTop: `${v.m}px` }); - const a = play(el, [frame(from), frame(to)], { duration: SMOOTH.duration, easing: SMOOTH.easing, fill: 'forwards' }); - a.onfinish = () => { - el.hidden = !open; - el.style.overflow = ''; - a.cancel(); - }; -} - export function startAdd() { const st = state(); if (!st || st.locked) return; @@ -127,7 +86,7 @@ export function startAdd() { true, ); if (secureFirst()) return; - const draft: Draft = { bypass: false }; + const draft: Draft = { bypass: true }; openSheet(() => vAdd(draft)); } @@ -147,53 +106,8 @@ function vAdd(draft: Draft): View { return fitName(n); }; - const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') }); - kinds.style.setProperty('--n', String(picks.length)); - const tiles = picks.map((k) => { - const t = h( - 'button', - { type: 'button', class: 'kind', role: 'radio', 'aria-label': pickLabel(k), onclick: () => choose(k) }, - h('span', { class: 'kind-tile' }, glass(k, 'blue')), - h('span', { class: 'kind-lbl' }, pickLabel(k)), - ); - kinds.appendChild(t); - return t; - }); - // With home access, the home networks still go into the tunnel: a local network on the same addresses is out - // of reach, and the row says so while LAN Bypass is on. - const home = st.server.home ?? []; - const except = home.length - ? h( - 'span', - { class: 'sw-sub sw-note', hidden: !draft.bypass }, - fmt(_('Except %s: those addresses lead to the home network.'), netsLabel(home)), - ) - : null; - // The whole row is the switch. Built as they left it, before it is on the page: nothing slides. - const lan = h( - 'button', - { - type: 'button', - class: draft.bypass ? 'swrow on' : 'swrow', - role: 'switch', - 'aria-checked': String(draft.bypass), - onclick: () => { - draft.bypass = !draft.bypass; - lan.classList.toggle('on', draft.bypass); - lan.setAttribute('aria-checked', String(draft.bypass)); - if (except) foldLine(except, draft.bypass); - }, - }, - glass('lan', 'blue'), - h( - 'span', - { class: 'sw-t' }, - h('b', {}, _('LAN Bypass')), - h('span', { class: 'sw-sub' }, _('Your local network stays reachable while connected.')), - except, - ), - h('span', { class: 'sw', 'aria-hidden': 'true' }), - ); + const kinds = kindTiles(picks, (k) => choose(k)); + const lan = lanSwitch(draft.bypass, st.server.home ?? [], (on) => (draft.bypass = on)); const input = h('input', { type: 'text', // Not `required`: the browser's own check would stop an empty submit before the field can shake. @@ -222,14 +136,9 @@ function vAdd(draft: Draft): View { void modelReady.then(() => { if (draft.name === undefined && pick === pickOf(guessKind())) input.value = suggest(pick); }); - // The picked tile rings itself where it stands (the ring does not travel between tiles). function choose(k: KindPick) { pick = draft.pick = k; - tiles.forEach((t, i) => { - const on = picks[i] === k; - t.classList.toggle('on', on); - t.setAttribute('aria-checked', String(on)); - }); + kinds.set(k); if (draft.name === undefined) { input.value = suggest(k); goBtn.classList.add('ready'); @@ -278,7 +187,7 @@ function vAdd(draft: Draft): View { { class: 'view' }, head(_('Add a device')), sub(fmt(N_(p.device_limit, '%s of %s slot free', '%s of %s slots free'), num(free), num(p.device_limit))), - kinds, + kinds.el, lan, form, err, diff --git a/web/src/portal/flows/device-actions.ts b/web/src/portal/flows/device-actions.ts index 7354cb9..24936cd 100644 --- a/web/src/portal/flows/device-actions.ts +++ b/web/src/portal/flows/device-actions.ts @@ -1,19 +1,22 @@ -// A device's own actions from its ⋯ menu: Reconnect (new keys, then the set-up -// of the new ones) and Remove (Rename edits the name on the card: rename.ts). A -// question comes before what cannot be undone; the action's button stays busy -// until the router answers. +// A device's own actions from its ⋯ menu: Reconnect (new keys, what it is and +// LAN Bypass asked again, then the set-up of the new ones), LAN Bypass on or +// off (the same keys, then the set-up of the updated configuration) and Remove +// (Rename edits the name on the card: rename.ts). A question comes before what +// cannot be undone; the action's button stays busy until the router answers. import type { ClientConfig, Device } from '../../shared/types'; +import { pickOf, PICKS, type KindPick } from '../../shared/format'; import { fmt } from '../../shared/i18n'; import { call } from '../api'; -import { h } from '../dom'; +import { h, ic } from '../dom'; import { EASE_IN, play } from '../motion'; import { repaint, setState, state, type State } from '../state'; import { once, toast } from '../ui/feedback'; import { glass, type Tone } from '../ui/glass'; -import { closeSheet, onClosed, openSheet, type View } from '../ui/sheet'; +import { closeSheet, head, onClosed, openSheet, sub, type View } from '../ui/sheet'; +import { kindOf, kindTiles, lanSwitch } from './device-form'; import { secureFirst } from './secure'; -import { continueSetup } from './setup-view'; +import { continueSetup, openSetup } from './setup-view'; /** A question before something that cannot be undone: the action's icon in its colour, what happens (on the left edge), Cancel and the action. */ function ask(o: { icon: string; tone: Tone; title: string; text: string; action: string; cls: string; run: () => Promise }): View { @@ -41,35 +44,82 @@ function ask(o: { icon: string; tone: Tone; title: string; text: string; action: /** * Set a device up from scratch (a new phone, the app reinstalled, settings the * admin changed): new keys, so what it holds stops working; it shows "Not set - * up yet" until it connects with the new configuration, which the sheet goes on to. + * up yet" until it connects with the new configuration, which the sheet goes on + * to. The sheet asks again what it is and about LAN Bypass, as Add a device does + * (device-form.ts), as they stand now; the name stays. */ export function reconnect(d: Device) { if (secureFirst()) return; - const here = state()?.here === d.id; - openSheet(() => - ask({ - icon: 'refresh', - tone: 'orange', - title: fmt(_('Reconnect %s?'), d.name), - text: here + openSheet(() => vReconnect(d)); +} + +function vReconnect(d: Device): View { + const st = state()!; + const here = st.here === d.id; + // The kinds this router takes, as the four choices; what it is now ringed. + const picks = PICKS.filter((k) => st.kinds.some((x) => pickOf(x) === k)); + let pick: KindPick = picks.includes(pickOf(d.kind)) ? pickOf(d.kind) : picks[0]; + let bypass = d.lan_bypass; + const kinds = kindTiles(picks, (k) => (pick = k)); + kinds.set(pick); + const lan = lanSwitch(bypass, st.server.home ?? [], (on) => (bypass = on)); + const run = async () => { + try { + const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { + action: 'reconnect', + kind: kindOf(pick, d.kind), + lan_bypass: bypass, + }); + setState(r.state); + repaint(); + await continueSetup(r.state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config); + } catch (er) { + toast((er as Error).message, true); + } + }; + const go = h( + 'button', + { type: 'button', class: 'btn warn block', onclick: (ev: Event) => once(ev.currentTarget as HTMLButtonElement, run) }, + ic('refresh'), + h('span', {}, _('Reconnect')), + ); + const title = fmt(_('Reconnect %s'), d.name); + const el = h( + 'div', + { class: 'view' }, + head(title), + sub( + here ? _( 'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.', ) : _('It gets new keys and its current settings stop working. Set it up again with the new ones that open next.'), - action: _('Reconnect'), - cls: 'accent', - run: async () => { - try { - const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'reconnect' }); - setState(r.state); - repaint(); - await continueSetup(r.state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config); - } catch (er) { - toast((er as Error).message, true); - } - }, - }), + ), + kinds.el, + lan, + go, ); + return { el, label: title }; +} + +/** + * LAN Bypass on or off from the ⋯ menu: the keys stay, the device needs its + * updated configuration (its own local network in or out of the tunnel is in + * there), so its set-up opens on it. + */ +export async function toggleBypass(d: Device) { + if (secureFirst()) return; + const on = !d.lan_bypass; + try { + const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'bypass', on }); + setState(r.state); + repaint(); + toast(on ? _('LAN Bypass is on: add the updated connection') : _('LAN Bypass is off: add the updated connection')); + const dev = r.state.person.devices.find((x) => x.id === d.id); + if (dev) await openSetup(dev); + } catch (er) { + toast((er as Error).message, true); + } } export function removeDevice(d: Device) { diff --git a/web/src/portal/flows/device-form.ts b/web/src/portal/flows/device-form.ts new file mode 100644 index 0000000..e88628d --- /dev/null +++ b/web/src/portal/flows/device-form.ts @@ -0,0 +1,129 @@ +// What a device is and how it connects, as Add a device and Reconnect ask it: +// the kinds as four tiles (phones and tablets are one choice, the same apps and +// the same smaller packets) and LAN Bypass, the whole row a switch. + +import type { Kind } from '../../shared/types'; +import { netsLabel, pickLabel, pickOf, type KindPick } from '../../shared/format'; +import { fmt } from '../../shared/i18n'; +import { h } from '../dom'; +import { SMOOTH, play } from '../motion'; +import { glass } from '../ui/glass'; + +export const UA = navigator.userAgent; +export const IPAD = /iPad/.test(UA) || (/Macintosh/.test(UA) && navigator.maxTouchPoints > 1); + +/** Best guess at the kind of device this page is open on (the browser never tells). */ +export function guessKind(): Kind { + if (IPAD || /Tablet/i.test(UA) || (/Android/.test(UA) && !/Mobile/.test(UA))) return 'tablet'; + if (/Android|iPhone|Mobile/i.test(UA)) return 'phone'; + return 'computer'; +} + +/** The kind a pick keeps: Mobile is a tablet when this page is open on one, or when the device was one already (`was`). */ +export function kindOf(p: KindPick, was?: Kind): Kind { + if (was && pickOf(was) === p) return was; + return p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone'; +} + +/** + * A line in a block opens or folds away: height, opacity and blur on SMOOTH, as the set-up steps fold, from + * where it is on screen (flicking the switch never snaps). The block's 1 px gap goes with it. + */ +function foldLine(el: HTMLElement, open: boolean) { + const cs = getComputedStyle(el); + const from = el.hidden + ? { h: 0, o: 0, b: 4, m: -1 } + : { + h: el.getBoundingClientRect().height, + o: +cs.opacity, + b: +(cs.filter.match(/blur\(([\d.]+)px\)/)?.[1] ?? 0), + m: parseFloat(cs.marginTop) || 0, + }; + el.getAnimations().forEach((a) => a.cancel()); + el.hidden = false; + el.style.overflow = 'hidden'; + const to = open ? { h: el.scrollHeight, o: 1, b: 0, m: 0 } : { h: 0, o: 0, b: 4, m: -1 }; + const frame = (v: typeof from) => ({ height: `${v.h}px`, opacity: v.o, filter: v.b ? `blur(${v.b}px)` : 'none', marginTop: `${v.m}px` }); + const a = play(el, [frame(from), frame(to)], { duration: SMOOTH.duration, easing: SMOOTH.easing, fill: 'forwards' }); + a.onfinish = () => { + el.hidden = !open; + el.style.overflow = ''; + a.cancel(); + }; +} + +export interface KindTiles { + el: HTMLElement; + /** Ring this one (the ring does not travel between tiles: the picked tile rings itself where it stands). */ + set(k: KindPick): void; +} + +/** The kinds a router takes, as tiles; `onPick` on a tap, after the ring moved. */ +export function kindTiles(picks: KindPick[], onPick: (k: KindPick) => void): KindTiles { + const el = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': _('What is it?') }); + el.style.setProperty('--n', String(picks.length)); + const set = (k: KindPick) => + tiles.forEach((t, i) => { + const on = picks[i] === k; + t.classList.toggle('on', on); + t.setAttribute('aria-checked', String(on)); + }); + const tiles = picks.map((k) => { + const t = h( + 'button', + { + type: 'button', + class: 'kind', + role: 'radio', + 'aria-label': pickLabel(k), + onclick: () => { + set(k); + onPick(k); + }, + }, + h('span', { class: 'kind-tile' }, glass(k, 'blue')), + h('span', { class: 'kind-lbl' }, pickLabel(k)), + ); + el.appendChild(t); + return t; + }); + return { el, set }; +} + +/** + * LAN Bypass, the whole row the switch, built as it is (`on`) before it is on + * the page: nothing slides. With home access the home networks still go into + * the tunnel: a local network on the same addresses is out of reach, and the + * row says so while it is on. + */ +export function lanSwitch(on: boolean, home: string[], onChange: (on: boolean) => void): HTMLElement { + const except = home.length + ? h('span', { class: 'sw-sub sw-note', hidden: !on }, fmt(_('Except %s: those addresses lead to the home network.'), netsLabel(home))) + : null; + const row = h( + 'button', + { + type: 'button', + class: on ? 'swrow on' : 'swrow', + role: 'switch', + 'aria-checked': String(on), + onclick: () => { + on = !on; + row.classList.toggle('on', on); + row.setAttribute('aria-checked', String(on)); + if (except) foldLine(except, on); + onChange(on); + }, + }, + glass('lan', 'blue'), + h( + 'span', + { class: 'sw-t' }, + h('b', {}, _('LAN Bypass')), + h('span', { class: 'sw-sub' }, _('Your local network stays reachable while connected.')), + except, + ), + h('span', { class: 'sw', 'aria-hidden': 'true' }), + ); + return row; +} diff --git a/web/src/portal/flows/setup-parts.ts b/web/src/portal/flows/setup-parts.ts index d708062..5a8e29e 100644 --- a/web/src/portal/flows/setup-parts.ts +++ b/web/src/portal/flows/setup-parts.ts @@ -10,6 +10,7 @@ import { h, ic, type Kid } from '../dom'; import { EASE_IN, EASE_OUT, POP, SMOOTH, play } from '../motion'; import { APP_NAME, + appName, importPath, importSteps, keyFileName, @@ -18,6 +19,7 @@ import { routerStore, scanPath, vpnContinue, + v2rTunnelMode, storeFor, type AppId, type Platform, @@ -29,14 +31,14 @@ import { glass } from '../ui/glass'; import { menuLine, morphText, setText } from '../ui/morph'; import { hint } from '../ui/sheet'; -export const APP_ICON: Record = { vpn: 'amnezia', awg: 'amneziawg', wg: 'wireguard' }; +export const APP_ICON: Record = { vpn: 'amnezia', awg: 'amneziawg', v2r: 'v2raytun', wg: 'wireguard' }; /** The app a device was set up with last time, so the sheet reopens on it. */ const memo = (d: Device) => `dl.app.${d.id}`; export function recallApp(d: Device): AppId | null { try { const v = localStorage.getItem(memo(d)); - return v === 'vpn' || v === 'awg' || v === 'wg' ? v : null; + return v === 'vpn' || v === 'awg' || v === 'v2r' || v === 'wg' ? v : null; } catch { return null; } @@ -49,11 +51,17 @@ export function rememberApp(d: Device, app: AppId) { } } -/** What the steps work with: the device, its configuration, the key, and the choices made. */ +/** What the steps work with: the device, its configuration, the key, the link, and the choices made. */ export interface SetupCtx { d: Device; cfg: ClientConfig; key: string; + /** The connection as V2RayTun's awg:// link (shared/awglink.ts). */ + link: string; + /** The link names the server by an IP in place of its name (false: the address is an IP already, or did not resolve). */ + byIp: boolean; + /** The disguise is off and this is no router: AmneziaWG's choice is WireGuard's too (setup.ts appName). */ + wgToo: boolean; /** The platform this page is open on. */ pf: Platform; /** "the phone": the device in a sentence. */ @@ -83,13 +91,26 @@ function badge( return h('a', { class: cls, href: st.href, target: app ? null : '_blank', rel: 'noopener noreferrer' }, inner); } -/** Where the app comes from: the store (and, on Android, the APK beside it), or a line to go and get it. */ -export function storeBlock(app: AppId, os: Platform, router: boolean): Kid[] { +/** + * Where the app comes from: the store (and, on Android, the APK beside it), or + * a line to go and get it. With the disguise off (`wgToo`), a line under + * AmneziaWG's says WireGuard takes the connection too, its name a link to its + * store here. + */ +export function storeBlock(app: AppId, os: Platform, router: boolean, wgToo = false): Kid[] { const st: Store | null = router ? routerStore(app) : storeFor(app, os); - if (!st) return [hint(fmt(_('Get %s on the %s and come back here.'), APP_NAME[app], platformLabel(os)))]; + const wg = wgToo && app === 'awg' && !router ? wgLine(os) : null; + if (!st) return [hint(fmt(_('Get %s on the %s and come back here.'), appName(app, wgToo && !router), platformLabel(os)))]; // Android: the store can fail (no Google Play, or it hides the app), so the APK sits beside it. - if (st.alt) return [h('div', { class: 'badges2' }, badge(st), badge(st.alt)), hint(st.alt.why)]; - return [badge(st)]; + if (st.alt) return [h('div', { class: 'badges2' }, badge(st), badge(st.alt)), hint(st.alt.why), wg]; + return [badge(st), wg]; +} + +/** "WireGuard works too, if it is already there": the name links to its store on this platform. */ +function wgLine(os: Platform): HTMLElement { + const st = storeFor('wg', os); + const name = st ? h('a', { href: st.href, target: '_blank', rel: 'noopener noreferrer' }, APP_NAME.wg) : h('b', {}, APP_NAME.wg); + return hint(...fill(_('%s works too, if it is already there: the disguise is off.'), name)); } const howto = (steps: [string, string][]) => @@ -101,10 +122,42 @@ const howto = (steps: [string, string][]) => const linkBtn = (label: string, run: (ev: Event) => void) => h('button', { type: 'button', onclick: run }, label); -/** Step 2: a link for AmneziaVPN, the file for the others, in the words of where they go. */ +/** V2RayTun has the server by its IP, not its name: once the router's address changes, the connection goes stale. The IP itself stays off the page. */ +const byIpWords = () => + _('V2RayTun reaches the server by its IP address, not its hostname: if the address changes, add the connection again.'); + +/** V2RayTun takes the connection as a link from the clipboard: copied, then "+ › Import config from Clipboard". */ +function v2rKids(c: SetupCtx): Kid[] { + // The words of the app on this device when the page is open on it (Windows has its own); else Android's. + const os = c.same() ? c.pf : 'unknown'; + const path = importPath('v2r', os); + const win = os === 'windows'; + return [ + badge( + { + top: _('The connection as one link'), + main: _('Copy the link'), + mark: 'copy', + onclick: (ev) => copy(c.link, _('Link copied'), ev.currentTarget), + }, + true, + ), + howto([ + [fmt(_('Open %s', 'step'), APP_NAME.v2r), ''], + [path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')], + // On Windows AmneziaWG runs in its Tunnel mode (the Mode switch on its main screen), which needs administrator rights. + win ? [fmt(_('Switch to %s mode and connect', 'step'), v2rTunnelMode()), ''] : [_('Connect', 'step'), ''], + ]), + win ? hint(_('V2RayTun needs administrator rights for this mode: it offers to restart with them.')) : null, + c.byIp ? hint(byIpWords()) : null, + ]; +} + +/** Step 2: a link for AmneziaVPN and V2RayTun, the file for the others, in the words of where they go. */ export function connectKids(c: SetupCtx): Kid[] { const app = c.app(); - const name = APP_NAME[app]; + const name = appName(app, c.wgToo); + if (app === 'v2r') return v2rKids(c); const hereHandheld = c.pf === 'ios' || c.pf === 'android'; // On the phone being set up, a link opens AmneziaVPN only on Android; an // iPhone takes the key as a .vpn file from the share sheet. @@ -141,7 +194,12 @@ export function connectKids(c: SetupCtx): Kid[] { share ? badge( { - top: c.same() ? fmt(_('Straight into %s'), name) : fmt(_('Send it to the %s'), c.there), + // Two apps' names do not fit the badge's small line: "the app" then. + top: c.same() + ? c.wgToo && app === 'awg' + ? _('Straight into the app') + : fmt(_('Straight into %s'), name) + : fmt(_('Send it to the %s'), c.there), main: _('Share the file'), mark: 'share', onclick: () => void share(), @@ -158,15 +216,29 @@ export function connectKids(c: SetupCtx): Kid[] { true, ), // In the words of the app where the file goes: the phone in hand, or the computer's system. - howto(importSteps(app, c.pf, c.cfg.filename, !!share && c.same())), + howto(importSteps(app, c.pf, c.cfg.filename, !!share && c.same(), c.wgToo)), ]; } -/** A computer set up from elsewhere: the connection to send there, as the key or the file. */ +/** A computer (or a TV, a box) set up from elsewhere: the connection to send there, as the key, the link or the file. */ export function sendKids(c: SetupCtx): Kid[] { const app = c.app(); const btn = (icon: string, label: string, run: (ev: Event) => void) => h('button', { type: 'button', class: 'btn soft sm', onclick: run }, ic(icon), h('span', { class: 'lbl' }, label)); + if (app === 'v2r') + return [ + h( + 'p', + { class: 'desc' }, + fmt(_('Send it to the %s in a message or a note, then in V2RayTun: %s.'), c.there, importPath('v2r').replace(/ → /g, ' › ')), + ), + h( + 'div', + { class: 'btnrow2' }, + btn('copy', _('Copy the link'), (ev) => copy(c.link, _('Link copied'), ev.currentTarget)), + ), + c.byIp ? hint(byIpWords()) : null, + ]; if (app === 'vpn') { const file = keyFileName(c.cfg.filename); const share = !!shareFile(file, c.key); @@ -189,7 +261,7 @@ export function sendKids(c: SetupCtx): Kid[] { h( 'p', { class: 'desc' }, - ...fill(_('Send it to the %s, then import %s in %s.'), c.there, h('b', {}, c.cfg.filename), APP_NAME[app]), + ...fill(_('Send it to the %s, then import %s in %s.'), c.there, h('b', {}, c.cfg.filename), appName(app, c.wgToo)), ), h( 'div', @@ -315,15 +387,26 @@ export interface ScanLine { set(app: AppId): void; } -/** "In AmneziaWG: + › Create from QR code", with both phone systems' wording where they differ. */ -export function scanLine(app: AppId): ScanLine { - const name = h('span', { class: 'osm-p' }, APP_NAME[app]); +/** + * "In AmneziaWG: + › Create from QR code", with both phone systems' wording + * where they differ ("In AmneziaWG or WireGuard:" with the disguise off, + * `wgToo`: the same code and menus). For V2RayTun, where the link names the + * server by its IP (`byIp`), a line under it says what that means. + */ +export function scanLine(app: AppId, byIp = false, wgToo = false): ScanLine { + const name = h('span', { class: 'osm-p' }, appName(app, wgToo)); const path = menuLine(scanPath(app, 'ios'), scanPath(app, 'android')); + const note = byIp ? hint(byIpWords()) : null; + const shows = (a: AppId) => { + if (note) note.hidden = a !== 'v2r'; + }; + shows(app); return { - el: h('span', { class: 'scanline' }, h('span', {}, ...fill(_('In %s:'), name)), path.el), + el: h('div', { class: 'scanwrap' }, h('span', { class: 'scanline' }, h('span', {}, ...fill(_('In %s:'), name)), path.el), note), set(a) { - morphText(name, APP_NAME[a], undefined, { whole: true }); + morphText(name, appName(a, wgToo), undefined, { whole: true }); path.set(scanPath(a, 'ios'), scanPath(a, 'android')); + shows(a); }, }; } @@ -342,7 +425,7 @@ export interface ConnPill { * still fades out), each move from where it stands. Copied: a check, and the * tooltip says so. */ -export function connPill(get: () => { text: string; msg: string; file: string; app: string }): ConnPill { +export function connPill(get: () => { text: string; msg: string; file: string; app: string; link?: boolean }): ConnPill { const tt = h('span', { class: 'tt' }); const tm = h('span', { class: 'tt-m' }); const tip = h('span', { class: 'hp-tip', 'aria-hidden': 'true' }, tt, tm); @@ -473,9 +556,9 @@ export function connPill(get: () => { text: string; msg: string; file: string; a return { el, sync() { - const app = get().app; - dl.setAttribute('aria-label', fmt(_('Download %s config'), app)); - cp.setAttribute('aria-label', fmt(_('Copy %s config'), app)); + const { app, link } = get(); + dl.setAttribute('aria-label', link ? fmt(_('Download %s link'), app) : fmt(_('Download %s config'), app)); + cp.setAttribute('aria-label', link ? fmt(_('Copy %s link'), app) : fmt(_('Copy %s config'), app)); }, }; } diff --git a/web/src/portal/flows/setup-view.ts b/web/src/portal/flows/setup-view.ts index 93b5137..dbce0e0 100644 --- a/web/src/portal/flows/setup-view.ts +++ b/web/src/portal/flows/setup-view.ts @@ -11,11 +11,12 @@ import type { ClientConfig, Device } from '../../shared/types'; import { fmt } from '../../shared/i18n'; +import { awgLink } from '../../shared/awglink'; import { vpnKey, vpnQrText } from '../../shared/vpnkey'; import { ApiError, call } from '../api'; import { h, put } from '../dom'; import { SMOOTH, play } from '../motion'; -import { APP_NAME, appsFor, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup'; +import { APP_NAME, appsFor, appsOn, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup'; import { pageUrl, platform, preset, repaint } from '../state'; import { accordion, regrow } from '../ui/accordion'; import { codeRow, linkRow, type CodeRow } from '../ui/codes'; @@ -124,11 +125,22 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie const layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away'; const there = deviceNoun(d.kind); const thereOn = deviceNoun(d.kind, true); - // A router takes AmneziaWG (or WireGuard), never AmneziaVPN. - const choices = apps.filter((a) => !router || a.id !== 'vpn'); - let app: AppId = recallApp(d) ?? (router ? 'awg' : 'vpn'); + // A router takes AmneziaWG or WireGuard, never AmneziaVPN; elsewhere WireGuard is AmneziaWG's choice; V2RayTun + // is for Android and Windows (setup.ts appsOn). + const choices = appsOn(d.kind, apps, same ? pf : null); + // AmneziaWG first, as the picker lists it; a device set up before opens on the app it was set up with. + let app: AppId = recallApp(d) ?? 'awg'; if (!choices.some((a) => a.id === app)) app = choices[0].id; - const c: SetupCtx = { d, cfg, key, pf, there, app: () => app, same: () => same }; + // V2RayTun takes the server by its IP (shared/awglink.ts): only when the address is a name do the words say what that means. + const ip = cfg.amnezia.host_ip; + // Its Windows app resolves the name itself (amneziawg-windows, before the tunnel starts): there the link keeps + // the name, so a new address at home does not break it, and nothing needs saying. + const named = same && pf === 'windows'; + const link = awgLink(cfg.conf, cfg.server, named ? null : ip); + const byIp = !named && !!ip && ip !== cfg.amnezia.host.replace(/^\[(.*)\]$/, '$1'); + // The disguise off: WireGuard takes AmneziaWG's file and code (one choice, both names; a router keeps both packages). + const wgToo = preset() === 'off' && !router; + const c: SetupCtx = { d, cfg, key, link, byIp, wgToo, pf, there, app: () => app, same: () => same }; // The pickers and the boxes a pick changes live across repaints: a pick only // refills what it changes, so the pills glide and nothing else in the sheet moves. @@ -178,9 +190,13 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie const pill = layout === 'away' ? connPill(() => ({ + // V2RayTun: its link, copied or as a .txt. Its "Import config from locally" takes a file line by line, + // each line a link: a .conf does not import that way (and its server's name would not connect either). ...(app === 'vpn' ? { text: key, msg: _('Key copied'), file: keyFileName(cfg.filename) } - : { text: cfg.conf, msg: _('Configuration copied'), file: cfg.filename }), + : app === 'v2r' + ? { text: link, msg: _('Link copied'), file: cfg.filename.replace(/\.conf$/i, '.txt'), link: true } + : { text: cfg.conf, msg: _('Configuration copied'), file: cfg.filename }), app: APP_NAME[app], })) : null; @@ -188,13 +204,14 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie /** Everything a pick changes, refilled in place. */ function fill() { morphText(title1, router ? fmt(_('Get %s on the router'), APP_NAME[app]) : fmt(_('Get %s'), APP_NAME[app]), undefined, { whole: true }); - morphInto(getBox, storeBlock(app, pf, router)); + morphInto(getBox, storeBlock(app, pf, router, wgToo)); // The router's file is the same for either app: it stays as it is (a folded configuration stays folded). if (!router) morphInto(addBox, connectKids(c)); else if (!addBox.firstChild) put(addBox, filePane(cfg)); // The connection as a code: only a phone or a tablet set up from here shows one. if (layout === 'away') { - const text = app === 'vpn' ? vpnQrText(key) : cfg.conf; + // V2RayTun scans its link: a .conf would come in named by the clock, the link carries the server's name. + const text = app === 'vpn' ? vpnQrText(key) : app === 'v2r' ? link : cfg.conf; // Another app: its words morph in place, the code changes only when it holds something else (codes.ts). if (code && scan && code.el.isConnected) { if (codeApp !== app) { @@ -202,7 +219,7 @@ function setupView(d: Device, cfg: ClientConfig, key: string, here = false): Vie scan.set(app); } } else { - scan = scanLine(app); + scan = scanLine(app, byIp, wgToo); code = codeRow(text, [scan.el], tooLong); codeBox.replaceChildren(code.el); } diff --git a/web/src/portal/i18n/portal.pot b/web/src/portal/i18n/portal.pot index 9a3fc73..584a8d0 100644 --- a/web/src/portal/i18n/portal.pot +++ b/web/src/portal/i18n/portal.pot @@ -157,10 +157,18 @@ msgstr[1] "" msgid "%s options" msgstr "" +#: web/src/portal/setup.ts +msgid "%s or %s" +msgstr "" + #: web/src/shared/format.ts msgid "%s this month" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "%s works too, if it is already there: the disguise is off." +msgstr "" + #: web/src/portal/page/notices.ts msgid "%s your time" msgstr "" @@ -299,6 +307,10 @@ msgstr "" msgid "Can’t finish connecting" msgstr "" +#: web/src/portal/setup.ts +msgid "Channel on" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Circle %s: server %s does not exist." msgstr "" @@ -328,6 +340,11 @@ msgstr "" msgid "Connect" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgctxt "step" +msgid "Connect" +msgstr "" + #: web/src/portal/page/devices.ts msgid "Connected" msgstr "" @@ -374,6 +391,10 @@ msgstr "" msgid "Copy %s config" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "Copy %s link" +msgstr "" + #: web/src/portal/page/devices.ts msgid "Copy IP address" msgstr "" @@ -404,6 +425,7 @@ msgid "Copy the key" msgstr "" #: web/src/portal/flows/page-code.ts +#: web/src/portal/flows/setup-parts.ts #: web/src/portal/ui/codes.ts msgid "Copy the link" msgstr "" @@ -539,6 +561,10 @@ msgstr "" msgid "Download %s config" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "Download %s link" +msgstr "" + #: web/src/portal/setup.ts msgid "Download for Linux" msgstr "" @@ -587,7 +613,7 @@ msgstr "" msgid "Enter a device name: up to %d letters, digits, spaces and - _ ." msgstr "" -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts msgid "Except %s: those addresses lead to the home network." msgstr "" @@ -673,6 +699,21 @@ msgctxt "WireGuard app" msgid "Import Tunnel(s) from File…" msgstr "" +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Import config from Clipboard" +msgstr "" + +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Import config from QRcode" +msgstr "" + +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Import from clipboard" +msgstr "" + #: web/src/portal/setup.ts msgctxt "WireGuard app" msgid "Import from file or archive" @@ -775,10 +816,19 @@ msgstr "" msgid "Key generation failed." msgstr "" -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts +#: web/src/portal/page/devices.ts msgid "LAN Bypass" msgstr "" +#: web/src/portal/flows/device-actions.ts +msgid "LAN Bypass is off: add the updated connection" +msgstr "" + +#: web/src/portal/flows/device-actions.ts +msgid "LAN Bypass is on: add the updated connection" +msgstr "" + #: web/src/portal/page/frame.ts msgid "Language" msgstr "" @@ -792,6 +842,8 @@ msgid "Last connected %s" msgstr "" #: web/src/portal/flows/page-code.ts +#: web/src/portal/flows/setup-parts.ts +#: web/src/portal/flows/setup-view.ts #: web/src/portal/ui/codes.ts msgid "Link copied" msgstr "" @@ -892,10 +944,18 @@ msgstr "" msgid "OR" msgstr "" +#: web/src/portal/page/devices.ts +msgid "Off" +msgstr "" + #: web/src/portal/setup.ts msgid "Official release on GitHub" msgstr "" +#: web/src/portal/page/devices.ts +msgid "On" +msgstr "" + #: web/src/portal/page/notices.ts msgid "On %s." msgstr "" @@ -979,6 +1039,10 @@ msgstr "" msgid "OpenWrt packages + kmod" msgstr "" +#: web/src/portal/setup.ts +msgid "Or, with wireguard-tools," +msgstr "" + #: web/src/shared/format.ts msgid "Other" msgstr "" @@ -1061,14 +1125,11 @@ msgstr "" msgid "Reconnect" msgstr "" +#: web/src/portal/flows/device-actions.ts #: web/src/portal/page/devices.ts msgid "Reconnect %s" msgstr "" -#: web/src/portal/flows/device-actions.ts -msgid "Reconnect %s?" -msgstr "" - #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "RejectAfterTime must be at most 180 seconds." msgstr "" @@ -1131,6 +1192,10 @@ msgstr "" msgid "Send it to the %s in a message or a note, then in AmneziaVPN: %s." msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "Send it to the %s in a message or a note, then in V2RayTun: %s." +msgstr "" + #: web/src/portal/flows/setup-parts.ts msgid "Send it to the %s, then import %s in %s." msgstr "" @@ -1189,6 +1254,10 @@ msgstr "" msgid "Straight into %s" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "Straight into the app" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Subnet must look like 10.77.0.0/24." msgstr "" @@ -1197,6 +1266,11 @@ msgstr "" msgid "Subnet overlaps %s." msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgctxt "step" +msgid "Switch to %s mode and connect" +msgstr "" + #: web/src/shared/format.ts msgid "TB" msgstr "" @@ -1241,6 +1315,10 @@ msgstr "" msgid "The connection as one key" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "The connection as one link" +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "The header protection key is not a key." msgstr "" @@ -1315,6 +1393,11 @@ msgstr "" msgid "Too many changes in a short time. Try again in a few minutes." msgstr "" +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Tunnel" +msgstr "" + #: web/src/portal/flows/setup-view.ts msgid "Two steps, about a minute" msgstr "" @@ -1339,6 +1422,10 @@ msgstr "" msgid "Unknown circle." msgstr "" +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Unknown device type." +msgstr "" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc msgid "Unknown device." @@ -1368,6 +1455,18 @@ msgstr "" msgid "Uploaded" msgstr "" +#: web/src/portal/flows/setup-parts.ts +msgid "V2RayTun needs administrator rights for this mode: it offers to restart with them." +msgstr "" + +#: web/src/portal/flows/setup-parts.ts +msgid "V2RayTun reaches the server by its IP address, not its hostname: if the address changes, add the connection again." +msgstr "" + +#: web/src/portal/setup.ts +msgid "V2RayTun’s own channel: news and updates of the app." +msgstr "" + #: web/src/portal/flows/wait.ts msgid "Waiting for the connection" msgstr "" @@ -1376,7 +1475,7 @@ msgstr "" msgid "Warning must be 0-60 days." msgstr "" -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts msgid "What is it?" msgstr "" @@ -1440,7 +1539,7 @@ msgstr "" msgid "Your devices can’t connect until it’s resumed." msgstr "" -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts msgid "Your local network stays reachable while connected." msgstr "" diff --git a/web/src/portal/i18n/ru.po b/web/src/portal/i18n/ru.po index 32259a6..d633abd 100644 --- a/web/src/portal/i18n/ru.po +++ b/web/src/portal/i18n/ru.po @@ -162,10 +162,18 @@ msgstr[2] "Свободно %s из %s мест" msgid "%s options" msgstr "Действия с устройством %s" +#: web/src/portal/setup.ts +msgid "%s or %s" +msgstr "%s или %s" + #: web/src/shared/format.ts msgid "%s this month" msgstr "%s в этом месяце" +#: web/src/portal/flows/setup-parts.ts +msgid "%s works too, if it is already there: the disguise is off." +msgstr "Подойдёт и %s, если он уже стоит: маскировка выключена." + #: web/src/portal/page/notices.ts msgid "%s your time" msgstr "%s по вашему времени" @@ -304,6 +312,10 @@ msgstr "Отмена" msgid "Can’t finish connecting" msgstr "Не удаётся подключиться" +#: web/src/portal/setup.ts +msgid "Channel on" +msgstr "Канал в" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Circle %s: server %s does not exist." msgstr "Круг %s: сервера %s нет." @@ -333,6 +345,11 @@ msgstr "Подтвердите импорт и подключитесь" msgid "Connect" msgstr "Подключить" +#: web/src/portal/flows/setup-parts.ts +msgctxt "step" +msgid "Connect" +msgstr "Подключитесь" + #: web/src/portal/page/devices.ts msgid "Connected" msgstr "Подключено" @@ -379,6 +396,10 @@ msgstr "Скопировать %s" msgid "Copy %s config" msgstr "Скопировать конфигурацию %s" +#: web/src/portal/flows/setup-parts.ts +msgid "Copy %s link" +msgstr "Скопировать ссылку %s" + #: web/src/portal/page/devices.ts msgid "Copy IP address" msgstr "Скопировать IP-адрес" @@ -409,6 +430,7 @@ msgid "Copy the key" msgstr "Скопируйте ключ" #: web/src/portal/flows/page-code.ts +#: web/src/portal/flows/setup-parts.ts #: web/src/portal/ui/codes.ts msgid "Copy the link" msgstr "Скопировать ссылку" @@ -544,6 +566,10 @@ msgstr "Скачать" msgid "Download %s config" msgstr "Скачать конфигурацию %s" +#: web/src/portal/flows/setup-parts.ts +msgid "Download %s link" +msgstr "Скачать ссылку %s" + #: web/src/portal/setup.ts msgid "Download for Linux" msgstr "Скачать для Linux" @@ -592,7 +618,7 @@ msgstr "Закончится %s" msgid "Enter a device name: up to %d letters, digits, spaces and - _ ." msgstr "Введите название устройства: до %d букв, цифр, пробелов и - _ ." -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts msgid "Except %s: those addresses lead to the home network." msgstr "Кроме %s: эти адреса ведут в домашнюю сеть." @@ -678,6 +704,21 @@ msgctxt "WireGuard app" msgid "Import Tunnel(s) from File…" msgstr "Импорт туннелей из файла…" +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Import config from Clipboard" +msgstr "Импорт из буфера обмена" + +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Import config from QRcode" +msgstr "Импорт из QR-кода" + +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Import from clipboard" +msgstr "Импорт из буфера обмена" + #: web/src/portal/setup.ts msgctxt "WireGuard app" msgid "Import from file or archive" @@ -780,10 +821,19 @@ msgstr "Не удалось создать ключ (нет случайных msgid "Key generation failed." msgstr "Не удалось создать ключ." -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts +#: web/src/portal/page/devices.ts msgid "LAN Bypass" msgstr "Обход локальной сети" +#: web/src/portal/flows/device-actions.ts +msgid "LAN Bypass is off: add the updated connection" +msgstr "Обход локальной сети выключен: добавьте обновлённое подключение" + +#: web/src/portal/flows/device-actions.ts +msgid "LAN Bypass is on: add the updated connection" +msgstr "Обход локальной сети включён: добавьте обновлённое подключение" + #: web/src/portal/page/frame.ts msgid "Language" msgstr "Язык" @@ -797,6 +847,8 @@ msgid "Last connected %s" msgstr "В сети %s" #: web/src/portal/flows/page-code.ts +#: web/src/portal/flows/setup-parts.ts +#: web/src/portal/flows/setup-view.ts #: web/src/portal/ui/codes.ts msgid "Link copied" msgstr "Ссылка скопирована" @@ -897,10 +949,18 @@ msgstr "Сейчас %s" msgid "OR" msgstr "ИЛИ" +#: web/src/portal/page/devices.ts +msgid "Off" +msgstr "Выкл." + #: web/src/portal/setup.ts msgid "Official release on GitHub" msgstr "Официальная версия на GitHub" +#: web/src/portal/page/devices.ts +msgid "On" +msgstr "Вкл." + #: web/src/portal/page/notices.ts msgid "On %s." msgstr "Дата окончания - %s." @@ -984,6 +1044,10 @@ msgstr "Пакеты OpenWrt" msgid "OpenWrt packages + kmod" msgstr "Пакеты OpenWrt + kmod" +#: web/src/portal/setup.ts +msgid "Or, with wireguard-tools," +msgstr "Или через wireguard-tools:" + #: web/src/shared/format.ts msgid "Other" msgstr "Другое" @@ -1066,14 +1130,11 @@ msgstr "QR-код" msgid "Reconnect" msgstr "Переподключить" +#: web/src/portal/flows/device-actions.ts #: web/src/portal/page/devices.ts msgid "Reconnect %s" msgstr "Переподключить %s" -#: web/src/portal/flows/device-actions.ts -msgid "Reconnect %s?" -msgstr "Переподключить «%s»?" - #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "RejectAfterTime must be at most 180 seconds." msgstr "RejectAfterTime: не больше 180 секунд." @@ -1136,6 +1197,10 @@ msgstr "Отправить на %s" msgid "Send it to the %s in a message or a note, then in AmneziaVPN: %s." msgstr "Отправьте его на %s в сообщении или заметке, затем в AmneziaVPN: %s." +#: web/src/portal/flows/setup-parts.ts +msgid "Send it to the %s in a message or a note, then in V2RayTun: %s." +msgstr "Отправьте её на %s в сообщении или заметке, затем в V2RayTun: %s." + #: web/src/portal/flows/setup-parts.ts msgid "Send it to the %s, then import %s in %s." msgstr "Отправьте его на %s, затем импортируйте %s в %s." @@ -1194,6 +1259,10 @@ msgstr "Показать ключ" msgid "Straight into %s" msgstr "Сразу в %s" +#: web/src/portal/flows/setup-parts.ts +msgid "Straight into the app" +msgstr "Сразу в приложение" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc msgid "Subnet must look like 10.77.0.0/24." msgstr "Подсеть указывается так: 10.77.0.0/24." @@ -1202,6 +1271,11 @@ msgstr "Подсеть указывается так: 10.77.0.0/24." msgid "Subnet overlaps %s." msgstr "Подсеть пересекается с %s." +#: web/src/portal/flows/setup-parts.ts +msgctxt "step" +msgid "Switch to %s mode and connect" +msgstr "Включите режим «%s» и подключитесь" + #: web/src/shared/format.ts msgid "TB" msgstr "ТБ" @@ -1246,6 +1320,10 @@ msgstr "Подключение" msgid "The connection as one key" msgstr "Подключение одним ключом" +#: web/src/portal/flows/setup-parts.ts +msgid "The connection as one link" +msgstr "Подключение одной ссылкой" + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc msgid "The header protection key is not a key." msgstr "Ключ защиты заголовков некорректен." @@ -1320,6 +1398,11 @@ msgstr "Сегодня" msgid "Too many changes in a short time. Try again in a few minutes." msgstr "Слишком много изменений за короткое время. Попробуйте ещё раз через несколько минут." +#: web/src/portal/setup.ts +msgctxt "V2RayTun app" +msgid "Tunnel" +msgstr "Туннель" + #: web/src/portal/flows/setup-view.ts msgid "Two steps, about a minute" msgstr "Два шага, около минуты" @@ -1344,6 +1427,10 @@ msgstr "Неизвестное действие." msgid "Unknown circle." msgstr "Неизвестный круг." +#: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc +msgid "Unknown device type." +msgstr "Неизвестный тип устройства." + #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc #: package/luci-app-dawnline/root/usr/share/ucode/dawnline/devices.uc msgid "Unknown device." @@ -1373,6 +1460,18 @@ msgstr "Не больше %s символов." msgid "Uploaded" msgstr "Отправлено" +#: web/src/portal/flows/setup-parts.ts +msgid "V2RayTun needs administrator rights for this mode: it offers to restart with them." +msgstr "Для этого режима V2RayTun нужны права администратора: приложение предложит перезапуститься с ними." + +#: web/src/portal/flows/setup-parts.ts +msgid "V2RayTun reaches the server by its IP address, not its hostname: if the address changes, add the connection again." +msgstr "V2RayTun подключается к серверу по IP-адресу, а не по доменному имени: если адрес сменится, добавьте подключение заново." + +#: web/src/portal/setup.ts +msgid "V2RayTun’s own channel: news and updates of the app." +msgstr "Канал самого V2RayTun: новости и обновления приложения." + #: web/src/portal/flows/wait.ts msgid "Waiting for the connection" msgstr "Ждём подключения" @@ -1381,7 +1480,7 @@ msgstr "Ждём подключения" msgid "Warning must be 0-60 days." msgstr "Предупреждать можно за 0–60 дней." -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts msgid "What is it?" msgstr "Что это за устройство?" @@ -1447,7 +1546,7 @@ msgstr "Ваши устройства не подключатся, пока до msgid "Your devices can’t connect until it’s resumed." msgstr "Ваши устройства не подключатся, пока доступ не возобновят." -#: web/src/portal/flows/add.ts +#: web/src/portal/flows/device-form.ts msgid "Your local network stays reachable while connected." msgstr "Ваша локальная сеть остаётся доступной при подключении." diff --git a/web/src/portal/page/access.ts b/web/src/portal/page/access.ts index 33b00a7..c85dbb3 100644 --- a/web/src/portal/page/access.ts +++ b/web/src/portal/page/access.ts @@ -123,16 +123,26 @@ function month(p: Person, used: number, pct: number): HTMLElement { say(-1); const chart = bars(series, 'bars-month', 64, days - day); readBars(chart, _('Your data this month'), say); - // "Today" under its bar; the month's ends step aside when it comes close. + // "Today" under its bar, kept inside the axis; the month's ends step aside where it comes within 6 px of + // either of them, measured (the words' widths follow the language and the axis the screen). Until the first + // measure, which comes before the first paint: under its bar, and the ends by the day. const td = h('span', { class: 'td' }, _('Today')); td.style.left = pc(day - 0.5, days); - const axis = h( - 'div', - { class: 'month-axis' }, - h('span', { class: day <= 4 ? 'hide' : '' }, short(1)), - td, - h('span', { class: day >= days - 3 ? 'hide' : '' }, short(days)), - ); + const first = h('span', { class: day <= 4 ? 'hide' : '' }, short(1)); + const last = h('span', { class: day >= days - 3 ? 'hide' : '' }, short(days)); + const axis = h('div', { class: 'month-axis' }, first, td, last); + const fit = () => { + const room = axis.clientWidth; + const w = td.offsetWidth; + if (!room || !w) return; + const x = Math.min(Math.max(((day - 0.5) / days) * room, w / 2), room - w / 2); + td.style.left = `${x}px`; + first.classList.toggle('hide', x - w / 2 < first.offsetWidth + 6); + last.classList.toggle('hide', x + w / 2 > room - last.offsetWidth - 6); + }; + // The axis on another width (a phone turned, the card's columns), or the words on theirs (the font arrived). + const ro = new ResizeObserver(fit); + for (const x of [axis, td, first, last]) ro.observe(x); // With a limit not yet reached: the pace lately (the devices' last 7 days, so the month's first days have one // too) and when the limit fills at it, orange within a week. const pace = paceOf( diff --git a/web/src/portal/page/devices.ts b/web/src/portal/page/devices.ts index ffc2a79..039afc0 100644 --- a/web/src/portal/page/devices.ts +++ b/web/src/portal/page/devices.ts @@ -17,7 +17,7 @@ import { glass } from '../ui/glass'; import { openMenu, type MenuItem } from '../ui/menu'; import { appear, fadeAway, look, morphChanged, morphText, setText, textsOf, type Look } from '../ui/morph'; import { startAdd } from '../flows/add'; -import { reconnect, removeDevice } from '../flows/device-actions'; +import { reconnect, removeDevice, toggleBypass } from '../flows/device-actions'; import { renameOnCard } from '../flows/rename'; import { openSetup } from '../flows/setup-view'; @@ -108,6 +108,10 @@ function menuItems(d: Device, st: State): (MenuItem | null)[] { ...(d.disabled ? [] : [ + // A setting in a group of its own: on or off now, under it; a tap switches it and opens the set-up of the + // updated configuration. Then what is done to the device itself. + { label: _('LAN Bypass'), icon: 'ethernet', sub: d.lan_bypass ? _('On') : _('Off'), run: () => toggleBypass(d) }, + null, { label: _('Rename'), icon: 'edit', run: () => renameHere(d) }, { label: _('Reconnect'), icon: 'refresh', tone: 'warn' as const, run: () => reconnect(d) }, { label: _('Remove'), icon: 'trash', tone: 'bad' as const, run: () => removeDevice(d) }, diff --git a/web/src/portal/setup.ts b/web/src/portal/setup.ts index bfea04d..90e3f22 100644 --- a/web/src/portal/setup.ts +++ b/web/src/portal/setup.ts @@ -3,13 +3,14 @@ import type { Kind } from '../shared/types'; import { fmt } from '../shared/i18n'; +import { V2R_WINDOWS } from '../shared/flags'; export type Platform = 'ios' | 'android' | 'windows' | 'mac' | 'linux' | 'unknown'; -export type AppId = 'vpn' | 'awg' | 'wg'; +export type AppId = 'vpn' | 'awg' | 'v2r' | 'wg'; /** The server's disguise generation as the portal sees it. */ export type Preset = 'off' | 'balanced' | 'max' | 'legacy'; -export const APP_NAME: Record = { vpn: 'AmneziaVPN', awg: 'AmneziaWG', wg: 'WireGuard' }; +export const APP_NAME: Record = { vpn: 'AmneziaVPN', awg: 'AmneziaWG', v2r: 'V2RayTun', wg: 'WireGuard' }; /** The platform the page is open on. iPadOS Safari calls itself a Mac; touch points tell. */ export function platformOf(ua: string, touchPoints = 0): Platform { @@ -45,17 +46,50 @@ export interface AppChoice { name: string; } -/** The apps that connect to a server with this disguise, the recommended one first; any WireGuard app without one. */ +/** + * The apps that connect to a server with this disguise, in the picker's order: + * the tunnel apps first (AmneziaWG; any WireGuard app without a disguise), then + * AmneziaVPN and V2RayTun. The sheet opens on the first, AmneziaWG (flows/setup-view.ts). + * V2RayTun runs AmneziaWG 2.0 (amneziawg-go 0.2.16 on Android, 0.2.18 on + * Windows), not 3.1: Maximum leaves it out. + */ export function appsFor(preset: Preset): AppChoice[] { - const out: AppChoice[] = [ - { id: 'vpn', name: APP_NAME.vpn }, - { id: 'awg', name: APP_NAME.awg }, - ]; + const out: AppChoice[] = [{ id: 'awg', name: APP_NAME.awg }]; if (preset === 'off') out.push({ id: 'wg', name: APP_NAME.wg }); + out.push({ id: 'vpn', name: APP_NAME.vpn }); + if (preset !== 'max') out.push({ id: 'v2r', name: APP_NAME.v2r }); return out; } -type Mark = 'appstore' | 'googleplay' | 'windows' | 'apple' | 'linux' | 'openwrt' | 'github' | 'site'; +/** + * The apps a device can take. A router takes AmneziaWG or WireGuard (its + * packages, one choice each). Anything else takes WireGuard under AmneziaWG's + * choice (the same file, code and menus: appName says both). V2RayTun has AmneziaWG in its Android app (phones, tablets, + * Android TV) and its Windows app, not on iOS, macOS or Linux (`os`: the + * device's own system where the page is open on it, else null). A phone or + * something else set up from elsewhere may be on Android; a computer only + * where the page is open on it under Windows (its link opens it there), and + * only while Windows is on (`windows`, shared/flags.ts V2R_WINDOWS). + */ +export function appsOn(kind: Kind, apps: AppChoice[], os: Platform | null = null, windows = V2R_WINDOWS): AppChoice[] { + return apps.filter((a) => { + if (kind === 'router') return a.id !== 'vpn' && a.id !== 'v2r'; + if (a.id === 'wg') return false; + if (a.id !== 'v2r') return true; + if (os === 'android' || (windows && os === 'windows')) return true; + return os === null && kind !== 'computer'; + }); +} + +/** + * An app's name in a sentence: with the disguise off (`wgToo`), AmneziaWG's + * choice is WireGuard's too ("AmneziaWG or WireGuard"), as their apps take the + * same file and code through the same menus. + */ +export const appName = (app: AppId, wgToo = false): string => + wgToo && app === 'awg' ? fmt(_('%s or %s'), APP_NAME.awg, APP_NAME.wg) : APP_NAME[app]; + +type Mark = 'appstore' | 'googleplay' | 'windows' | 'apple' | 'linux' | 'openwrt' | 'github' | 'telegram' | 'site'; export interface Store { href: string; @@ -63,11 +97,19 @@ export interface Store { top: string; main: string; mark: Mark; - /** A second source shown beside the first, where the store can fail (Android). */ + /** A second source shown beside the first: where the store can fail (Android), or the app's own channel. */ alt?: { href: string; top: string; main: string; mark: Mark; why: string }; } const GH_CLIENT = 'https://github.com/amnezia-vpn/amnezia-client/releases/latest'; +/** V2RayTun's channel (linked from v2raytun.com): its news and updates, beside its store. */ +const v2rChannel = (): NonNullable => ({ + href: 'https://t.me/v2raytun', + top: _('Channel on'), + main: 'Telegram', + mark: 'telegram', + why: _('V2RayTun’s own channel: news and updates of the app.'), +}); const apk = (href: string): NonNullable => ({ href, top: _('APK file on'), @@ -118,6 +160,24 @@ export function storeFor(app: AppId, platform: Platform): Store | null { }, linux: { href: 'https://github.com/amnezia-vpn/amneziawg-tools', top: _('On GitHub'), main: 'amneziawg-tools', mark: 'linux' }, }, + v2r: { + android: { + href: 'https://play.google.com/store/apps/details?id=com.v2raytun.android', + top: onPlay, + main: 'Google Play', + mark: 'googleplay', + // Its site's Android download is this store page too: the channel goes beside it. + alt: v2rChannel(), + }, + // The installer the official site (v2raytun.com) links to. + windows: { + href: 'https://storage.v2raytun.com/v2RayTun_Setup.exe', + top: _('Download from'), + main: 'v2raytun.com', + mark: 'windows', + alt: v2rChannel(), + }, + }, wg: { ios: { href: 'https://apps.apple.com/app/wireguard/id1441195209', top: onAppStore, main: 'App Store', mark: 'appstore' }, android: { @@ -179,16 +239,42 @@ function tunnelMenu(platform: Platform): { file: string; qr?: string } | undefin return menus[platform]; } +/* + * V2RayTun, read from its apps in November 2026 (its sources are closed). + * Android 5.26.83: the + at the top of its server list (menu_main); both items + * hand the text to one importer, which takes an amneziawg:// or awg:// link or a .conf. + * Windows (the Flutter app of v2RayTun_Setup.exe, read from its Dart snapshot): + * a + (tooltip "Import") at the top of the connection screen opens Import from + * clipboard, Type manually, Import from file, Import from QR code (an image + * file) and Import from phone. The clipboard takes an awg:// link (its parser + * refuses the amneziawg:// scheme) or a whole .conf; + * "Import from file" offers .txt and .json only and reads them line by line, + * a link a line. AmneziaWG runs there in its Tunnel mode (or Proxy + Tunnel), + * picked under "Mode" on the same screen. + */ +const v2rScan = () => menu('+', _('Import config from QRcode', 'V2RayTun app')); +const v2rImport = (platform: Platform) => + menu('+', platform === 'windows' ? _('Import from clipboard', 'V2RayTun app') : _('Import config from Clipboard', 'V2RayTun app')); + +/** V2RayTun's mode AmneziaWG needs on Windows, in its own words (it restarts as administrator for it). */ +export const v2rTunnelMode = () => _('Tunnel', 'V2RayTun app'); + /** Where the app scans a code; a phone of either kind gets both wordings. */ export function scanPath(app: AppId, platform: Platform = 'unknown'): string { if (app === 'vpn') return menu('+', _('QR code', 'AmneziaVPN app')); + if (app === 'v2r') return v2rScan(); const qr = tunnelMenu(platform)?.qr; return qr ?? fmt(_('%s (Android: %s)'), tunnelMenu('ios')!.qr, tunnelMenu('android')!.qr!.replace(/^.* → /, '')); } -/** Where the app takes a file (AmneziaVPN: the key, pasted by its Insert button); elsewhere, the Android app's words. */ +/** + * Where the app takes the connection: a file, or what is copied (AmneziaVPN: + * the key, pasted by its Insert button; V2RayTun: the link, from the + * clipboard); elsewhere, the Android app's words. + */ export function importPath(app: AppId, platform: Platform = 'unknown'): string { if (app === 'vpn') return menu('+', _('Insert', 'AmneziaVPN app')); + if (app === 'v2r') return v2rImport(platform); return (tunnelMenu(platform) ?? tunnelMenu('android')!).file; } @@ -198,18 +284,20 @@ export const vpnContinue = () => fmt(_('Tap “%s” and connect'), _('Continue' /** * The file into the app, step by step: [text, the part in bold]. Linux has no * app, only the tools: the file goes up straight from where it was saved - * (its name is a valid interface name, see tunnel_name on the router). + * (its name is a valid interface name, see tunnel_name on the router); with + * the disguise off (`wgToo`) wireguard-tools' wg-quick takes it too. */ -export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean): [string, string][] { +export function importSteps(app: AppId, platform: Platform, file: string, shared: boolean, wgToo = false): [string, string][] { if (platform === 'linux') return [ [_('Open a terminal in the folder with the file'), ''], // The command comes after the word, in bold: "Run sudo awg-quick up …". [`${_('Run')} `, `sudo ${app === 'wg' ? 'wg-quick' : 'awg-quick'} up ./${file}`], + ...(wgToo && app === 'awg' ? ([[`${_('Or, with wireguard-tools,')} `, `sudo wg-quick up ./${file}`]] as [string, string][]) : []), ]; const path = importPath(app, platform); return [ - [fmt(_('Open %s', 'step'), APP_NAME[app]), ''], + [fmt(_('Open %s', 'step'), appName(app, wgToo)), ''], [path.replace(/ → [^→]*$/, ' → '), path.replace(/^.* → /, '')], [shared ? _('Confirm the import and connect') : _('Pick the file and connect'), ''], ]; diff --git a/web/src/portal/styles/controls.css b/web/src/portal/styles/controls.css index 5610bc1..b4cf353 100644 --- a/web/src/portal/styles/controls.css +++ b/web/src/portal/styles/controls.css @@ -97,6 +97,15 @@ .btn.red:hover { background: color-mix(in srgb, var(--bad) 82%, transparent); } +/* Reconnect: the warn colour it has in the ⋯ menu and on the card's status. Dark ink: white on it reads at 2.3:1. */ +.btn.warn { + background: var(--warn); + color: #241300; + font-weight: 600; +} +.btn.warn:hover { + background: color-mix(in srgb, var(--warn) 82%, transparent); +} /* Waiting for the router: the button keeps its size, its content blurs away and an orb comes up in its place (ui/busy.ts runs the change). The orb is B4 Converge from aicss.dev's Orbs, at its own 28px stage and twice its speed: one circle walks a triangle, sharp at each corner and smaller, @@ -510,12 +519,43 @@ opacity: 1; margin-left: 0; } +/* A name wider than its place (ui/seg.ts marquee): it fades to nothing at the edge it runs past, the right one + at its start, the left one at its end, the fade sliding across as the name glides. */ +@property --fade-l { + syntax: ''; + inherits: false; + initial-value: 0px; +} +@property --fade-r { + syntax: ''; + inherits: false; + initial-value: 0px; +} +.appseg .seg-l { + -webkit-mask-image: linear-gradient(to right, transparent, #000 var(--fade-l), #000 calc(100% - var(--fade-r)), transparent); + mask-image: linear-gradient(to right, transparent, #000 var(--fade-l), #000 calc(100% - var(--fade-r)), transparent); + transition: + --fade-l 320ms var(--ease-out), + --fade-r 320ms var(--ease-out); +} +.appseg .seg-l.clip { + --fade-r: 18px; +} +.appseg .seg-l.clip.end { + --fade-l: 18px; + --fade-r: 0px; +} +.appseg .seg-t { + display: inline-block; +} /* Three apps on a phone: the icons take less room, so the picked one's name fits whole. */ .appseg { container-type: inline-size; } +/* The pill takes the narrow width too: a container query reaches only what is inside the track, never the track + itself, so --b is set on the pill (on .appseg it would stay 56 and the pill fall short of its item). */ @container (max-width: 300px) { - .appseg { + .appseg .seg-pill { --b: 44px; } .appseg .seg-b { @@ -770,11 +810,19 @@ background: var(--accent-soft); color: var(--accent); } +/* Two side by side while each has room for its words on one line (a store's name never wraps); else one under + the other. */ .badges2 { display: grid; - grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 8px; } +.badges2 .b-top, +.badges2 .b-main { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} .badges2 .badge { padding: 0 10px; gap: 10px; diff --git a/web/src/portal/styles/setup.css b/web/src/portal/styles/setup.css index e0f54f5..d828b48 100644 --- a/web/src/portal/styles/setup.css +++ b/web/src/portal/styles/setup.css @@ -439,6 +439,12 @@ align-items: baseline; column-gap: 0.3em; } +/* The scan line and, for V2RayTun reached by IP, the line under it. */ +.scanwrap { + display: flex; + flex-direction: column; + gap: 6px; +} .scanline .osm { white-space: nowrap; } diff --git a/web/src/portal/ui/seg.ts b/web/src/portal/ui/seg.ts index 67db687..cfd0ea9 100644 --- a/web/src/portal/ui/seg.ts +++ b/web/src/portal/ui/seg.ts @@ -5,7 +5,8 @@ // they stay right while the sheet around them changes width. At rest the pill // stands where CSS puts it (its item's place among the others: controls.css), so // a sheet changing width, a phone turned, carry it along with nothing to watch; -// only a pick moves it from here. +// only a pick moves it from here. A name wider than its place fades out at +// the edge it runs past and glides to its end on hover (marquee()). import { h, ic } from '../dom'; import { EASE_OUT, LEAD, SMOOTH, calm, play } from '../motion'; @@ -42,21 +43,104 @@ export function labelFade(at: LabelAt, picked: boolean): { duration: number; del return { duration: left > 0.01 ? 220 * left : 0, delay: 0 }; } +/** How fast a name too long for its place glides to its end (px/s): slow enough to read along. */ +const GLIDE_SPEED = 40; +/** In and out of the glide, gently at both ends. */ +const GLIDE_EASE = 'cubic-bezier(.45, 0, .55, 1)'; + +interface Marquee { + /** Glide to the name's end, or back to its start (`now`: at once). */ + go(end: boolean, now?: boolean): void; + /** At the start, at once (another item picked). */ + reset(): void; + /** At the end: back; at the start: to the end (a tap on the picked item, where there is no hover). */ + toggle(): void; +} + +/** + * A name in its place (`l`, its words the inline block inside): wider than + * the place, it is `.clip` and fades to nothing at the edge it runs past + * (controls.css); at its end (`.end`) the fade moves to the other edge. It + * glides from where it stands, at GLIDE_SPEED, a beat after the pointer comes. + */ +function marquee(l: HTMLElement): Marquee { + const t = l.firstElementChild as HTMLElement; + let atEnd = false; + /** The glide under way, if any. */ + let glide: Animation | null = null; + const over = () => Math.max(0, t.offsetWidth - l.clientWidth); + /** To the end or the start, from where it stands; `delay` before it sets off (a beat on hover, none to follow a moved end). */ + function go(end: boolean, now = false, delay = end ? 240 : 0) { + const o = end ? over() : 0; + atEnd = end && o > 0; + l.classList.toggle('end', atEnd); + const from = new DOMMatrix(getComputedStyle(t).transform).m41; + t.getAnimations().forEach((a) => a.cancel()); + glide = null; + t.style.transform = o ? `translateX(${-o}px)` : ''; + const dist = Math.abs(-o - from); + if (now || dist < 0.5) return; + const a = play(t, [{ transform: `translateX(${from}px)` }, { transform: `translateX(${-o}px)` }], { + duration: Math.max(420, (dist / GLIDE_SPEED) * 1000), + delay, + easing: GLIDE_EASE, + fill: 'backwards', + }); + glide = a; + // The place changed while it glided (a pick still opening it, the sheet still gliding to its width): on to + // the end it has now, from where it landed, without a jump. + a.onfinish = () => { + if (glide !== a) return; + glide = null; + if (atEnd && Math.abs(over() - o) > 0.5) go(true, false, 0); + }; + } + // Its place changes (a pick opens or folds it, the sheet changes width): clipped or not. At its end and still, + // it glides to where the end is now (back to the start if it fits); a glide under way corrects when it lands. + new ResizeObserver(() => { + l.classList.toggle('clip', over() > 0.5); + if (atEnd && !glide) go(true, false, 0); + }).observe(l); + return { go, reset: () => go(false, true), toggle: () => go(!atEnd) }; +} + export function iconSeg(items: SegItem[], value: T, onPick: (v: T) => void): IconSeg { const pill = h('span', { class: 'seg-pill' }); const el = h('div', { class: 'seg appseg', role: 'tablist' }, pill); + // A touch has no hover: a tap on the picked item glides its name instead. + let touch = false; const btns = items.map((it) => { const b = h( 'button', - { type: 'button', class: 'seg-b', role: 'tab', 'aria-label': it.label, title: it.label, onclick: () => pick(it.value) }, + { + type: 'button', + class: 'seg-b', + role: 'tab', + 'aria-label': it.label, + title: it.label, + onclick: () => (it.value === value ? touch && marquees[btns.indexOf(b)].toggle() : pick(it.value)), + }, ic(it.icon), - h('span', { class: 'seg-l' }, it.label), + h('span', { class: 'seg-l' }, h('span', { class: 'seg-t' }, it.label)), ); b.dataset.v = it.value; + b.addEventListener('pointerdown', (e) => (touch = e.pointerType !== 'mouse')); + // The picked item's name glides to its end while the pointer (or the keyboard's focus) is on it. + b.addEventListener('pointerenter', (e) => { + if (e.pointerType === 'mouse' && b.classList.contains('on')) marquees[btns.indexOf(b)].go(true); + }); + b.addEventListener('pointerleave', (e) => { + if (e.pointerType === 'mouse') marquees[btns.indexOf(b)].go(false); + }); + b.addEventListener('focus', () => { + if (b.matches(':focus-visible') && b.classList.contains('on')) marquees[btns.indexOf(b)].go(true); + }); + b.addEventListener('blur', () => marquees[btns.indexOf(b)].go(false)); el.appendChild(b); return b; }); const labelOf = (b: HTMLElement) => b.querySelector('.seg-l') as HTMLElement; + const marquees = btns.map((b) => marquee(labelOf(b))); const mark = () => btns.forEach((b) => { const on = b.dataset.v === value; @@ -102,10 +186,18 @@ export function iconSeg(items: SegItem[], value: T, onPick: return { width: l.getBoundingClientRect().width, opacity: +s.opacity, filter: s.filter, marginLeft: s.marginLeft }; }); [...btns, ...labels].forEach((x) => x.getAnimations().forEach((a) => a.cancel())); + // Every name back at its start; the picked one glides once it has its place, if the pointer is still on it. + marquees.forEach((m) => m.reset()); + window.setTimeout(() => { + if (value === v && btns[to].matches(':hover') && !touch) marquees[to].go(true); + }, SMOOTH.duration); value = v; mark(); - // The picked name's whole width, as it will stand once its item has its share. - const w1 = labels[to].getBoundingClientRect().width; + // The picked name's own width (its words, up to the 180 px CSS gives a picked name), not the room it has + // now: the room changes while it opens (AmneziaVPN's dense code widens the sheet), and a width measured + // before that would jump to the new room when the animation hands back to CSS. Where there is less room, + // the item squeezes the name (it shrinks to its place: controls.css), so the end is where CSS puts it. + const w1 = Math.min(180, (labels[to].firstElementChild as HTMLElement).offsetWidth); btns.forEach((b, i) => { const g1 = i === to ? 1 : 0; const f1 = getComputedStyle(b).flexBasis; @@ -184,6 +276,7 @@ export function iconSeg(items: SegItem[], value: T, onPick: sync(v) { if (v === value) return; value = v; + marquees.forEach((m) => m.reset()); mark(); placePill(); }, diff --git a/web/src/shared/awglink.ts b/web/src/shared/awglink.ts new file mode 100644 index 0000000..4ba74c1 --- /dev/null +++ b/web/src/shared/awglink.ts @@ -0,0 +1,60 @@ +// The connection as an `awg://` link, the form V2RayTun imports (its Android +// app since 5.24.76 and its Windows app, both with AmneziaWG 2.0): +// +// awg://@:?publickey=…&address=…&dns=…# +// +// Every other line of the .conf goes in as a parameter under its own name in +// lower case (PresharedKey → presharedkey, Jc → jc, I1 → i1), its value +// percent-encoded; lists lose the spaces after their commas. Made from the +// .conf itself, so the link always says what the file says. +// +// Why awg:// and not amneziawg:// (Android's own export): both apps pick the +// AmneziaWG parser for either prefix, but the Windows one (AwgParser. +// tryParseAwgUri in its Dart snapshot) then refuses any scheme but "awg", and +// the import ends in "Error". Android's parser never looks at the scheme. +// +// What V2RayTun 5.26.83 reads (its parser, from the APK; Windows reads the +// same names): the keys in lower case; jc, jmin, jmax, s1–s4 as whole numbers, +// h1–h4 and i1–i5 as text (ranges and tags pass); no AmneziaWG 3.1 keys (its +// cores have none). The name is the fragment: a .conf imported there is named +// by the clock instead (and "Import from file" reads a file line by line, a +// link a line: a .txt with the link imports, a .conf does not). It hands the +// endpoint to its core as it is, and its Android core takes no name: `ip`, +// where given, goes in place of the server's name. Its Windows core +// (amneziawg-windows) resolves the name itself, so there it stays. + +/** AmneziaWG 3.1's own lines (Maximum): V2RayTun's cores (amneziawg-go 0.2.16/0.2.18) have none. */ +const V31 = + /^\s*(HeaderProtectionKey|ContentPaddingAddition|RandomTrailers|DisableCookies|RekeyAfterTime|RekeyTimeout|RejectAfterTime|KeepaliveTimeout|MaxHandshakeAttempts)\s*=/im; + +/** Whether V2RayTun can take this configuration: false for AmneziaWG 3.1 (the Maximum disguise). */ +export const v2rFits = (conf: string): boolean => !V31.test(conf); + +/** In the order V2RayTun's own export writes them; the disguise after them. */ +const FIRST = ['publickey', 'address', 'dns', 'mtu', 'presharedkey', 'allowedips', 'persistentkeepalive']; +/** Lines that are lists: "1.1.1.1, 1.0.0.1" goes in as "1.1.1.1,1.0.0.1". */ +const LISTS = new Set(['address', 'dns', 'allowedips']); + +export function awgLink(conf: string, name: string, ip?: string | null): string { + const lines = new Map(); + for (const line of conf.split(/\r?\n/)) { + const m = /^\s*([A-Za-z0-9]+)\s*=\s*(.*?)\s*$/.exec(line); + if (m) lines.set(m[1].toLowerCase(), m[2]); + } + const priv = lines.get('privatekey') ?? ''; + // The last colon splits the port off, so a bracketed IPv6 host keeps its own. + const ep = lines.get('endpoint') ?? ''; + const at = ep.lastIndexOf(':'); + const host = ip ? (ip.includes(':') ? `[${ip}]` : ip) : at > 0 ? ep.slice(0, at) : ep; + const port = at > 0 ? ep.slice(at + 1) : ''; + lines.delete('privatekey'); + lines.delete('endpoint'); + const keys = [...FIRST.filter((k) => lines.has(k)), ...[...lines.keys()].filter((k) => !FIRST.includes(k))]; + const query = keys + .map((k) => { + const v = lines.get(k)!; + return `${k}=${encodeURIComponent(LISTS.has(k) ? v.replace(/,\s+/g, ',') : v)}`; + }) + .join('&'); + return `awg://${encodeURIComponent(priv)}@${host}${port ? `:${port}` : ''}?${query}#${encodeURIComponent(name)}`; +} diff --git a/web/src/shared/flags.ts b/web/src/shared/flags.ts new file mode 100644 index 0000000..6e1e5b7 --- /dev/null +++ b/web/src/shared/flags.ts @@ -0,0 +1,13 @@ +// Features that are built but kept off: each flag says why it is off and what +// turns it back on. Read at build time; the admin and the portal share them. + +/** + * V2RayTun on Windows (the admin's set-up of a computer, the portal's picker + * on a Windows computer). Off since November 2026: its AmneziaWG core + * (awgcore.dll from v2RayTun 3.10.15) never gives the tunnel the server's DNS + * (main.configureInterface has no SetDNS), so Windows keeps its own DNS, and + * with a full tunnel its firewall lets DNS reach the server's DNS alone: no + * names at all. Reported to V2RayTun; turn it on once a release fixes it + * (check that the tunnel adapter gets the DNS line of the .conf). + */ +export const V2R_WINDOWS = false; diff --git a/web/src/shared/icons.ts b/web/src/shared/icons.ts index 0f0ebd4..f03ccd9 100644 --- a/web/src/shared/icons.ts +++ b/web/src/shared/icons.ts @@ -36,11 +36,17 @@ const P: Record = { '', wireguard: '', + // V2RayTun: its logo, a filled Apple squircle (continuous corners) with V2R in SF Rounded Heavy cut out (256 px art). + v2raytun: + '', // Store and platform marks for the portal's set-up sheet (filled, 512 px art scaled to 24). appstore: '', googleplay: '', + // Telegram's paper plane alone, as the other store marks are glyphs alone (Simple Icons' path, CC0), centred and grown. + telegram: + '', github: '', openwrt: diff --git a/web/src/shared/types.ts b/web/src/shared/types.ts index 1e57327..6df8e51 100644 --- a/web/src/shared/types.ts +++ b/web/src/shared/types.ts @@ -292,6 +292,8 @@ interface AmneziaFields { server_pub_key: string; persistent_keep_alive: string; obfuscation: Record; + /** The server's address as an IP, from the portal (null: the name does not resolve; older routers leave it out). */ + host_ip?: string | null; } export interface AwgConfig { diff --git a/web/tests/events.test.ts b/web/tests/events.test.ts index d159f89..6502e7e 100644 --- a/web/tests/events.test.ts +++ b/web/tests/events.test.ts @@ -135,6 +135,14 @@ describe('a device’s link', () => { 'You changed device Phone of Myata · MTU', ); }); + it('says what each option became, and names the portal where a person changed it', () => { + expect(deviceChangedText('lan_bypass=on, kind=tablet')).toBe('LAN Bypass on, type: Tablet'); + expect(deviceChangedText('lan_bypass=off, mtu=1400, keepalive=25')).toBe('LAN Bypass off, MTU 1400, keep-alive 25 s'); + expect(deviceChangedText('mtu=auto, keepalive=auto')).toBe('MTU: automatic, keep-alive: automatic'); + const change = ev({ type: 'device_changed', by: 'portal', person: 'p1', device: 'd1', detail: 'kind=phone, lan_bypass=on' }); + expect(text(eventText({ people }, change))).toBe('Person Myata changed device Phone on their portal · type: Phone, LAN Bypass on'); + expect(text(eventText({ people }, change, 'p1'))).toBe('Device Phone changed on the portal · type: Phone, LAN Bypass on'); + }); }); describe('the router’s words', () => { diff --git a/web/tests/setup.test.ts b/web/tests/setup.test.ts index 6abbe47..7c2108e 100644 --- a/web/tests/setup.test.ts +++ b/web/tests/setup.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from 'vitest'; +import { awgLink, v2rFits } from '../src/shared/awglink'; import { addLink, appsFor, + appName, + appsOn, importPath, importSteps, inWebview, @@ -80,9 +83,99 @@ describe('setup', () => { expect(sameDevice('router', 'linux', true)).toBe(false); }); - it('lists the apps a disguise allows, AmneziaVPN first', () => { - expect(appsFor('max').map((a) => a.id)).toEqual(['vpn', 'awg']); - expect(appsFor('off').map((a) => a.id)).toEqual(['vpn', 'awg', 'wg']); + it('lists the apps a disguise allows, the tunnel apps first, V2RayTun short of 3.1', () => { + expect(appsFor('max').map((a) => a.id)).toEqual(['awg', 'vpn']); + expect(appsFor('balanced').map((a) => a.id)).toEqual(['awg', 'vpn', 'v2r']); + expect(appsFor('legacy').map((a) => a.id)).toEqual(['awg', 'vpn', 'v2r']); + expect(appsFor('off').map((a) => a.id)).toEqual(['awg', 'wg', 'vpn', 'v2r']); + }); + + it('offers V2RayTun on Android and Windows only, and a router its packages', () => { + // V2RayTun on Windows as when its flag is on (shared/flags.ts); off, below. + const ids = (kind: Parameters[0], os: Parameters[2] = null) => + appsOn(kind, appsFor('off'), os, true).map((a) => a.id); + expect(ids('router')).toEqual(['awg', 'wg']); + expect(ids('computer', 'windows')).toEqual(['awg', 'vpn', 'v2r']); + expect(ids('computer', 'mac')).not.toContain('v2r'); + expect(ids('computer', 'linux')).not.toContain('v2r'); + expect(ids('computer')).not.toContain('v2r'); + expect(ids('phone')).toContain('v2r'); + expect(ids('phone', 'android')).toContain('v2r'); + expect(ids('phone', 'ios')).not.toContain('v2r'); + expect(ids('other', 'android')).toContain('v2r'); + expect(ids('other', 'windows')).toContain('v2r'); + expect(ids('other', 'mac')).not.toContain('v2r'); + const off = (kind: Parameters[0], os: Parameters[2]) => + appsOn(kind, appsFor('off'), os, false).map((a) => a.id); + expect(off('computer', 'windows')).not.toContain('v2r'); + expect(off('other', 'windows')).not.toContain('v2r'); + expect(off('phone', 'android')).toContain('v2r'); + expect(off('phone', null)).toContain('v2r'); + expect(storeFor('v2r', 'android')?.href).toContain('com.v2raytun.android'); + expect(storeFor('v2r', 'android')?.alt?.href).toBe('https://t.me/v2raytun'); + expect(storeFor('v2r', 'ios')).toBeNull(); + expect(storeFor('v2r', 'windows')?.href).toBe('https://storage.v2raytun.com/v2RayTun_Setup.exe'); + expect(storeFor('v2r', 'mac')).toBeNull(); + expect(importPath('v2r', 'windows')).toBe('+ → Import from clipboard'); + expect(scanPath('v2r', 'android')).toBe('+ → Import config from QRcode'); + expect(importPath('v2r')).toBe('+ → Import config from Clipboard'); + }); + + it('writes the .conf as V2RayTun’s awg:// link, word for word as its own', () => { + const conf = [ + '[Interface]', + 'PrivateKey = To5H+v75ph8CwYDGaWIV+rpmLfig46SzvpJYucuyRp8=', + 'Address = 10.8.48.141/32', + 'DNS = 1.1.1.1, 1.0.0.1', + 'MTU = 1380', + 'Jc = 6', + 'Jmin = 40', + 'Jmax = 1000', + 'S1 = 67', + 'S2 = 41', + 'H1 = 1225345823', + 'H2 = 1000314123', + 'H3 = 827179548', + 'H4 = 962210412', + '', + '[Peer]', + 'PublicKey = Aif5mPmmTkPNf3uUOH1TSWnerLIV6hRgxC8oXyqTFDM=', + 'AllowedIPs = 0.0.0.0/0, ::/0', + 'Endpoint = hel-01.v2tun.net:51820', + 'PersistentKeepalive = 25', + '', + ].join('\n'); + expect(awgLink(conf, '1793854167195')).toBe( + 'awg://To5H%2Bv75ph8CwYDGaWIV%2BrpmLfig46SzvpJYucuyRp8%3D@hel-01.v2tun.net:51820' + + '?publickey=Aif5mPmmTkPNf3uUOH1TSWnerLIV6hRgxC8oXyqTFDM%3D&address=10.8.48.141%2F32&dns=1.1.1.1%2C1.0.0.1' + + '&mtu=1380&allowedips=0.0.0.0%2F0%2C%3A%3A%2F0&persistentkeepalive=25&jc=6&jmin=40&jmax=1000&s1=67&s2=41' + + '&h1=1225345823&h2=1000314123&h3=827179548&h4=962210412#1793854167195', + ); + }); + + it('keeps the preshared key, AmneziaWG 2.0 lines and an IPv6 endpoint in the link', () => { + const conf = + '[Interface]\nPrivateKey = a/b=\nAddress = 10.0.0.2/32\nS3 = 20\nH1 = 100-200\nI1 = \n\n' + + '[Peer]\nPublicKey = c+d=\nPresharedKey = e=\nAllowedIPs = 0.0.0.0/0\nEndpoint = [2001:db8::1]:51820\n'; + const url = awgLink(conf, 'Home Server'); + expect(url.startsWith('awg://a%2Fb%3D@[2001:db8::1]:51820?publickey=c%2Bd%3D&address=10.0.0.2%2F32&presharedkey=e%3D&')).toBe(true); + expect(url).toContain('&s3=20&h1=100-200&i1=%3Cr%202%3E%3Cb%200x8580%3E'); + expect(url.endsWith('#Home%20Server')).toBe(true); + }); + + it('names the server by its IP in the link where one is given (V2RayTun’s core takes no name)', () => { + const conf = '[Interface]\nPrivateKey = k=\n\n[Peer]\nPublicKey = p=\nEndpoint = engage.example.eu:4500\n'; + expect(awgLink(conf, 'Home', '203.0.113.7')).toBe('awg://k%3D@203.0.113.7:4500?publickey=p%3D#Home'); + expect(awgLink(conf, 'Home', '2001:db8::7')).toContain('@[2001:db8::7]:4500?'); + expect(awgLink(conf, 'Home', null)).toContain('@engage.example.eu:4500?'); + }); + + it('offers V2RayTun for AmneziaWG 2.0 and plain WireGuard, never for 3.1 (Maximum)', () => { + const v2 = '[Interface]\nPrivateKey = k=\nJc = 4\nS3 = 20\nI1 = \n\n[Peer]\nPublicKey = p=\n'; + expect(v2rFits(v2)).toBe(true); + expect(v2rFits('[Interface]\nPrivateKey = k=\n')).toBe(true); + expect(v2rFits(v2.replace('S3 = 20', 'HeaderProtectionKey = h=\nRandomTrailers = on'))).toBe(false); + expect(v2rFits(v2.replace('S3 = 20', 'ContentPaddingAddition = 10-100'))).toBe(false); }); it('sends people to the store first and to GitHub where no store has the app', () => { @@ -121,6 +214,22 @@ describe('setup', () => { expect(importSteps('wg', 'linux', 'Outline-Home.conf', false)[1][1]).toContain('wg-quick up'); }); + it('gives WireGuard AmneziaWG’s choice where the disguise is off, and a router both packages', () => { + const ids = (kind: Parameters[0]) => appsOn(kind, appsFor('off'), 'android').map((a) => a.id); + expect(ids('phone')).not.toContain('wg'); + expect(ids('computer')).not.toContain('wg'); + expect(ids('router')).toEqual(['awg', 'wg']); + expect(appName('awg', true)).toBe('AmneziaWG or WireGuard'); + expect(appName('awg')).toBe('AmneziaWG'); + expect(appName('vpn', true)).toBe('AmneziaVPN'); + expect(importSteps('awg', 'mac', 'Home.conf', false, true)[0]).toEqual(['Open AmneziaWG or WireGuard', '']); + expect(importSteps('awg', 'linux', 'Home.conf', false, true)[2]).toEqual([ + 'Or, with wireguard-tools, ', + 'sudo wg-quick up ./Home.conf', + ]); + expect(importSteps('awg', 'linux', 'Home.conf', false)).toHaveLength(2); + }); + it('spots in-app browsers', () => { expect(inWebview(`${ANDROID} Telegram-Android/10.0`)).toBe(true); expect(inWebview(IPHONE)).toBe(false); diff --git a/web/vercel.json b/web/vercel.json index 8eda7e8..571f172 100644 --- a/web/vercel.json +++ b/web/vercel.json @@ -4,7 +4,7 @@ "installCommand": "npm ci", "buildCommand": "npm run build:demo", "outputDirectory": "dist/demo", - "ignoreCommand": "[ \"$VERCEL_GIT_COMMIT_REF\" != main ] || git diff --quiet \"$VERCEL_GIT_PREVIOUS_SHA\" HEAD -- .", + "ignoreCommand": "[ \"$VERCEL_GIT_COMMIT_REF\" != main ] || { git cat-file -e \"$VERCEL_GIT_PREVIOUS_SHA^{commit}\" 2>/dev/null || exit 1; git diff --quiet \"$VERCEL_GIT_PREVIOUS_SHA\" HEAD -- .; }", "headers": [ { "source": "/(.*)",