Compare commits

9 Commits
Author SHA1 Message Date
Aemeath db9657c01c Dawnline 0.12.1
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Device cards on a computer keep "↓ 3.2 GB ↑ 557 MB" on one line, clear of
  the week's bars (0.12.0 let them run together in the two columns). A
  narrow card gets slightly smaller numbers and thinner bars, with the bars
  in the middle of the row; resizing the window, the card glides between
  its two shapes
- A device whose settings changed shows one big Reconnect button, the same
  as Connect on a device not set up yet, in place of its week and the
  orange Update pill. It opens the same question as Reconnect in the ⋯ menu
2026-10-20 21:54:42 +03:00
Aemeath fb73ac3a9f Dawnline 0.12.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- The portal's traffic charts show what came down and what went up apart.
  A device's last 7 days and "Data this month" draw each day both ways:
  downloads rise above a thin line, uploads hang below it, on one scale.
  Beside them "↓ 3.2 GB ↑ 557 MB" instead of one total; hover a day for
  its own, its date where "left" stands
- Charts answer the pointer between their bars too, in the portal and in
  the admin's daily charts (a device's week, a device card's 30 days, the
  last 30 days): the figures no longer blink back to the total
- The calendar under "Access until" plays its days in only when the row is
  opened, not again each time the page refreshes with it open
- On a phone the page comes in from the top down: "Your access" first,
  then the devices
- "Show key" on a router's set-up morphs to "Hide key" with its icon, and
  brings the keys themselves into focus (it blurred the field names)
2026-10-20 20:58:36 +03:00
Aemeath 2f2aaf6c34 Dawnline 0.11.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Russian translation. The admin pages, the LuCI menu and the router's
  messages (errors, Health checks, update steps, the service log) come in
  Russian with the new luci-i18n-dawnline-ru package, released beside the
  app. LuCI shows it when its language is Russian, or "auto" with a Russian
  browser
- The translation installs with install.sh when LuCI is in Russian (or with
  --lang ru), follows every Dawnline update and rollback, and can be added
  or removed in Components → Dawnline → Translation
- The portal speaks the visitor's language: it opens in the system's
  language and switches between English and Russian in place, from the
  language pill beside its QR code. It carries its own translation and needs
  no package
- Set-up steps quote the apps' own menus word for word, in Russian too:
  AmneziaVPN is "+ → Insert → Continue" (it has no "Add server"), and the
  Mac and Windows menus of WireGuard and AmneziaWG have their real names
- Questions in the portal (Reconnect, Remove) read from the left edge and
  close with Cancel, without ×
- Numbers, sizes and dates follow the page's language. A server that can't
  start says why in one sentence; event details and service log lines read
  as whole sentences
- README in Russian (README_ru.md). rules/i18n.md: how strings are written
  and translated; CI checks the catalogs (npm run i18n:check)
2026-10-20 19:33:52 +03:00
Aemeath caed976e63 Portal demo for Vercel
- The real portal over a router that lives in the page
  (web/src/portal/demo): "User" on "Dawnline Preview", ten scenarios
  (first visit, settings changed, out of data, outside the hours, paused,
  ended, plain HTTP, plain WireGuard, no free slots), devices kept per
  visitor in localStorage. Keys are random and the server's address never
  resolves: nothing is installed and nothing connects
- A "Demo" chip after the breadcrumb opens a drawer with the scenarios and
  Start over; a new device "connects" a few seconds after its settings
- A GitHub pill beside the page's QR knob; on a phone, where the names
  need the room, a GitHub button in the drawer instead
- npm run build:demo builds the static site into web/dist/demo;
  web/vercel.json deploys it with the portal's CSP and headers, and builds
  only commits on main that change web/
- README links to the live demo (dawnline-demo.vercel.app)
- Tests for the demo router (tests/demo.test.ts)
2026-10-19 23:08:06 +03:00
Aemeath 8e7c15ad56 README: fix the Development link; social preview image
- The Development heading's emoji carried a variation selector, which
  GitHub keeps in the heading's anchor, so the top link to #-development
  went nowhere
- docs/social-preview.png: the repository's social preview, in the
  screenshots' panel style
2026-10-19 21:19:16 +03:00
Aemeath 4f12ca19e7 Dawnline 0.10.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Portal redesigned from scratch. No header bar: the page opens with the
  server's name and the person's and fades under the edges. Device cards
  show the status, the last 7 days (hover a day for its figures) and a
  Connect or Update button; "Your access" folds into rows: what they can
  reach (with the names at home), data this month day by day, and when
  access ends. The page follows the system's light or dark theme
- Adding a device: pick the kind (PC, Mobile, Router, Other) and a name, or
  add it from the device itself with the page's QR code. The set-up sheet
  then shows the app for that system and the connection, waits for the
  first connection, says "<device> connected" and closes on its own
- Switching apps in the set-up sheet changes only what differs: the old
  words blur into the new ones, and the menu path is shown for iOS and
  Android in one line. Names, numbers and statuses that change on the page
  morph in place
- Dialogs open in the middle on a computer, on the same spring as the menu;
  buttons that wait for the router show a spinner at once
- A paused account gets one card that says so; the page's messages are
  short and no longer send people to the admin. A QR code of the page sits
  beside the breadcrumb, to open it on another device
- Allowed hours are shown in the visitor's own time zone
- The portal's Title setting is gone: the page and its tab take the
  server's name. A title set before is removed on upgrade
- The admin names .conf files after the server too, as the portal does
  (Outline-Home.conf); its device menu says "Download AmneziaWG config" and
  "Copy AmneziaVPN config", and its QR codes use the portal's round look in
  the admin's light or dark colours
- README rewritten, with screenshots made from a demo cast
  (scripts/capture-screenshots.mjs --demo)
2026-10-19 21:07:14 +03:00
Aemeath edeb1506fd Dawnline 0.9.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Portal: Reconnect replaces New keys and the connection sheet (QR, Key,
  File, and the menu's QR, key and .conf items). It gives the device new
  keys, shows it as "Not set up yet" until it connects with them (in the
  admin too) and opens the set-up sheet on the new configuration; "Update
  the connection" goes the same way. Reconnect is orange in the menu
- iPhone: "Open in AmneziaVPN" is "Send to AmneziaVPN": the key goes in as
  a .vpn file from the share sheet. AmneziaVPN takes vpn:// links only on
  Android; on iOS Safari said the address was invalid, or another app that
  claims vpn:// got the key. The desktop "Open in AmneziaVPN" link is gone
- A computer set up from a phone: get the app, add the connection, then
  "Or open your link on the computer"; "Another app" offers AmneziaWG and
  WireGuard there too and step 2 follows the pick. "Other" devices pick any
  system (iPhone/iPad, Android, Windows, Mac, Linux); the page counts as the
  device in hand only when the pick is its own system
- Import steps in each app's own words (iOS "+ → Create from file or
  archive", Android "+ → Import from file or archive", Mac, Windows "Add
  Tunnel → Import tunnel(s) from file"); Linux gets the awg-quick command
- Files are shared only on iOS (on Android the apps take no shared files:
  a download there), and alone: with a title, "Save to Files" also wrote
  the title as a .txt
- Files and tunnels are named after the server ("Outline Home" →
  Outline-Home.conf and .vpn) in the form every client accepts: letters,
  digits and "-", 15 characters, no Windows device names. The admin's
  downloads keep the device in the name. The AmneziaVPN key's description
  is the server's name alone
- The AmneziaVPN QR code holds the key without "vpn://": AmneziaVPN's
  scanner decodes the text as it is and failed on the prefix
- "This device" also when the page is opened beside the tunnel: the apps
  route the VPN's own address, which the portal shares, around their
  tunnel, so the one online device whose tunnel comes from the page's
  address is the one
- Fixed: "Already has AmneziaVPN?Copy the key" lost its space
2026-10-19 05:19:08 +03:00
Aemeath 7a6370aa9e Dawnline 0.8.1
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Fixed: the Overview's map stayed empty after leaving the page and coming
  back (the map freed on leaving was never made again); a map still loading
  when freed no longer draws into a dropped element
- A new connection's city shows within seconds: the agent looks its address
  up the moment the device connects or roams, in a child process so the
  watcher never waits, and open pages refresh once the place is known; the
  connection's entry in the activity log gets its place too. Since 0.7.0 the
  lookup waited for the minute tick and the pages for their 30-second poll
- Device window: each place has a strip of when the device was there (from
  the log's connections) and its share of the time; ▶ replays the period on
  the map: the place it leaves goes gray, a blue shimmer runs along a dotted
  arc to the next one, which lights up. A click or a drag on a strip goes to
  that moment; short visits are folded only past 24 moves. The fixed trail
  line is gone, and place names are no longer cut off at the map's edges
- Overview: the disguise tile's icon is gray when the disguise is Off
- People: "Add device" is a dashed chip with its label; "Send invite" is gone
  from the card (the invite card stays in its ⋯ menu)
2026-10-19 00:48:09 +03:00
Aemeath 466ca6c7b0 Dawnline 0.8.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Every field says what is wrong as you type, in the router's own words,
  and Save refuses what the router would: UDP port when editing a server,
  MTU, keep-alive, public address, DNS for devices, person name, device
  limit, end date and data limit, device names (the next free "Phone 2"
  is offered), home services, circles, portal title, redirect and other
  addresses, defaults, update time
- Cyrillic names give Latin ids, hostnames and file names; names are
  counted in characters, the rule names the characters it refuses; end
  dates must exist on the calendar; a mistyped extra portal address is
  refused instead of dropped
- The public address is checked on the router as it is typed: points at
  this router, at another address, behind Cloudflare, or the WAN is
  private or CGNAT; the wizard says so before the first step, never
  pre-fills a private WAN address and says where its suggestion came
  from; the Connection card says when the server was last reached from
  the internet; IPv6 names and literals work throughout
- A person can be moved to another server from their page; a server's
  tunnel network can be changed in the Danger zone (devices are
  renumbered and marked "Update config"); WAN and LAN zones come from the
  router's actual devices; when the public IPv4 changed, one click puts
  the new one in
- Over the data limit or outside the allowed hours the tunnel stays
  connected and the portal explains why nothing gets through, instead of
  a silent handshake failure; Health's "devices loaded" compares the
  peers themselves, not their count
- Portal: install links for this platform, two first steps on a first
  visit, the phone's back button closes a sheet, the file goes through
  the share sheet into the app, two QR codes (AmneziaVPN camera, AmneziaWG
  and WireGuard apps), the sheet notices the first connection
- Admin: Enter submits a dialog, arrow keys walk the menus, Find in People
  ("/" focuses it), a device of a paused, ended or over-limit person says
  so, "Keep access" past its end date is said on the Overview, Allowed
  hours enforce nothing until saved, the invite card shares the link
- Health warns when another package's policy routing (mwan3, pbr) sends
  tunnel traffic past the home-device path
- CLI: person ls, device ls, log with -n, --since, --level, --src and
  --json; exit code 2 for an unknown command and 1 when health finds an
  error; person rm asks for --yes when devices would go; devices added
  from the command line get their event and "issued" marker like the
  UI's
- Three disguises: Off, Balanced and Maximum. Standard and Strong (1.0-style
  junk only, which networks learned to spot) are no longer offered; a server
  still on one keeps running and its card says to switch. A new server gets
  the strongest disguise its router can run
- Portal: setting up a device is one sheet with two steps. Get the app
  (AmneziaVPN first; AmneziaWG, and WireGuard with the disguise off, behind
  "Another app") from the store of the device in hand, with the GitHub release
  where no store has it and the version the server needs said once; then add
  the connection (open in AmneziaVPN, copy the key, share or download the
  file). A device set up from another device gets its link to take there, as a
  QR code for a phone; a phone set up from a computer also gets the connection
  as a code, one code revealed at a time so the camera cannot read the wrong one
- Portal motion: the first visit comes in once (blocks in reading order,
  meters fill, the sun rises in the logo); a repaint glides cards to their
  new places and brings changed values into focus; sheets slide up on
  phones and can be pulled down, come into focus on a computer, follow
  their content's height and turn into the next sheet in place; tabs and
  segments slide, menus, tooltips and toasts grow out of what opened them,
  copy buttons turn into a check, buttons waiting for the router spin;
  with reduced motion only the fades remain
- Portal: while a device is set up, a card at the top shows the way from
  it to the router with a light running along it; on the first connection
  the way fills green, the steps fold away and the sheet closes by itself.
  The first connection is the first fresh handshake, so it is no longer
  missed while the watcher catches up (or after new keys), and the device's
  card goes on to Connected
- Portal: QR codes are light dots on a black card, fuller on dense keys,
  with "Show a light code" for scanners that read only dark on light (every
  code switches, the choice is kept); the link and code a set-up sheet
  hands to another device open that device's set-up there at once
- Portal: Remove and New keys ask in a small alert with the action's icon;
  the open one of two cards is not a button; device names are no longer
  repeated in every line of the set-up sheet; the code card lines up with
  the rest of its card (a class clash gave it the page's padding); text
  keeps the arrow cursor, store badges and link buttons are not underlined
2026-10-18 23:28:10 +03:00
252 changed files with 37988 additions and 5395 deletions

No files matched your search

+7 -5
View File
@@ -1,8 +1,9 @@
name: Build packages name: Build packages
# A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk # A tag vX.Y.Z builds luci-app-dawnline and its translation packages
# (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with # (luci-i18n-dawnline-<lang>) as .ipk (OpenWrt 24.10, opkg) and .apk (OpenWrt
# both packages and sha256sums.txt, the files install.sh and the in-app updater # 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with the
# packages and sha256sums.txt, the files install.sh and the in-app updater
# download. The release notes list what changed since the previous tag, from the # download. The release notes list what changed since the previous tag, from the
# commits (scripts/release-notes.sh). Run it by hand to get the packages as # commits (scripts/release-notes.sh). Run it by hand to get the packages as
# workflow artifacts only. # workflow artifacts only.
@@ -89,7 +90,8 @@ jobs:
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with: with:
name: package-${{ matrix.type }} name: package-${{ matrix.type }}
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }} # The app and its translation packages (luci-i18n-dawnline-<lang>).
path: dist/luci-*-${{ needs.version.outputs.version }}.${{ matrix.type }}
if-no-files-found: error if-no-files-found: error
retention-days: 7 retention-days: 7
@@ -123,7 +125,7 @@ jobs:
- name: Checksums - name: Checksums
working-directory: release working-directory: release
run: | run: |
sha256sum luci-app-dawnline-* > sha256sums.txt sha256sum luci-* > sha256sums.txt
cat sha256sums.txt cat sha256sums.txt
- name: Publish the release - name: Publish the release
+10
View File
@@ -51,6 +51,15 @@ jobs:
id: types id: types
run: npm run --silent typecheck run: npm run --silent typecheck
# The catalogs follow the code: every string collected, translated, its placeholders kept.
- name: Translations
id: i18n
run: |
if ! npm run --silent i18n:check; then
echo "::error::The translation catalogs are out of date or incomplete. Run 'npm run i18n' in web/, translate the new entries in each ru.po and commit them (rules/i18n.md)."
exit 1
fi
- name: Tests - name: Tests
id: tests id: tests
run: npm test run: npm test
@@ -79,6 +88,7 @@ jobs:
echo "|---|---|" echo "|---|---|"
echo "| Formatting | ${{ steps.format.outcome }} |" echo "| Formatting | ${{ steps.format.outcome }} |"
echo "| Types | ${{ steps.types.outcome }} |" echo "| Types | ${{ steps.types.outcome }} |"
echo "| Translations | ${{ steps.i18n.outcome }} |"
echo "| Tests | ${{ steps.tests.outcome }} |" echo "| Tests | ${{ steps.tests.outcome }} |"
echo "| Bundles | ${{ steps.build.outcome }} |" echo "| Bundles | ${{ steps.build.outcome }} |"
} >> "$GITHUB_STEP_SUMMARY" } >> "$GITHUB_STEP_SUMMARY"
+5 -3
View File
@@ -9,13 +9,15 @@ Guidance for coding agents working in this repository (`tickcount/luci-app-dawnl
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision. - `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
- `rules/shell.md` — install, uninstall, init and CI scripts. - `rules/shell.md` — install, uninstall, init and CI scripts.
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser. - `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
- `rules/i18n.md` — translations: every visible string and backend message wrapped, the catalogs, the Russian style guide and glossary. Anything added to the admin UI or the portal is localized in the same change; anything removed takes its catalog entries with it.
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`). This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
## Layout ## Layout
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL. - `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`. - `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`. `web/i18n/` — the string catalogs' tools (`extract.ts`, `po.ts`, `lmo.ts`).
- `package/luci-app-dawnline/po/` — the admin's catalog (`templates/dawnline.pot`, `ru/dawnline.po`): luci.mk builds the `luci-i18n-dawnline-ru` package from it. The portal's catalog is `web/src/portal/i18n/ru.po`, bundled into the portal.
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`). - `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`. - `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`. - `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
@@ -24,7 +26,7 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational). - `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`. - `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm test`, `npm run build` — and commit the rebuilt bundles (CI fails on a changed or new file under `package/`). - In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run i18n:check` (after changing visible text: `npm run i18n`, translate the new entries in each `ru.po`), `npm test`, `npm run build` — and commit the rebuilt bundles and the catalogs (CI fails on a changed or new file under `package/`).
- `shellcheck -S warning` for the shell scripts (CI finds them by shebang). - `shellcheck -S warning` for the shell scripts (CI finds them by shebang).
- A tag builds only after CI passes on it (`build.yml` calls `ci.yml`). - A tag builds only after CI passes on it (`build.yml` calls `ci.yml`).
@@ -33,6 +35,6 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit. - A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree). - Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
- No `Co-Authored-By` or other agent attribution in commits. - No `Co-Authored-By` or other agent attribution in commits.
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` and `sha256sums.txt`. - Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` (the app and `luci-i18n-dawnline-ru`) and `sha256sums.txt`.
- Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead. - Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead.
- On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256). - On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256).
+324 -116
View File
@@ -1,88 +1,192 @@
# Dawnline <div align="center">
[![CI](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml/badge.svg)](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml) <picture>
[![Build packages](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml/badge.svg)](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml) <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
</picture>
Your OpenWrt router as a private VPN for the people you choose. <h1>Dawnline</h1>
Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router **Your OpenWrt router as a private VPN for the people you choose.**
and gives every person a personal link. They open it, add their own devices
(up to the limit you set) and connect with AmneziaVPN or AmneziaWG. You decide
what each person may reach: the home network, the internet, or both.
Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-liminal): <a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Latest release" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
the same idea rebuilt around people instead of peers, with a personal portal, <a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
limits, live traffic and a LuCI admin that follows a modern design. <a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Downloads" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="License" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<br>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 and 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
![Overview](docs/screenshots/overview.png) [**Quick start**](#-quick-start) &nbsp;·&nbsp; [**Live demo**](https://dawnline-demo.vercel.app) &nbsp;·&nbsp; [Features](#-features) &nbsp;·&nbsp; [How it works](#-how-it-works) &nbsp;·&nbsp; [Screenshots](#-a-closer-look) &nbsp;·&nbsp; [FAQ](#-faq) &nbsp;·&nbsp; [Development](#-development)
| People | A person | **English** &nbsp;·&nbsp; [Русский](README_ru.md)
</div>
<br>
Dawnline runs an [AmneziaWG] server on your OpenWrt router and gives every
person you invite **a personal link**. They open it, **add their own phones and
computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide
**what each of them may reach** (the home network, the internet, or both) and
**for how long, how much and when**.
<p align="center">
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="The personal portal: devices and access, and adding a phone in three steps" width="860"></a>
<br>
<sub>A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect.
<a href="https://dawnline-demo.vercel.app"><b>Try it in the live demo</b></a>: nothing installs and nothing connects.</sub>
</p>
## 💡 Why Dawnline?
Sharing a home VPN usually means making a config file by hand, sending it over
a messenger and hoping nobody shares it further. Dawnline turns that around:
| | A VPN by hand | With Dawnline |
|---|---|---|
| **Setting up a device** | You make a config and send it | They add it themselves from their link |
| **Who can do what** | Everyone gets the same | Home, internet or both, per person |
| **Ending access** | Find and delete their peers | A date, a data limit, or one click |
| **Knowing what goes on** | Read `wg show` | Who is online, traffic, places, a log |
| **When something breaks** | You find out from them | A watchdog notices and repairs it |
It is the successor of [Liminal]: the same idea rebuilt around people instead
of peers, with a personal portal, limits, live traffic and a LuCI admin that
follows a modern design.
## 🚀 Quick start
1. **Install** on the router (it asks before it changes anything):
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
2. **Set up** in LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, and follow the
wizard. It suggests the port, the public address and the networks.
3. **Invite** someone: <kbd>Add person</kbd>, then send them the link or the
invite card with its QR code. They do the rest.
> [!TIP]
> Behind Cloudflare, give the portal a port Cloudflare proxies: 2053, 2083,
> 2087, 2096 or 8443.
## ✨ Features
<table>
<tr>
<td width="50%" valign="top">
<h3>🔗 A link, not an account</h3>
<p>Three words, like <code>vpn.example.com/kamiro-telosu-bavine</code>. The link is the key: no sign-up, no password, and a new link locks the old one out at once.</p>
</td>
<td width="50%" valign="top">
<h3>📱 Their own devices</h3>
<p>People add, rename and remove devices up to their limit. Adding one walks them through it: the right app, then a QR code, a link, a key or a file.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>👥 People, not peers</h3>
<p>One card per person with their devices, who is online, traffic, end date and data limit. Filter by who needs attention or is paused.</p>
</td>
<td valign="top">
<h3>🧭 Who reaches what</h3>
<p>The home network, the internet or both; only some networks or devices at home (a NAS, Home Assistant). Family sees family, guests see guests.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>⏳ Limits</h3>
<p>End dates, monthly or total data limits, allowed hours, a pause button. Changes apply at once, without dropping anyone else's connection.</p>
</td>
<td valign="top">
<h3>🕶️ Disguise</h3>
<p>Presets that make the VPN traffic harder to spot and block, with what each one needs from the apps.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🏠 Internet like a home device</h3>
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
</td>
<td valign="top">
<h3>🗺️ Overview and places</h3>
<p>Who is online with what, speed now, the last 30 days, and a map of where people connect from, at city level.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🩺 Repairs itself</h3>
<p>Health checks with one-click fixes, and a watchdog that checks the tunnels, access rules and portal every minute and mends them.</p>
</td>
<td valign="top">
<h3>📦 Updates and backups</h3>
<p>Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🌐 English and Russian</h3>
<p>The portal follows the visitor's language and switches in its header. The admin pages and the router's messages come in Russian with the <code>luci-i18n-dawnline-ru</code> package.</p>
</td>
<td valign="top"></td>
</tr>
</table>
## 🧩 How it works
```mermaid
flowchart LR
you(["🛠️ You, in LuCI"]) -- "add a person" --> link["🔗 Their link"]
link -- "they open it" --> portal["📱 Their portal"]
portal -- "add a device" --> app["App and connection"]
app == "AmneziaWG tunnel" ==> router["🌅 Dawnline<br>on your router"]
router -- "if allowed" --> home["🏠 Home network"]
router -- "if allowed" --> net["🌍 Internet"]
```
1. **You add a person** in LuCI and choose what they may reach, their device
limit, an end date or a data limit.
2. **They open their link** on any device. The portal is theirs alone: it shows
their devices and their access; access and limits stay yours to change.
3. **They add a device.** The portal points them to the app for that system and
hands over the connection; the router gives each device its own keys.
4. **The device connects** through the router's AmneziaWG server, and Dawnline
lets through what that person may reach, counts their traffic and keeps to
their limits.
## 📸 A closer look
<p align="center">
<img src="docs/screenshots/overview.png" alt="Overview: who is online, speed, the last 30 days and where people connect from" width="720">
<br>
<sub><b>Overview</b>: who is online, speed now, the last 30 days and a map of where people connect from.</sub>
</p>
<table>
<tr>
<td width="50%" valign="top">
<img alt="People: everyone on the server, with their devices, data and state" src="docs/screenshots/people.png">
<p align="center"><sub><b>People</b>: online, ending soon, over the limit, outside their hours, paused.</sub></p>
</td>
<td width="50%" valign="top">
<img alt="A person: their devices, traffic, places and limits" src="docs/screenshots/person.png">
<p align="center"><sub><b>A person</b>: their devices, traffic, places and limits.</sub></p>
</td>
</tr>
</table>
## 📋 Requirements
| | What Dawnline needs |
|---|---| |---|---|
| ![People](docs/screenshots/people.png) | ![Person](docs/screenshots/person.png) | | **OpenWrt** | 24.10 (opkg, `.ipk`) or 25.12 (apk, `.apk`) |
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: the installer adds a build made for your firmware when they are missing |
| **Free flash** | about 2 MB |
| Personal portal | Home network access | ## 📥 Install
|---|---|
| ![Personal portal](docs/screenshots/portal.png) | ![Access](docs/screenshots/access.png) |
## Features
- **People, not peers.** One card per person with device chips, live status,
traffic, end date and data limit. Add a person, send them the link or the
invite card (QR code), and they do the rest.
- **Personal portal.** Every person gets a link made of three words
(`https://vpn.example.com/kamiro-telosu-bavine`). The link is the key: no
accounts, no sessions, and a new link locks the old one out at once. People
add, rename and remove their devices and get each one as a QR code,
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
access or limits. Links work on the portal's own port with a Let's Encrypt
certificate (via ACME), several addresses at once (a Cloudflare-proxied name,
a plain IP), the same link at home, and wrong links can redirect to your
website. Behind Cloudflare, pick a port it proxies (2053, 2083, 2087, 2096 or
8443).
- **Access per person**, enforced in an `inet dawnline` nftables table on the
tunnel interface: home network only, internet only, or both, and optionally
only some home networks or home services (picked from the devices the router
sees over DHCP). Devices of different people reach each other never, always,
or within circles (family sees family, guests see guests). "Who reaches what"
sums up the rules and "Check access" walks them step by step for a device
and an address.
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
or total data limits, allowed hours, pause anyone. Devices
drop off the tunnel at once (`awg syncconf`, no interface restart).
- **Disguise presets** for AmneziaWG obfuscation (junk packets,
header and padding parameters), with what each preset needs from the apps.
- **Internet like a home device.** Tunnel clients' internet traffic enters the
router from the LAN, through a small network namespace on the LAN bridge
(needs `kmod-veth`). Whatever handles LAN traffic on the router (proxies, DPI
bypass, DNS filters, the `lan` zone) handles VPN clients too, with no
per-tool integration.
- **Overview.** Who is online with what, speed now, today and the last 30 days,
and a map of where people connect from (city level).
- **Diagnostics.** Health checks with one-click fixes, including the ones that
matter for reaching the portal from outside (DNS, port forwards, reply
routing behind proxies such as SSClash/Mihomo, certificate coverage). A
watchdog checks the tunnels, access rules, portal, resolver and LuCI link
every minute and repairs them on its own (a cron job looks after the agent
itself). One log holds people's activity and the service log: tunnel starts
and stops with netifd's reasons, repairs and errors (`dawnline log` on the
router).
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
the few OpenWrt packages Dawnline adds.
- **Backups** nightly and before risky operations, JSON export/import to move
to another router.
## Requirements
- OpenWrt **24.10** (opkg, `.ipk`) or **25.12** (apk, `.apk`)
- AmneziaWG (`kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`):
the installer adds a build made for your firmware when it is missing
- About 2 MB of free flash
## Install
On the router:
```sh ```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)" sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
@@ -90,17 +194,22 @@ sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline
The installer checks the firmware, the clock, free space and DNS, lets you pick The installer checks the firmware, the clock, free space and DNS, lets you pick
a release (the latest is the default), shows the plan and asks before it a release (the latest is the default), shows the plan and asks before it
changes anything. It downloads the Dawnline package for your package manager, changes anything. It downloads the package for your package manager, checks it
checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
if it is missing, then installs Dawnline with its dependencies and checks that missing, then installs Dawnline (with its Russian translation when LuCI is in
LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup Russian) and checks that LuCI can reach it.
wizard.
Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}` > [!NOTE]
and the service state to `/etc/dawnline/installer-backups/` (the newest three > Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
are kept); if a step fails, it puts them back. Packages are not rolled back: to > and the service state to `/etc/dawnline/installer-backups/` (the newest three
return to an older release, run the installer with `--tag`. Everything it does > are kept), and puts them back if a step fails. Packages are not rolled back:
is logged to `/tmp/dawnline-install.log`. > to return to an older release, run the installer with `--tag`. Everything it
> does is logged to `/tmp/dawnline-install.log`.
<details>
<summary><b>Installer options</b></summary>
<br>
With options, download it first: With options, download it first:
@@ -109,6 +218,7 @@ wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luc
sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
sh /tmp/dawnline-install.sh --lang ru # with the admin's Russian translation
``` ```
| Option | | | Option | |
@@ -117,39 +227,68 @@ sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing | | `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors | | `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) | | `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same | | `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov], then [2Grey] (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Components**). `DAWNLINE_AWG` does the same |
| `--no-awg` | Same as `--awg skip` | | `--no-awg` | Same as `--awg skip` |
| `--lang auto\|ru\|none` | The admin's translation, `luci-i18n-dawnline-<lang>`: `auto` (the default) adds it when LuCI is set to that language or has its LuCI translation; `none` adds none. An installed one is always kept up to date. Later: **Dawnline → Components → Translation**. `DAWNLINE_LANG` does the same |
When GitHub is slow or blocked, the installer retries downloads through </details>
`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
through a mirror: <details>
<summary><b>When GitHub is slow or blocked</b></summary>
<br>
The installer retries downloads through `ghfast.top` and `gh-proxy.com` on its
own. To fetch the installer itself through a mirror:
```sh ```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)" sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)" sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
``` ```
By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases): </details>
<details>
<summary><b>Installing by hand</b></summary>
<br>
From a [release](https://github.com/tickcount/luci-app-dawnline/releases):
```sh ```sh
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10 opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12 apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
``` ```
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings, The Russian translation is `luci-i18n-dawnline-ru-<version>` from the same
keys and history are kept, and a backup is made first. release, installed the same way after the app (then `/etc/init.d/uhttpd restart`).
**Remove** on the router: </details>
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Components</kbd>, or run the installer
again. Settings, keys and history are kept, and a backup is made first.
### Remove
```sh ```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)" sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
``` ```
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
removal (the same as **Settings → Remove Dawnline from this router**), removes removal (the same as <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>),
the package and cleans up what is left. AmneziaWG stays installed, since other removes the package and cleans up what is left. After installing Dawnline
tunnels may use it. After installing Dawnline again, restore the backup in again, restore the backup in <kbd>Settings</kbd> › <kbd>Backups</kbd>.
**Settings → Backups**. With options, download it first:
> [!IMPORTANT]
> AmneziaWG stays installed, since other tunnels may use it. Add `--remove-awg`
> to take it away too.
<details>
<summary><b>Uninstaller options</b></summary>
<br>
With options, download it first:
```sh ```sh
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
@@ -163,25 +302,83 @@ sh /tmp/dawnline-uninstall.sh --dry-run
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) | | `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
| `-n`, `--dry-run` | Show what would be removed; change nothing | | `-n`, `--dry-run` | Show what would be removed; change nothing |
By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then By hand: <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>
`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`. (keeps a backup), then `opkg remove luci-app-dawnline` or
`apk del luci-app-dawnline`.
## What Dawnline changes on the router </details>
## ❓ FAQ
<details>
<summary><b>Which apps do people use?</b></summary>
<br>
AmneziaVPN or AmneziaWG on phones and computers, and plain WireGuard when the
disguise is off. The portal shows each person the app for their system and how
to add the connection in it.
</details>
<details>
<summary><b>What happens when someone loses their link?</b></summary>
<br>
Make a new one on their page. The old link stops working at once; their devices
keep working, unless you tick the ones to remove with it.
</details>
<details>
<summary><b>Does it touch the rest of my router?</b></summary>
<br>
Only what it created, and `dawnline teardown` removes all of it. The full list
is under [What Dawnline changes on the router](#-what-dawnline-changes-on-the-router).
</details>
<details>
<summary><b>How do I move to another router?</b></summary>
<br>
<kbd>Export JSON</kbd> in <kbd>Settings</kbd> › <kbd>Backups</kbd> on the old
one, install Dawnline on the new one and import the file there.
</details>
<details>
<summary><b>Where do the places on the map come from?</b></summary>
<br>
From the address a device connects from, looked up at city level and cached on
the router. It can be turned off in <kbd>Settings</kbd>.
</details>
## 🧾 What Dawnline changes on the router
Only objects it created: network interfaces tagged `_dawnline`, firewall Only objects it created: network interfaces tagged `_dawnline`, firewall
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`, sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
latter a port of the LAN bridge), policy rules for the tunnel interfaces with latter a port of the LAN bridge, which needs `kmod-veth`), policy rules for the
one routing table, a second dnsmasq instance on port 5354 tunnel interfaces with one routing table, a second dnsmasq instance on port
(`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check 5354 (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat
and, while the portal is on, a uhttpd instance for it. `dawnline teardown` check and, while the portal is on, a uhttpd instance for it.
removes all of them. `dawnline teardown` removes all of them.
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters `/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
are kept in `/var/run/dawnline` and flushed to flash at most hourly. are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access
changes reach the tunnel with `awg syncconf`, without restarting the interface;
`dawnline log` on the router shows the service log.
## Development ## 🧰 Development
``` ```
package/luci-app-dawnline/ package/luci-app-dawnline/
@@ -192,7 +389,9 @@ package/luci-app-dawnline/
root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets
root/usr/bin/dawnline command line (`dawnline help`) root/usr/bin/dawnline command line (`dawnline help`)
htdocs/ LuCI views and the generated module dawnline/app.js htdocs/ LuCI views and the generated module dawnline/app.js
po/ the admin's string catalog (dawnline.pot, ru/dawnline.po)
web/ TypeScript sources of the admin UI and the portal web/ TypeScript sources of the admin UI and the portal
web/i18n/ catalog tools: collect strings, merge .po files, compile .lmo
build/Dockerfile package build with the OpenWrt SDK build/Dockerfile package build with the OpenWrt SDK
scripts/ build, deploy and check scripts scripts/ build, deploy and check scripts
``` ```
@@ -201,20 +400,29 @@ scripts/ build, deploy and check scripts
cd web cd web
npm ci npm ci
npm run format # Prettier npm run format # Prettier
npm run ci # format check, types, tests, minified bundles npm run ci # format check, types, catalogs, tests, minified bundles
npm run i18n # collect new strings into the catalogs (then translate them in ru.po)
scripts/lint-ucode.py # static ucode checks scripts/lint-ucode.py # static ucode checks
scripts/check-ucode.sh root@router # compile every ucode file on a router scripts/check-ucode.sh root@router # compile every ucode file on a router
scripts/deploy.sh root@router # install the working tree (backs up configs first) scripts/deploy.sh root@router # install the working tree (backs up configs first)
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
scripts/capture-screenshots.mjs # capture docs/screenshots/raw/*.png from a router scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
scripts/frame-screenshots.py # frame them for this README scripts/frame-screenshots.py # frame them for this README
``` ```
The web bundles are committed: CI fails when they are out of date. Pushing a The web bundles and the catalogs are committed: CI fails when they are out of
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK date or a string is untranslated (`rules/i18n.md`). Pushing a tag `vX.Y.Z`
and publishes a release with `sha256sums.txt`. (matching `PKG_VERSION`) builds the packages and their translations with the
OpenWrt SDK and publishes a release with `sha256sums.txt`.
## License ---
[MIT](LICENSE) <div align="center">
<sub>Made for OpenWrt · <a href="LICENSE">MIT license</a> · <a href="#readme">Back to top ↑</a></sub>
</div>
[AmneziaWG]: https://docs.amnezia.org/
[Liminal]: https://github.com/tickcount/openwrt-liminal
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
[2Grey]: https://github.com/2Grey/awg-openwrt
+431
View File
@@ -0,0 +1,431 @@
<div align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
</picture>
<h1>Dawnline</h1>
**Ваш роутер на OpenWrt как личный VPN для тех, кого вы выберете.**
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Последний релиз" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Загрузки" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Лицензия" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
<br>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 и 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
[**Быстрый старт**](#-быстрый-старт) &nbsp;·&nbsp; [**Демо**](https://dawnline-demo.vercel.app) &nbsp;·&nbsp; [Возможности](#-возможности) &nbsp;·&nbsp; [Как это работает](#-как-это-работает) &nbsp;·&nbsp; [Скриншоты](#-как-это-выглядит) &nbsp;·&nbsp; [Вопросы](#-вопросы-и-ответы) &nbsp;·&nbsp; [Разработка](#-разработка)
[English](README.md) &nbsp;·&nbsp; **Русский**
</div>
<br>
Dawnline запускает сервер [AmneziaWG] на вашем роутере с OpenWrt и даёт каждому,
кого вы пригласите, **личную ссылку**. По ней человек **сам добавляет свои
телефоны и компьютеры** и подключается через AmneziaVPN, AmneziaWG или WireGuard.
Вы решаете, **что ему доступно** (домашняя сеть, интернет или и то и другое), и
**на какой срок, сколько трафика и в какие часы**.
<p align="center">
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
<br>
<sub>Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился.
<a href="https://dawnline-demo.vercel.app"><b>Попробуйте в демо</b></a>: ничего не устанавливается и никуда не подключается.</sub>
</p>
## 💡 Почему Dawnline?
Обычно, чтобы поделиться домашним VPN, приходится вручную делать файл
конфигурации, отправлять его в мессенджере и надеяться, что дальше он никуда не
уйдёт. Dawnline делает наоборот:
| | VPN вручную | С Dawnline |
|---|---|---|
| **Настройка устройства** | Вы делаете конфиг и отправляете его | Человек добавляет устройство сам по своей ссылке |
| **Кому что можно** | Всем одно и то же | Дом, интернет или и то и другое, для каждого своё |
| **Конец доступа** | Найти и удалить его пиры | Дата, лимит трафика или один клик |
| **Что происходит** | Читать `wg show` | Кто в сети, трафик, места, журнал |
| **Когда что-то ломается** | Узнаёте от людей | Автовосстановление замечает и чинит |
Это преемник [Liminal]: та же идея, перестроенная вокруг людей, а не пиров, с
личным порталом, лимитами, трафиком в реальном времени и современной админкой
в LuCI.
## 🚀 Быстрый старт
1. **Установите** на роутер (установщик спрашивает, прежде чем что-то менять):
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
2. **Настройте** в LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, дальше по
мастеру. Он предложит порт, публичный адрес и сети.
3. **Пригласите** человека: <kbd>Добавить человека</kbd>, затем отправьте ему
ссылку или карточку приглашения с QR-кодом. Остальное он сделает сам.
> [!TIP]
> Если портал за Cloudflare, дайте ему порт, который Cloudflare проксирует:
> 2053, 2083, 2087, 2096 или 8443.
## ✨ Возможности
<table>
<tr>
<td width="50%" valign="top">
<h3>🔗 Ссылка вместо аккаунта</h3>
<p>Три слова, например <code>vpn.example.com/kamiro-telosu-bavine</code>. Ссылка и есть ключ: без регистрации и пароля, а новая ссылка сразу отключает старую.</p>
</td>
<td width="50%" valign="top">
<h3>📱 Свои устройства</h3>
<p>Люди сами добавляют, переименовывают и удаляют устройства в пределах лимита. При добавлении портал ведёт по шагам: нужное приложение, затем QR-код, ссылка, ключ или файл.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>👥 Люди, а не пиры</h3>
<p>Карточка на каждого человека: устройства, кто в сети, трафик, дата окончания и лимит. Фильтры по тем, кто требует внимания или на паузе.</p>
</td>
<td valign="top">
<h3>🧭 Кому что доступно</h3>
<p>Домашняя сеть, интернет или и то и другое; только часть домашних сетей или устройств (NAS, Home Assistant). Семья видит семью, гости видят гостей.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>⏳ Лимиты</h3>
<p>Даты окончания, лимит трафика на месяц или за всё время, часы доступа, кнопка паузы. Изменения применяются сразу и не обрывают подключения остальных.</p>
</td>
<td valign="top">
<h3>🕶️ Маскировка</h3>
<p>Пресеты, которые мешают распознать и заблокировать VPN-трафик, и что каждый из них требует от приложений.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🏠 Интернет как у домашних устройств</h3>
<p>Устройства людей выходят в интернет так же, как домашние, поэтому ваши прокси, фильтры рекламы и DNS работают и для них.</p>
</td>
<td valign="top">
<h3>🗺️ Обзор и места</h3>
<p>Кто в сети и с чего, скорость сейчас, последние 30 дней и карта, откуда подключаются, с точностью до города.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🩺 Чинит себя сам</h3>
<p>Проверки состояния с исправлением в один клик и автовосстановление, которое каждую минуту проверяет туннели, правила доступа и портал и чинит их.</p>
</td>
<td valign="top">
<h3>📦 Обновления и резервные копии</h3>
<p>Dawnline и AmneziaWG, собранный под вашу прошивку, в одном месте; ночные резервные копии, экспорт и импорт для переезда на другой роутер.</p>
</td>
</tr>
<tr>
<td valign="top">
<h3>🌐 Английский и русский</h3>
<p>Портал подстраивается под язык посетителя и переключается в шапке. Админка и сообщения роутера на русском с пакетом <code>luci-i18n-dawnline-ru</code>.</p>
</td>
<td valign="top"></td>
</tr>
</table>
## 🧩 Как это работает
```mermaid
flowchart LR
you(["🛠️ Вы, в LuCI"]) -- "добавляете человека" --> link["🔗 Его ссылка"]
link -- "он открывает её" --> portal["📱 Его портал"]
portal -- "добавляет устройство" --> app["Приложение и подключение"]
app == "туннель AmneziaWG" ==> router["🌅 Dawnline<br>на вашем роутере"]
router -- "если разрешено" --> home["🏠 Домашняя сеть"]
router -- "если разрешено" --> net["🌍 Интернет"]
```
1. **Вы добавляете человека** в LuCI и выбираете, что ему доступно, лимит
устройств, дату окончания или лимит трафика.
2. **Он открывает свою ссылку** на любом устройстве. Портал только его: там его
устройства и его доступ; доступ и лимиты меняете только вы.
3. **Он добавляет устройство.** Портал подсказывает приложение для его системы и
передаёт подключение; роутер выдаёт каждому устройству свои ключи.
4. **Устройство подключается** через сервер AmneziaWG на роутере, а Dawnline
пропускает только то, что доступно этому человеку, считает его трафик и
следит за лимитами.
## 📸 Как это выглядит
<p align="center">
<img src="docs/screenshots/overview.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
<br>
<sub><b>Обзор</b>: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.</sub>
</p>
<table>
<tr>
<td width="50%" valign="top">
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people.png">
<p align="center"><sub><b>Люди</b>: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.</sub></p>
</td>
<td width="50%" valign="top">
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person.png">
<p align="center"><sub><b>Человек</b>: его устройства, трафик, места и лимиты.</sub></p>
</td>
</tr>
</table>
## 📋 Требования
| | Что нужно Dawnline |
|---|---|
| **OpenWrt** | 24.10 (opkg, `.ipk`) или 25.12 (apk, `.apk`) |
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: если их нет, установщик поставит сборку для вашей прошивки |
| **Свободная флеш-память** | около 2 МБ |
## 📥 Установка
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
Установщик проверяет прошивку, часы, свободное место и DNS, даёт выбрать релиз
(по умолчанию последний), показывает план и спрашивает, прежде чем что-то
менять. Он скачивает пакет для вашего менеджера пакетов, сверяет его с
`sha256sums.txt`, ставит AmneziaWG для вашей прошивки, если его нет, затем
ставит Dawnline (с русским переводом, если LuCI на русском) и проверяет, что
LuCI его видит.
> [!NOTE]
> Прежде чем что-то менять, он сохраняет `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
> и состояние служб в `/etc/dawnline/installer-backups/` (хранятся три последние
> копии) и возвращает их, если какой-то шаг не удался. Пакеты не откатываются:
> чтобы вернуться к старому релизу, запустите установщик с `--tag`. Всё, что он
> делает, записывается в `/tmp/dawnline-install.log`.
<details>
<summary><b>Параметры установщика</b></summary>
<br>
С параметрами его нужно сначала скачать:
```sh
wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh
sh /tmp/dawnline-install.sh --dry-run # всё проверить, ничего не менять
sh /tmp/dawnline-install.sh -y --tag 0.3.1 # конкретный релиз, без вопросов
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG от 2Grey
sh /tmp/dawnline-install.sh --lang ru # с русским переводом админки
```
| Параметр | |
|---|---|
| `-y`, `--yes` | Без вопросов: последний релиз (или `--tag`) и рекомендуемые варианты |
| `-n`, `--dry-run` | Проверить систему, найти, скачать и проверить релиз; ничего не менять |
| `-v`, `--verbose` / `-q`, `--quiet` | Подробнее / только предупреждения и ошибки |
| `--tag X.Y.Z` | Конкретный релиз (`sh install.sh 0.3.1` тоже работает) |
| `--awg auto\|slava\|grey\|skip` | Откуда брать AmneziaWG, если его нет: [Slava-Shchipunov], затем [2Grey] (`auto`, по умолчанию), только один из них или вообще не ставить (потом можно в **Dawnline → Компоненты**). То же самое делает `DAWNLINE_AWG` |
| `--no-awg` | То же, что `--awg skip` |
| `--lang auto\|ru\|none` | Перевод админки, `luci-i18n-dawnline-<язык>`: `auto` (по умолчанию) ставит его, если LuCI настроен на этот язык или в нём стоит перевод LuCI на него; `none` не ставит. Уже установленный перевод всегда обновляется вместе с Dawnline. Позже: **Dawnline → Компоненты → Перевод**. То же самое делает `DAWNLINE_LANG` |
</details>
<details>
<summary><b>Если GitHub медленный или заблокирован</b></summary>
<br>
Установщик сам повторяет загрузки через `ghfast.top` и `gh-proxy.com`. Чтобы
скачать сам установщик через зеркало:
```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
</details>
<details>
<summary><b>Установка вручную</b></summary>
<br>
Из [релиза](https://github.com/tickcount/luci-app-dawnline/releases):
```sh
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
```
Русский перевод: `luci-i18n-dawnline-ru-<версия>` из того же релиза, ставится
так же, после приложения (затем `/etc/init.d/uhttpd restart`).
</details>
**Обновление**: в <kbd>Dawnline</kbd> › <kbd>Компоненты</kbd> или повторным
запуском установщика. Настройки, ключи и история сохраняются, перед обновлением
делается резервная копия.
### Удаление
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
```
Деинсталлятор сохраняет конфигурацию в `/etc/dawnline/backups`, запускает
удаление средствами самого Dawnline (как <kbd>Настройки</kbd> › <kbd>Удалить
Dawnline с этого роутера</kbd>), удаляет пакет и подчищает остатки. После
повторной установки Dawnline восстановите копию в <kbd>Настройки</kbd> ›
<kbd>Резервные копии</kbd>.
> [!IMPORTANT]
> AmneziaWG остаётся установленным: его могут использовать другие туннели.
> Чтобы удалить и его, добавьте `--remove-awg`.
<details>
<summary><b>Параметры деинсталлятора</b></summary>
<br>
С параметрами его нужно сначала скачать:
```sh
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
sh /tmp/dawnline-uninstall.sh --dry-run
```
| Параметр | |
|---|---|
| `-y`, `--yes` | Не спрашивать подтверждения |
| `-p`, `--purge` | Удалить также конфигурацию, ключи, историю и все резервные копии (`/etc/config/dawnline`, `/etc/dawnline`); копия не делается |
| `--remove-awg` | Удалить также AmneziaWG, если его не использует другой интерфейс (`--keep-awg`, по умолчанию, оставляет его) |
| `-n`, `--dry-run` | Показать, что будет удалено; ничего не менять |
Вручную: <kbd>Настройки</kbd> › <kbd>Удалить Dawnline с этого роутера</kbd>
(резервная копия сохраняется), затем `opkg remove luci-app-dawnline` или
`apk del luci-app-dawnline`.
</details>
## ❓ Вопросы и ответы
<details>
<summary><b>Какими приложениями пользуются люди?</b></summary>
<br>
AmneziaVPN или AmneziaWG на телефонах и компьютерах, а обычный WireGuard, если
маскировка выключена. Портал показывает каждому приложение для его системы и
как добавить в нём подключение.
</details>
<details>
<summary><b>Что делать, если человек потерял ссылку?</b></summary>
<br>
Создайте новую на его странице. Старая ссылка сразу перестанет работать; его
устройства продолжат работать, если не отметить те, что нужно удалить вместе с
ней.
</details>
<details>
<summary><b>Затрагивает ли он остальной роутер?</b></summary>
<br>
Только то, что создал сам, и `dawnline teardown` убирает всё это. Полный список:
[Что Dawnline меняет на роутере](#-что-dawnline-меняет-на-роутере).
</details>
<details>
<summary><b>Как переехать на другой роутер?</b></summary>
<br>
<kbd>Экспорт JSON</kbd> в <kbd>Настройки</kbd> › <kbd>Резервные копии</kbd> на
старом роутере, установите Dawnline на новый и импортируйте там этот файл.
</details>
<details>
<summary><b>Откуда берутся места на карте?</b></summary>
<br>
Из адреса, с которого подключается устройство: город определяется по нему и
кешируется на роутере. Это можно выключить в <kbd>Настройках</kbd>.
</details>
## 🧾 Что Dawnline меняет на роутере
Только то, что создал сам: сетевые интерфейсы с меткой `_dawnline`, секции
межсетевого экрана `dawnline_*`, таблицу nft `inet dawnline`, `/tmp/hosts/dawnline`,
сетевое пространство имён `dawnline` с двумя veth-связями (`dlx0` и `dll0`,
вторая подключена к мосту LAN и требует `kmod-veth`), правила маршрутизации для
интерфейсов туннелей с одной таблицей маршрутизации, второй экземпляр dnsmasq на
порту 5354 (`/var/etc/dawnline-dns.conf`), строку cron для проверки пульса
агента и, пока портал включён, экземпляр uhttpd для него. `dawnline teardown`
убирает всё это.
Данные хранятся в `/etc/config/dawnline` (права 0600, там приватные ключи) и в
`/etc/dawnline/` (трафик, события, выданные конфигурации, резервные копии).
Текущие счётчики живут в `/var/run/dawnline` и записываются во флеш-память не
чаще раза в час. Изменения доступа доходят до туннеля через `awg syncconf`, без
перезапуска интерфейса; `dawnline log` на роутере показывает журнал служб.
## 🧰 Разработка
```
package/luci-app-dawnline/
root/usr/share/ucode/dawnline/ библиотека на ucode: модель (core), AmneziaWG (awg), apply, live,
ops, view, loop, portal
root/usr/share/rpcd/ucode/ объект RPC luci.dawnline
root/usr/libexec/dawnline/ агент (трафик, лимиты, присутствие) и апдейтер
root/usr/share/dawnline/portal/ CGI-обёртка портала и его (минифицированные) файлы
root/usr/bin/dawnline командная строка (`dawnline help`)
htdocs/ представления LuCI и сгенерированный модуль dawnline/app.js
po/ каталог строк админки (dawnline.pot, ru/dawnline.po)
web/ исходники админки и портала на TypeScript
web/i18n/ инструменты каталогов: сбор строк, слияние .po, сборка .lmo
build/Dockerfile сборка пакетов в OpenWrt SDK
scripts/ скрипты сборки, деплоя и проверок
```
```sh
cd web
npm ci
npm run format # Prettier
npm run ci # форматирование, типы, каталоги, тесты, минифицированные бандлы
npm run i18n # собрать новые строки в каталоги (затем перевести их в ru.po)
scripts/lint-ucode.py # статические проверки ucode
scripts/check-ucode.sh root@router # скомпилировать все файлы ucode на роутере
scripts/deploy.sh root@router # поставить рабочую копию (сначала сохраняет конфиги)
scripts/build-packages.sh all # .ipk и .apk в OpenWrt SDK в Docker
scripts/capture-screenshots.mjs --demo # скриншоты для README с роутера, с демо-людьми вместо настоящих
scripts/frame-screenshots.py # оформить их для README
```
Бандлы и каталоги лежат в репозитории: CI падает, если они устарели или строка
не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
собирает пакеты и переводы в OpenWrt SDK и публикует релиз с `sha256sums.txt`.
---
<div align="center">
<sub>Сделано для OpenWrt · <a href="LICENSE">лицензия MIT</a> · <a href="#readme">Наверх ↑</a></sub>
</div>
[AmneziaWG]: https://docs.amnezia.org/
[Liminal]: https://github.com/tickcount/openwrt-liminal
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
[2Grey]: https://github.com/2Grey/awg-openwrt
+6 -2
View File
@@ -9,13 +9,17 @@ COPY package/luci-app-dawnline /builder/package/feeds/luci/luci-app-dawnline
# The SDK's default config builds every kernel module and every package in the # The SDK's default config builds every kernel module and every package in the
# feeds; turn that off and select only this package (it ships scripts and web # feeds; turn that off and select only this package (it ships scripts and web
# files, so nothing else needs building). # files, so nothing else needs building) and its translations: luci.mk makes
# luci-i18n-dawnline-<lang> from po/<lang> when LuCI's language <lang> is selected.
RUN make defconfig && \ RUN make defconfig && \
sed -i -e 's/^CONFIG_ALL_KMODS=y/# CONFIG_ALL_KMODS is not set/' \ sed -i -e 's/^CONFIG_ALL_KMODS=y/# CONFIG_ALL_KMODS is not set/' \
-e 's/^CONFIG_ALL_NONSHARED=y/# CONFIG_ALL_NONSHARED is not set/' \ -e 's/^CONFIG_ALL_NONSHARED=y/# CONFIG_ALL_NONSHARED is not set/' \
-e 's/^CONFIG_ALL=y/# CONFIG_ALL is not set/' .config && \ -e 's/^CONFIG_ALL=y/# CONFIG_ALL is not set/' .config && \
echo 'CONFIG_PACKAGE_luci-app-dawnline=m' >> .config && \ echo 'CONFIG_PACKAGE_luci-app-dawnline=m' >> .config && \
for l in $(ls /builder/package/feeds/luci/luci-app-dawnline/po | grep -v '^templates$'); do \
sed -i "/CONFIG_LUCI_LANG_$l[= ]/d" .config && echo "CONFIG_LUCI_LANG_$l=y" >> .config; done && \
make defconfig && \ make defconfig && \
make package/luci-app-dawnline/compile V=s -j4 && \ make package/luci-app-dawnline/compile V=s -j4 && \
mkdir -p /builder/out && \ mkdir -p /builder/out && \
find /builder/bin/packages -name 'luci-app-dawnline*' \( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \; find /builder/bin/packages \( -name 'luci-app-dawnline*' -o -name 'luci-i18n-dawnline-*' \) \
\( -name '*.ipk' -o -name '*.apk' \) -exec cp {} /builder/out/ \;
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#ffffff"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#0a0a0a"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0a0a0a" fill-opacity=".5"/></svg>

After

Width:  |  Height:  |  Size: 254 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#0a0a0a"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#ffffff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#ffffff" fill-opacity=".5"/></svg>

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 525 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 908 KiB

After

Width:  |  Height:  |  Size: 457 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 639 KiB

After

Width:  |  Height:  |  Size: 397 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 825 KiB

After

Width:  |  Height:  |  Size: 430 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 615 KiB

After

Width:  |  Height:  |  Size: 363 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 KiB

After

Width:  |  Height:  |  Size: 435 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 191 KiB

After

Width:  |  Height:  |  Size: 373 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 327 KiB

After

Width:  |  Height:  |  Size: 407 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 170 KiB

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

+143 -12
View File
@@ -9,7 +9,8 @@
# sh /tmp/dawnline-install.sh [options] [version] # sh /tmp/dawnline-install.sh [options] [version]
# #
# Installs AmneziaWG built for this firmware when it is missing, then the # Installs AmneziaWG built for this firmware when it is missing, then the
# Dawnline package with its dependencies from the OpenWrt feeds. Settings and # Dawnline package with its dependencies from the OpenWrt feeds, and the admin's
# translation when LuCI speaks that language (--lang). Settings and
# keys survive reinstalls and upgrades. A recovery snapshot of the configs it # keys survive reinstalls and upgrades. A recovery snapshot of the configs it
# may touch is taken first and restored if anything fails. `--help` lists the # may touch is taken first and restored if anything fails. `--help` lists the
# options. # options.
@@ -18,6 +19,8 @@ INSTALLER_VERSION="1.0.0"
REPO="${DAWNLINE_REPO:-tickcount/luci-app-dawnline}" REPO="${DAWNLINE_REPO:-tickcount/luci-app-dawnline}"
PKG_NAME="luci-app-dawnline" PKG_NAME="luci-app-dawnline"
AWG_PKGS="kmod-amneziawg amneziawg-tools luci-proto-amneziawg" AWG_PKGS="kmod-amneziawg amneziawg-tools luci-proto-amneziawg"
# The admin's translations a release has: luci-i18n-dawnline-<lang>.
I18N_LANGS="ru"
CONNECT_TIMEOUT=15 CONNECT_TIMEOUT=15
METADATA_TIMEOUT=60 METADATA_TIMEOUT=60
@@ -43,6 +46,7 @@ VERBOSE=0
QUIET=0 QUIET=0
TAG="" TAG=""
AWG_SOURCE="${DAWNLINE_AWG:-auto}" AWG_SOURCE="${DAWNLINE_AWG:-auto}"
I18N_CHOICE="${DAWNLINE_LANG:-auto}"
LOG_READY=0 LOG_READY=0
TMP_DIR="" TMP_DIR=""
@@ -67,6 +71,11 @@ WAS_ENABLED=0
WAS_RUNNING=0 WAS_RUNNING=0
MODE="install" MODE="install"
I18N_LANG=""
I18N_PKG=""
I18N_ASSET=""
I18N_FILE=""
AWG_ACTION="keep" AWG_ACTION="keep"
AWG_CANDIDATES="" AWG_CANDIDATES=""
AWG_REPO="" AWG_REPO=""
@@ -175,12 +184,18 @@ Usage: sh install.sh [options] [version]
grey 2Grey/awg-openwrt grey 2Grey/awg-openwrt
skip do not install it (add it later in Dawnline → Components) skip do not install it (add it later in Dawnline → Components)
--no-awg Same as --awg skip --no-awg Same as --awg skip
--lang LANG The admin's translation (luci-i18n-dawnline-LANG):
auto when LuCI is set to that language or has its
LuCI translation installed (default)
ru Russian
none add none (an installed one is kept up to date)
--version Print the installer version --version Print the installer version
-h, --help Show this help -h, --help Show this help
Environment: Environment:
DAWNLINE_REPO=owner/name GitHub repository with the releases ($REPO) DAWNLINE_REPO=owner/name GitHub repository with the releases ($REPO)
DAWNLINE_AWG=SOURCE Same as --awg (the option wins) DAWNLINE_AWG=SOURCE Same as --awg (the option wins)
DAWNLINE_LANG=LANG Same as --lang (the option wins)
DAWNLINE_SNAPSHOT_KEEP=N Recovery snapshots to keep (default 3) DAWNLINE_SNAPSHOT_KEEP=N Recovery snapshots to keep (default 3)
Log: $LOG_FILE Log: $LOG_FILE
@@ -214,6 +229,17 @@ set_awg() {
esac esac
} }
set_lang() {
for _l in auto none $I18N_LANGS; do
[ "$1" = "$_l" ] && {
I18N_CHOICE="$1"
return 0
}
done
err "Unknown language: $1 (auto, none or one of: $I18N_LANGS)"
return 1
}
parse_args() { parse_args() {
while [ "$#" -gt 0 ]; do while [ "$#" -gt 0 ]; do
case "$1" in case "$1" in
@@ -240,6 +266,15 @@ parse_args() {
;; ;;
--awg=*) set_awg "${1#*=}" || return 2 ;; --awg=*) set_awg "${1#*=}" || return 2 ;;
--no-awg) AWG_SOURCE="skip" ;; --no-awg) AWG_SOURCE="skip" ;;
--lang)
[ "$#" -gt 1 ] || {
err "--lang needs a language (auto, none or one of: $I18N_LANGS)"
return 2
}
shift
set_lang "$1" || return 2
;;
--lang=*) set_lang "${1#*=}" || return 2 ;;
--version) --version)
printf 'dawnline-installer %s\n' "$INSTALLER_VERSION" printf 'dawnline-installer %s\n' "$INSTALLER_VERSION"
exit 0 exit 0
@@ -268,6 +303,7 @@ parse_args() {
return 2 return 2
fi fi
set_awg "$AWG_SOURCE" || return 2 set_awg "$AWG_SOURCE" || return 2
set_lang "$I18N_CHOICE" || return 2
return 0 return 0
} }
@@ -895,6 +931,68 @@ resolve_release() {
fi fi
} }
lang_name() {
case "$1" in
ru) printf 'Russian' ;;
*) printf '%s' "$1" ;;
esac
}
# LuCI's language, when Dawnline has a translation for it: its setting, or with
# "auto" (the browser's) a LuCI translation that is installed (base.<lang>.lmo).
luci_lang() {
_ll="$(uci -q get luci.main.lang)"
for _l in $I18N_LANGS; do
case "$_ll" in "$_l" | "$_l"[_-]*)
printf '%s' "$_l"
return 0
;;
esac
done
case "$_ll" in '' | auto) ;; *) return 0 ;; esac
for _l in $I18N_LANGS; do
[ -f "/usr/lib/lua/luci/i18n/base.$_l.lmo" ] && {
printf '%s' "$_l"
return 0
}
done
return 0
}
# The admin's translation: an installed one is kept (it must match the app's
# version), else --lang or LuCI's own language decides.
resolve_i18n() {
I18N_LANG=""
for _l in $I18N_LANGS; do
pkg_is_installed "luci-i18n-dawnline-$_l" && I18N_LANG="$_l"
done
if [ -z "$I18N_LANG" ]; then
case "$I18N_CHOICE" in
none) ;;
auto) I18N_LANG="$(luci_lang)" ;;
*) I18N_LANG="$I18N_CHOICE" ;;
esac
fi
[ -n "$I18N_LANG" ] || return 0
I18N_PKG="luci-i18n-dawnline-$I18N_LANG"
I18N_ASSET="$I18N_PKG-$VERSION.$EXT"
_rj="$TMP_DIR/release.json"
if [ -s "$_rj" ]; then
_size="$(jsonfilter -i "$_rj" -e "@.assets[@.name='$I18N_ASSET'].size" 2>/dev/null | head -n 1)"
if [ -z "$_size" ]; then
# Releases before the translations have none.
warn "Release $VERSION has no $(lang_name "$I18N_LANG") translation: Dawnline stays in English"
I18N_LANG=""
I18N_PKG=""
I18N_ASSET=""
return 0
fi
DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + _size))
else
DOWNLOAD_BYTES=$((DOWNLOAD_BYTES + 262144))
fi
}
# AmneziaWG packages are built per firmware version and target by the # AmneziaWG packages are built per firmware version and target by the
# awg-openwrt projects: <name>_v<release>_<arch>_<target>_<subtarget>.<ext> # awg-openwrt projects: <name>_v<release>_<arch>_<target>_<subtarget>.<ext>
awg_postfix() { awg_postfix() {
@@ -981,6 +1079,11 @@ print_plan() {
downgrade) msg " Dawnline: downgrade $WAS_VERSION → $VERSION (a backup is made first)" ;; downgrade) msg " Dawnline: downgrade $WAS_VERSION → $VERSION (a backup is made first)" ;;
esac esac
msg " Package manager: $PKG_MANAGER ($ASSET)" msg " Package manager: $PKG_MANAGER ($ASSET)"
if [ -n "$I18N_PKG" ]; then
msg " Translation: $(lang_name "$I18N_LANG") ($I18N_PKG)"
else
msg " Translation: none (Russian: --lang ru)"
fi
case "$AWG_ACTION" in case "$AWG_ACTION" in
keep) msg " AmneziaWG: keep the installed one" ;; keep) msg " AmneziaWG: keep the installed one" ;;
skip) msg " AmneziaWG: skip (install it later from Dawnline → Components)" ;; skip) msg " AmneziaWG: skip (install it later from Dawnline → Components)" ;;
@@ -1011,28 +1114,37 @@ confirm() {
# ---------- download phase ---------- # ---------- download phase ----------
download_dawnline() { # download_release_file NAME: one file of the release into $TMP_DIR, verified.
download_release_file() {
_name="$1"
_sums="$TMP_DIR/sha256sums.txt" _sums="$TMP_DIR/sha256sums.txt"
ASSET_FILE="$TMP_DIR/$ASSET"
# The checksum: GitHub's own (API), else the release's sha256sums.txt straight from github.com. # The checksum: GitHub's own (API), else the release's sha256sums.txt straight from github.com.
_want="$(asset_digest "$TMP_DIR/release.json" "$ASSET")" _want="$(asset_digest "$TMP_DIR/release.json" "$_name")"
if [ -z "$_want" ]; then if [ -z "$_want" ]; then
download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || { [ -s "$_sums" ] || download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || {
err "Download failed: sha256sums.txt (does release $VERSION exist?)" err "Download failed: sha256sums.txt (does release $VERSION exist?)"
return 1 return 1
} }
_want="$(awk -v f="$ASSET" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")" _want="$(awk -v f="$_name" '$2 == f || $2 == "*" f { print $1; exit }' "$_sums")"
[ -n "$_want" ] || { [ -n "$_want" ] || {
err "sha256sums.txt has no entry for $ASSET: not installing an unverified package" err "sha256sums.txt has no entry for $_name: not installing an unverified package"
return 1 return 1
} }
fi fi
download "$ASSET_BASE/$ASSET" "$ASSET_FILE" "$ASSET" "$_want" || { download "$ASSET_BASE/$_name" "$TMP_DIR/$_name" "$_name" "$_want" || {
err "Download failed: $ASSET" err "Download failed: $_name"
return 1 return 1
} }
verify_archive "$ASSET_FILE" || return 1 verify_archive "$TMP_DIR/$_name" || return 1
ok "$ASSET verified (sha256, package format)" ok "$_name verified (sha256, package format)"
}
download_dawnline() {
download_release_file "$ASSET" || return 1
ASSET_FILE="$TMP_DIR/$ASSET"
[ -n "$I18N_ASSET" ] || return 0
download_release_file "$I18N_ASSET" || return 1
I18N_FILE="$TMP_DIR/$I18N_ASSET"
} }
download_awg() { download_awg() {
@@ -1156,11 +1268,16 @@ install_dawnline() {
_force=0 _force=0
case "$MODE" in reinstall | downgrade) _force=1 ;; esac case "$MODE" in reinstall | downgrade) _force=1 ;; esac
if [ "$DRY_RUN" -eq 1 ]; then if [ "$DRY_RUN" -eq 1 ]; then
dry "$MODE Dawnline $VERSION ($ASSET)" dry "$MODE Dawnline $VERSION ($ASSET${I18N_ASSET:+, $I18N_ASSET})"
return 0 return 0
fi fi
msg "Installing Dawnline $VERSION" msg "Installing Dawnline $VERSION"
# The translation in the same transaction: it depends on this very version.
if [ -n "$I18N_FILE" ]; then
pkg_install_files dawnline "$_force" "$ASSET_FILE" "$I18N_FILE"
else
pkg_install_files dawnline "$_force" "$ASSET_FILE" pkg_install_files dawnline "$_force" "$ASSET_FILE"
fi
} }
healthcheck() { healthcheck() {
@@ -1201,6 +1318,9 @@ healthcheck() {
if [ "$_r" != true ]; then if [ "$_r" != true ]; then
warn "The Dawnline agent is not running yet (see Dawnline → Diagnostics)" warn "The Dawnline agent is not running yet (see Dawnline → Diagnostics)"
fi fi
if [ -n "$I18N_PKG" ] && [ "$(pkg_version "$I18N_PKG")" != "$VERSION" ]; then
warn "$I18N_PKG $VERSION is not installed: Dawnline shows in English"
fi
ok "Healthcheck passed: $PKG_NAME $VERSION, LuCI backend answers" ok "Healthcheck passed: $PKG_NAME $VERSION, LuCI backend answers"
} }
@@ -1215,6 +1335,15 @@ keep_service_intent() {
return 0 return 0
} }
# LuCI reads a language's catalogs once per web server process: a new or
# replaced translation needs a fresh one.
reload_luci() {
[ "$DRY_RUN" -eq 0 ] && [ -n "$I18N_FILE" ] || return 0
msg "Restarting the web server so LuCI reads the translation"
/etc/init.d/uhttpd restart >/dev/null 2>&1 ||
warn "uhttpd did not restart: the translation shows after a reboot"
}
commit_transaction() { commit_transaction() {
TX_COMMITTED=1 TX_COMMITTED=1
TX_ACTIVE=0 TX_ACTIVE=0
@@ -1328,6 +1457,7 @@ main() {
select_release select_release
resolve_release || fail "Could not resolve the Dawnline release" resolve_release || fail "Could not resolve the Dawnline release"
resolve_i18n
resolve_awg || fail "AmneziaWG is not available for this firmware" resolve_awg || fail "AmneziaWG is not available for this firmware"
check_tmp_space || fail "Not enough free memory for the downloads" check_tmp_space || fail "Not enough free memory for the downloads"
print_plan print_plan
@@ -1348,6 +1478,7 @@ main() {
healthcheck || fail "The installed Dawnline did not pass the healthcheck" healthcheck || fail "The installed Dawnline did not pass the healthcheck"
keep_service_intent keep_service_intent
commit_transaction commit_transaction
reload_luci
trap on_hup HUP trap on_hup HUP
_took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS)) _took=$(($(date +%s 2>/dev/null || echo "$START_TS") - START_TS))
+4 -1
View File
@@ -6,9 +6,12 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.7.0 PKG_VERSION:=0.12.1
PKG_RELEASE:=1 PKG_RELEASE:=1
PKG_LICENSE:=MIT PKG_LICENSE:=MIT
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
# with the app and at its version (luci.mk would take a git revision otherwise).
PKG_PO_VERSION:=$(PKG_VERSION)-r$(PKG_RELEASE)
LUCI_TITLE:=Dawnline - AmneziaWG access server LUCI_TITLE:=Dawnline - AmneziaWG access server
# AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not # AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not
@@ -5,25 +5,27 @@
'require poll'; 'require poll';
'require rpc'; 'require rpc';
'require ui'; 'require ui';
var gr=Object.create;var ao=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,wr=Object.prototype.hasOwnProperty;var yr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var kr=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of br(e))!wr.call(n,r)&&r!==o&&ao(n,r,{get:()=>e[r],enumerable:!(a=vr(e,r))||a.enumerable});return n};var $r=(n,e,o)=>(o=n!=null?gr(xr(n)):{},kr(e||!n||!n.__esModule?ao(o,"default",{value:n,enumerable:!0}):o,n));var bo=yr((go,vo)=>{"use strict";var fo=(function(){var n=function(E,y){var S=236,b=17,x=E,M=o[y],h=null,f=0,R=null,C=[],I={},Q=function(T,A){f=x*4+17,h=(function($){for(var H=new Array($),_=0;_<$;_+=1){H[_]=new Array($);for(var j=0;j<$;j+=1)H[_][j]=null}return H})(f),G(0,0),G(f-7,0),G(0,f-7),K(),z(),ce(T,A),x>=7&&X(T),R==null&&(R=U(x,M,C)),fe(R,A)},G=function(T,A){for(var $=-1;$<=7;$+=1)if(!(T+$<=-1||f<=T+$))for(var H=-1;H<=7;H+=1)A+H<=-1||f<=A+H||(0<=$&&$<=6&&(H==0||H==6)||0<=H&&H<=6&&($==0||$==6)||2<=$&&$<=4&&2<=H&&H<=4?h[T+$][A+H]=!0:h[T+$][A+H]=!1)},Y=function(){for(var T=0,A=0,$=0;$<8;$+=1){Q(!0,$);var H=r.getLostPoint(I);($==0||T>H)&&(T=H,A=$)}return A},z=function(){for(var T=8;T<f-8;T+=1)h[T][6]==null&&(h[T][6]=T%2==0);for(var A=8;A<f-8;A+=1)h[6][A]==null&&(h[6][A]=A%2==0)},K=function(){for(var T=r.getPatternPosition(x),A=0;A<T.length;A+=1)for(var $=0;$<T.length;$+=1){var H=T[A],_=T[$];if(h[H][_]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[H+j][_+Z]=!0:h[H+j][_+Z]=!1}},X=function(T){for(var A=r.getBCHTypeNumber(x),$=0;$<18;$+=1){var H=!T&&(A>>$&1)==1;h[Math.floor($/3)][$%3+f-8-3]=H}for(var $=0;$<18;$+=1){var H=!T&&(A>>$&1)==1;h[$%3+f-8-3][Math.floor($/3)]=H}},ce=function(T,A){for(var $=M<<3|A,H=r.getBCHTypeInfo($),_=0;_<15;_+=1){var j=!T&&(H>>_&1)==1;_<6?h[_][8]=j:_<8?h[_+1][8]=j:h[f-15+_][8]=j}for(var _=0;_<15;_+=1){var j=!T&&(H>>_&1)==1;_<8?h[8][f-_-1]=j:_<9?h[8][15-_-1+1]=j:h[8][15-_-1]=j}h[f-8][8]=!T},fe=function(T,A){for(var $=-1,H=f-1,_=7,j=0,Z=r.getMaskFunction(A),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var pe=0;pe<2;pe+=1)if(h[H][V-pe]==null){var be=!1;j<T.length&&(be=(T[j]>>>_&1)==1);var ee=Z(H,V-pe);ee&&(be=!be),h[H][V-pe]=be,_-=1,_==-1&&(j+=1,_=7)}if(H+=$,H<0||f<=H){H-=$,$=-$;break}}},O=function(T,A){for(var $=0,H=0,_=0,j=new Array(A.length),Z=new Array(A.length),V=0;V<A.length;V+=1){var pe=A[V].dataCount,be=A[V].totalCount-pe;H=Math.max(H,pe),_=Math.max(_,be),j[V]=new Array(pe);for(var ee=0;ee<j[V].length;ee+=1)j[V][ee]=255&T.getBuffer()[ee+$];$+=pe;var Te=r.getErrorCorrectPolynomial(be),_e=s(j[V],Te.getLength()-1),to=_e.mod(Te);Z[V]=new Array(Te.getLength()-1);for(var ee=0;ee<Z[V].length;ee+=1){var no=ee+to.getLength()-Z[V].length;Z[V][ee]=no>=0?to.getAt(no):0}}for(var oo=0,ee=0;ee<A.length;ee+=1)oo+=A[ee].totalCount;for(var Mn=new Array(oo),Wt=0,ee=0;ee<H;ee+=1)for(var V=0;V<A.length;V+=1)ee<j[V].length&&(Mn[Wt]=j[V][ee],Wt+=1);for(var ee=0;ee<_;ee+=1)for(var V=0;V<A.length;V+=1)ee<Z[V].length&&(Mn[Wt]=Z[V][ee],Wt+=1);return Mn},U=function(T,A,$){for(var H=l.getRSBlocks(T,A),_=c(),j=0;j<$.length;j+=1){var Z=$[j];_.put(Z.getMode(),4),_.put(Z.getLength(),r.getLengthInBits(Z.getMode(),T)),Z.write(_)}for(var V=0,j=0;j<H.length;j+=1)V+=H[j].dataCount;if(_.getLengthInBits()>V*8)throw"code length overflow. ("+_.getLengthInBits()+">"+V*8+")";for(_.getLengthInBits()+4<=V*8&&_.put(0,4);_.getLengthInBits()%8!=0;)_.putBit(!1);for(;!(_.getLengthInBits()>=V*8||(_.put(S,8),_.getLengthInBits()>=V*8));)_.put(b,8);return O(_,H)};I.addData=function(T,A){A=A||"Byte";var $=null;switch(A){case"Numeric":$=d(T);break;case"Alphanumeric":$=p(T);break;case"Byte":$=u(T);break;case"Kanji":$=w(T);break;default:throw"mode:"+A}C.push($),R=null},I.isDark=function(T,A){if(T<0||f<=T||A<0||f<=A)throw T+","+A;return h[T][A]},I.getModuleCount=function(){return f},I.make=function(){if(x<1){for(var T=1;T<40;T++){for(var A=l.getRSBlocks(T,M),$=c(),H=0;H<C.length;H++){var _=C[H];$.put(_.getMode(),4),$.put(_.getLength(),r.getLengthInBits(_.getMode(),T)),_.write($)}for(var j=0,H=0;H<A.length;H++)j+=A[H].dataCount;if($.getLengthInBits()<=j*8)break}x=T}Q(!1,Y())},I.createTableTag=function(T,A){T=T||2,A=typeof A>"u"?T*4:A;var $="";$+='<table style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: "+A+"px;",$+='">',$+="<tbody>";for(var H=0;H<I.getModuleCount();H+=1){$+="<tr>";for(var _=0;_<I.getModuleCount();_+=1)$+='<td style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: 0px;",$+=" width: "+T+"px;",$+=" height: "+T+"px;",$+=" background-color: ",$+=I.isDark(H,_)?"#000000":"#ffffff",$+=";",$+='"/>';$+="</tr>"}return $+="</tbody>",$+="</table>",$},I.createSvgTag=function(T,A,$,H){var _={};typeof arguments[0]=="object"&&(_=arguments[0],T=_.cellSize,A=_.margin,$=_.alt,H=_.title),T=T||2,A=typeof A>"u"?T*4:A,$=typeof $=="string"?{text:$}:$||{},$.Line truncated var Ha=Object.create;var Go=Object.defineProperty;var za=Object.getOwnPropertyDescriptor;var Ra=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,Ba=Object.prototype.hasOwnProperty;var Oa=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ja=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ra(e))!Ba.call(n,r)&&r!==o&&Go(n,r,{get:()=>e[r],enumerable:!(s=za(e,r))||s.enumerable});return n};var Ua=(n,e,o)=>(o=n!=null?Ha(Ia(n)):{},ja(e||!n||!n.__esModule?Go(o,"default",{value:n,enumerable:!0}):o,n));var os=Oa((ts,ns)=>{"use strict";var es=(function(){var n=function(S,$){var b=236,C=17,y=S,z=o[$],k=null,f=0,x=null,T=[],I={},V=function(R,O){f=y*4+17,k=(function(P){for(var U=new Array(P),D=0;D<P;D+=1){U[D]=new Array(P);for(var G=0;G<P;G+=1)U[D][G]=null}return U})(f),J(0,0),J(f-7,0),J(0,f-7),Q(),B(),fe(R,O),y>=7&&ne(R),x==null&&(x=Y(y,z,T)),oe(x,O)},J=function(R,O){for(var P=-1;P<=7;P+=1)if(!(R+P<=-1||f<=R+P))for(var U=-1;U<=7;U+=1)O+U<=-1||f<=O+U||(0<=P&&P<=6&&(U==0||U==6)||0<=U&&U<=6&&(P==0||P==6)||2<=P&&P<=4&&2<=U&&U<=4?k[R+P][O+U]=!0:k[R+P][O+U]=!1)},te=function(){for(var R=0,O=0,P=0;P<8;P+=1){V(!0,P);var U=r.getLostPoint(I);(P==0||R>U)&&(R=U,O=P)}return O},B=function(){for(var R=8;R<f-8;R+=1)k[R][6]==null&&(k[R][6]=R%2==0);for(var O=8;O<f-8;O+=1)k[6][O]==null&&(k[6][O]=O%2==0)},Q=function(){for(var R=r.getPatternPosition(y),O=0;O<R.length;O+=1)for(var P=0;P<R.length;P+=1){var U=R[O],D=R[P];if(k[U][D]==null)for(var G=-2;G<=2;G+=1)for(var ee=-2;ee<=2;ee+=1)G==-2||G==2||ee==-2||ee==2||G==0&&ee==0?k[U+G][D+ee]=!0:k[U+G][D+ee]=!1}},ne=function(R){for(var O=r.getBCHTypeNumber(y),P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;k[Math.floor(P/3)][P%3+f-8-3]=U}for(var P=0;P<18;P+=1){var U=!R&&(O>>P&1)==1;k[P%3+f-8-3][Math.floor(P/3)]=U}},fe=function(R,O){for(var P=z<<3|O,U=r.getBCHTypeInfo(P),D=0;D<15;D+=1){var G=!R&&(U>>D&1)==1;D<6?k[D][8]=G:D<8?k[D+1][8]=G:k[f-15+D][8]=G}for(var D=0;D<15;D+=1){var G=!R&&(U>>D&1)==1;D<8?k[8][f-D-1]=G:D<9?k[8][15-D-1+1]=G:k[8][15-D-1]=G}k[f-8][8]=!R},oe=function(R,O){for(var P=-1,U=f-1,D=7,G=0,ee=r.getMaskFunction(O),X=f-1;X>0;X-=2)for(X==6&&(X-=1);;){for(var be=0;be<2;be+=1)if(k[U][X-be]==null){var Le=!1;G<R.length&&(Le=(R[G]>>>D&1)==1);var re=ee(U,X-be);re&&(Le=!Le),k[U][X-be]=Le,D-=1,D==-1&&(G+=1,D=7)}if(U+=P,U<0||f<=U){U-=P,P=-P;break}}},j=function(R,O){for(var P=0,U=0,D=0,G=new Array(O.length),ee=new Array(O.length),X=0;X<O.length;X+=1){var be=O[X].dataCount,Le=O[X].totalCount-be;U=Math.max(U,be),D=Math.max(D,Le),G[X]=new Array(be);for(var re=0;re<G[X].length;re+=1)G[X][re]=255&R.getBuffer()[re+P];P+=be;var Ie=r.getErrorCorrectPolynomial(Le),Be=i(G[X],Ie.getLength()-1),jo=Be.mod(Ie);ee[X]=new Array(Ie.getLength()-1);for(var re=0;re<ee[X].length;re+=1){var Uo=re+jo.getLength()-ee[X].length;ee[X][re]=Uo>=0?jo.getAt(Uo):0}}for(var Wo=0,re=0;re<O.length;re+=1)Wo+=O[re].totalCount;for(var Vn=new Array(Wo),rn=0,re=0;re<U;re+=1)for(var X=0;X<O.length;X+=1)re<G[X].length&&(Vn[rn]=G[X][re],rn+=1);for(var re=0;re<D;re+=1)for(var X=0;X<O.length;X+=1)re<ee[X].length&&(Vn[rn]=ee[X][re],rn+=1);return Vn},Y=function(R,O,P){for(var U=l.getRSBlocks(R,O),D=d(),G=0;G<P.length;G+=1){var ee=P[G];D.put(ee.getMode(),4),D.put(ee.getLength(),r.getLengthInBits(ee.getMode(),R)),ee.write(D)}for(var X=0,G=0;G<U.length;G+=1)X+=U[G].dataCount;if(D.getLengthInBits()>X*8)throw"code length overflow. ("+D.getLengthInBits()+">"+X*8+")";for(D.getLengthInBits()+4<=X*8&&D.put(0,4);D.getLengthInBits()%8!=0;)D.putBit(!1);for(;!(D.getLengthInBits()>=X*8||(D.put(b,8),D.getLengthInBits()>=X*8));)D.put(C,8);return j(D,U)};I.addData=function(R,O){O=O||"Byte";var P=null;switch(O){case"Numeric":P=c(R);break;case"Alphanumeric":P=p(R);break;case"Byte":P=u(R);break;case"Kanji":P=w(R);break;default:throw"mode:"+O}T.push(P),x=null},I.isDark=function(R,O){if(R<0||f<=R||O<0||f<=O)throw R+","+O;return k[R][O]},I.getModuleCount=function(){return f},I.make=function(){if(y<1){for(var R=1;R<40;R++){for(var O=l.getRSBlocks(R,z),P=d(),U=0;U<T.length;U++){var D=T[U];P.put(D.getMode(),4),P.put(D.getLength(),r.getLengthInBits(D.getMode(),R)),D.write(P)}for(var G=0,U=0;U<O.length;U++)G+=O[U].dataCount;if(P.getLengthInBits()<=G*8)break}y=R}V(!1,te())},I.createTableTag=function(R,O){R=R||2,O=typeof O>"u"?R*4:O;var P="";P+='<table style="',P+=" border-width: 0px; border-style: none;",P+=" border-collapse: collapse;",P+=" padding: 0px; margin: "+O+"px;",P+='">',P+="<tbody>";for(var U=0;U<I.getModuleCount();U+=1){P+="<tr>";for(var D=0;D<I.getModuleCount();D+=1)P+='<td style="',P+=" border-width: 0px; border-style: none;",P+=" border-collapse: collapse;",P+=" padding: 0px; margin: 0px;",P+=" width: "+R+"px;",P+=" height: "+R+"px;",P+=" background-color: ",P+=I.isDark(U,D)?"#000000":"#ffffff",P+=";",P+='"/>';P+="</tr>"}return P+="</tbody>",P+="</table>",P},I.createSvgTag=function(R,O,P,U){var D={};typeof arguments[0]=="object"&&(D=arguments[0],R=D.cellSize,O=D.margin,P=D.alt,U=D.title),R=R||2,O=typeof O>"u"?R*4:O,P=typeof P==Line truncated
`}return $%2&&T>0?_e.substring(0,_e.length-$-1)+Array($+1).join("▀"):_e.substring(0,_e.length-1)};return I.createASCII=function(T,A){if(T=T||1,T<2)return oe(A);T-=1,A=typeof A>"u"?T*2:A;var $=I.getModuleCount()*T+A*2,H=A,_=$-A,j,Z,V,pe,be=Array(T+1).join("██"),ee=Array(T+1).join(" "),Te="",_e="";for(j=0;j<$;j+=1){for(V=Math.floor((j-H)/T),_e="",Z=0;Z<$;Z+=1)pe=1,H<=Z&&Z<_&&H<=j&&j<_&&I.isDark(V,Math.floor((Z-H)/T))&&(pe=0),_e+=pe?be:ee;for(V=0;V<T;V+=1)Te+=_e+` `}return P%2&&R>0?Be.substring(0,Be.length-P-1)+Array(P+1).join("▀"):Be.substring(0,Be.length-1)};return I.createASCII=function(R,O){if(R=R||1,R<2)return ve(O);R-=1,O=typeof O>"u"?R*2:O;var P=I.getModuleCount()*R+O*2,U=O,D=P-O,G,ee,X,be,Le=Array(R+1).join("██"),re=Array(R+1).join(" "),Ie="",Be="";for(G=0;G<P;G+=1){for(X=Math.floor((G-U)/R),Be="",ee=0;ee<P;ee+=1)be=1,U<=ee&&ee<D&&U<=G&&G<D&&I.isDark(X,Math.floor((ee-U)/R))&&(be=0),Be+=be?Le:re;for(X=0;X<R;X+=1)Ie+=Be+`
`}return Te.substring(0,Te.length-1)},I.renderTo2dContext=function(T,A){A=A||2;for(var $=I.getModuleCount(),H=0;H<$;H++)for(var _=0;_<$;_++)T.fillStyle=I.isDark(H,_)?"black":"white",T.fillRect(H*A,_*A,A,A)},I};n.stringToBytesFuncs={default:function(E){for(var y=[],S=0;S<E.length;S+=1){var b=E.charCodeAt(S);y.push(b&255)}return y}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,y){var S=(function(){for(var x=k(E),M=function(){var z=x.read();if(z==-1)throw"eof";return z},h=0,f={};;){var R=x.read();if(R==-1)break;var C=M(),I=M(),Q=M(),G=String.fromCharCode(R<<8|C),Y=I<<8|Q;f[G]=Y,h+=1}if(h!=y)throw h+" != "+y;return f})(),b=63;return function(x){for(var M=[],h=0;h<x.length;h+=1){var f=x.charCodeAt(h);if(f<128)M.push(f);else{var R=S[x.charAt(h)];typeof R=="number"?(R&255)==R?M.push(R):(M.push(R>>>8),M.push(R&255)):M.push(b)}}return M}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],y=1335,S=7973,b=21522,x={},M=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return x.getBCHTypeInfo=function(h){for(var f=h<<10;M(f)-M(y)>=0;)f^=y<<M(f)-M(y);return(h<<10|f)^b},x.getBCHTypeNumber=function(h){for(var f=h<<12;M(f)-M(S)>=0;)f^=S<<M(f)-M(S);return h<<12|f},x.getPatternPosition=function(h){return E[h-1]},x.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(f,R){return(f+R)%2==0};case a.PATTERN001:return function(f,R){return f%2==0};case a.PATTERN010:return function(f,R){return R%3==0};case a.PATTERN011:return function(f,R){return(f+R)%3==0};case a.PATTERN100:return function(f,R){return(Math.floor(f/2)+Math.floor(R/3))%2==0};case a.PATTERN101:return function(f,R){return f*R%2+f*R%3==0};case a.PATTERN110:return function(f,R){return(f*R%2+f*R%3)%2==0};case a.PATTERN111:return function(f,R){return(f*R%3+(f+R)%2)%2==0};default:throw"bad maskPattern:"+h}},x.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),R=0;R<h;R+=1)f=f.multiply(s([1,i.gexp(R)],0));return f},x.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},x.getLostPoint=function(h){for(var f=h.getModuleCount(),R=0,C=0;C<f;C+=1)for(var I=0;I<f;I+=1){for(var Q=0,G=h.isDark(C,I),Y=-1;Y<=1;Y+=1)if(!(C+Y<0||f<=C+Y))for(var z=-1;z<=1;z+=1)I+z<0||f<=I+z||Y==0&&z==0||G==h.isDark(C+Y,I+z)&&(Q+=1);Q>5&&(R+=3+Q-5)}for(var C=0;C<f-1;C+=1)for(var I=0;I<f-1;I+=1){var K=0;h.isDark(C,I)&&(K+=1),h.isDark(C+1,I)&&(K+=1),h.isDark(C,I+1)&&(K+=1),h.isDark(C+1,I+1)&&(K+=1),(K==0||K==4)&&(R+=3)}for(var C=0;C<f;C+=1)for(var I=0;I<f-6;I+=1)h.isDark(C,I)&&!h.isDark(C,I+1)&&h.isDark(C,I+2)&&h.isDark(C,I+3)&&h.isDark(C,I+4)&&!h.isDark(C,I+5)&&h.isDark(C,I+6)&&(R+=40);for(var I=0;I<f;I+=1)for(var C=0;C<f-6;C+=1)h.isDark(C,I)&&!h.isDark(C+1,I)&&h.isDark(C+2,I)&&h.isDark(C+3,I)&&h.isDark(C+4,I)&&!h.isDark(C+5,I)&&h.isDark(C+6,I)&&(R+=40);for(var X=0,I=0;I<f;I+=1)for(var C=0;C<f;C+=1)h.isDark(C,I)&&(X+=1);var ce=Math.abs(100*X/f/f-50)/5;return R+=ce*10,R},x})(),i=(function(){for(var E=new Array(256),y=new Array(256),S=0;S<8;S+=1)E[S]=1<<S;for(var S=8;S<256;S+=1)E[S]=E[S-4]^E[S-5]^E[S-6]^E[S-8];for(var S=0;S<255;S+=1)y[E[S]]=S;var b={};return b.glog=function(x){if(x<1)throw"glog("+x+")";return y[x]},b.gexp=function(x){for(;x<0;)x+=255;for(;x>=256;)x-=255;return E[x]},b})();function s(E,y){if(typeof E.length>"u")throw E.length+"/"+y;var S=(function(){for(var x=0;x<E.length&&E[x]==0;)x+=1;for(var M=new Array(E.length-x+y),h=0;h<E.length-x;h+=1)M[h]=E[h+x];return M})(),b={};return b.getAt=function(x){return S[x]},b.getLength=function(){return S.length},b.multiply=function(x){for(var M=new Array(b.getLength()+x.getLength()-1),h=0;h<b.getLength();h+=1)for(var f=0;f<x.getLength();f+=1)M[h+f]^=i.gexp(i.glog(b.getAt(h))+i.glog(x.getAt(f)));return s(M,0)},b.mod=function(x){if(b.getLength() Line truncated `}return Ie.substring(0,Ie.length-1)},I.renderTo2dContext=function(R,O){O=O||2;for(var P=I.getModuleCount(),U=0;U<P;U++)for(var D=0;D<P;D++)R.fillStyle=I.isDark(U,D)?"black":"white",R.fillRect(U*O,D*O,O,O)},I};n.stringToBytesFuncs={default:function(S){for(var $=[],b=0;b<S.length;b+=1){var C=S.charCodeAt(b);$.push(C&255)}return $}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(S,$){var b=(function(){for(var y=h(S),z=function(){var B=y.read();if(B==-1)throw"eof";return B},k=0,f={};;){var x=y.read();if(x==-1)break;var T=z(),I=z(),V=z(),J=String.fromCharCode(x<<8|T),te=I<<8|V;f[J]=te,k+=1}if(k!=$)throw k+" != "+$;return f})(),C=63;return function(y){for(var z=[],k=0;k<y.length;k+=1){var f=y.charCodeAt(k);if(f<128)z.push(f);else{var x=b[y.charAt(k)];typeof x=="number"?(x&255)==x?z.push(x):(z.push(x>>>8),z.push(x&255)):z.push(C)}}return z}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var S=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],$=1335,b=7973,C=21522,y={},z=function(k){for(var f=0;k!=0;)f+=1,k>>>=1;return f};return y.getBCHTypeInfo=function(k){for(var f=k<<10;z(f)-z($)>=0;)f^=$<<z(f)-z($);return(k<<10|f)^C},y.getBCHTypeNumber=function(k){for(var f=k<<12;z(f)-z(b)>=0;)f^=b<<z(f)-z(b);return k<<12|f},y.getPatternPosition=function(k){return S[k-1]},y.getMaskFunction=function(k){switch(k){case s.PATTERN000:return function(f,x){return(f+x)%2==0};case s.PATTERN001:return function(f,x){return f%2==0};case s.PATTERN010:return function(f,x){return x%3==0};case s.PATTERN011:return function(f,x){return(f+x)%3==0};case s.PATTERN100:return function(f,x){return(Math.floor(f/2)+Math.floor(x/3))%2==0};case s.PATTERN101:return function(f,x){return f*x%2+f*x%3==0};case s.PATTERN110:return function(f,x){return(f*x%2+f*x%3)%2==0};case s.PATTERN111:return function(f,x){return(f*x%3+(f+x)%2)%2==0};default:throw"bad maskPattern:"+k}},y.getErrorCorrectPolynomial=function(k){for(var f=i([1],0),x=0;x<k;x+=1)f=f.multiply(i([1,a.gexp(x)],0));return f},y.getLengthInBits=function(k,f){if(1<=f&&f<10)switch(k){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+k}else if(f<27)switch(k){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+k}else if(f<41)switch(k){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+k}else throw"type:"+f},y.getLostPoint=function(k){for(var f=k.getModuleCount(),x=0,T=0;T<f;T+=1)for(var I=0;I<f;I+=1){for(var V=0,J=k.isDark(T,I),te=-1;te<=1;te+=1)if(!(T+te<0||f<=T+te))for(var B=-1;B<=1;B+=1)I+B<0||f<=I+B||te==0&&B==0||J==k.isDark(T+te,I+B)&&(V+=1);V>5&&(x+=3+V-5)}for(var T=0;T<f-1;T+=1)for(var I=0;I<f-1;I+=1){var Q=0;k.isDark(T,I)&&(Q+=1),k.isDark(T+1,I)&&(Q+=1),k.isDark(T,I+1)&&(Q+=1),k.isDark(T+1,I+1)&&(Q+=1),(Q==0||Q==4)&&(x+=3)}for(var T=0;T<f;T+=1)for(var I=0;I<f-6;I+=1)k.isDark(T,I)&&!k.isDark(T,I+1)&&k.isDark(T,I+2)&&k.isDark(T,I+3)&&k.isDark(T,I+4)&&!k.isDark(T,I+5)&&k.isDark(T,I+6)&&(x+=40);for(var I=0;I<f;I+=1)for(var T=0;T<f-6;T+=1)k.isDark(T,I)&&!k.isDark(T+1,I)&&k.isDark(T+2,I)&&k.isDark(T+3,I)&&k.isDark(T+4,I)&&!k.isDark(T+5,I)&&k.isDark(T+6,I)&&(x+=40);for(var ne=0,I=0;I<f;I+=1)for(var T=0;T<f;T+=1)k.isDark(T,I)&&(ne+=1);var fe=Math.abs(100*ne/f/f-50)/5;return x+=fe*10,x},y})(),a=(function(){for(var S=new Array(256),$=new Array(256),b=0;b<8;b+=1)S[b]=1<<b;for(var b=8;b<256;b+=1)S[b]=S[b-4]^S[b-5]^S[b-6]^S[b-8];for(var b=0;b<255;b+=1)$[S[b]]=b;var C={};return C.glog=function(y){if(y<1)throw"glog("+y+")";return $[y]},C.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return S[y]},C})();function i(S,$){if(typeof S.length>"u")throw S.length+"/"+$;var b=(function(){for(var y=0;y<S.length&&S[y]==0;)y+=1;for(var z=new Array(S.length-y+$),k=0;k<S.length-y;k+=1)z[k]=S[k+y];return z})(),C={};return C.getAt=function(y){return b[y]},C.getLength=function(){return b.length},C.multiply=function(y){for(var z=new Array(C.getLength()+y.getLength()-1),k=0;k<C.getLength();k+=1)for(var f=0;f<y.getLength();f+=1)z[k+f]^=a.gexp(a.glog(C.getAt(k))+a.glog(y.getAt(f)));return i(z,0)},C.mod=function(y){if(C Line truncated
`)}function Nr(n){let e=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ue(n,e,o,a="",r=[]){let i=Nr(n),s=[...e.map(p=>({ts:p.ts,category:_t(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:De(p)??""})),...r.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?` `)}function hi(n){let e=new Map(n.people.map(s=>[s.id,s.name])),o=new Map(n.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Qe(n,e,o,s="",r=[]){let a=hi(n),i=[...e.map(u=>({ts:u.ts,category:qt(u.type),type:u.type,person:u.person?a.people.get(u.person)??u.pname??u.person:"",device:u.device?a.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?`
${p.detail}`:""}`,where:Ct[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){Le(c,JSON.stringify(s,null,2),"application/json");return}Le(c,$o(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Hr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],Eo=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Ke(n,e,o,a,r,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...gt.map(c=>t("option",{value:c,selected:c===r?"selected":null},rt[c])),i?t("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Hr.map(([c,d])=>t("option",{value:c},d)));ae(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[le()," ",D("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await P.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){F(ve(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await P.serviceLogClear(l.value)).removed}catch(d){de(),F(`${s.value==="system"?"":`Activity: ${Eo(c).toLowerCase()}. `}The service log was not cleared: ${ve(d)}`,"error",1e4),a();return}de(),F(Eo(c),"success",3e3),a()},"negative")])}function vt(n,e,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},r)],[le()," ",D("Reset",async()=>{await W(()=>P.usageClear(n,e),"Traffic history reset")&&(de(),a())},"negative")])}function ge(n,e,o){let a=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!a.classList.contains("on");Dn(a,r),o?.(r)}},t("i"));return a}function Dn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Se=n=>n.classList.contains("on");function xe(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let a=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function We(n,e,o,a={}){return t("button",{type:"button",...a,class:`dl-chipbtn${e?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Zt(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Rr={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Ir={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Br(n){let e={};for(let[o,a]of Object.entries(Ir))n[o]!=null&&n[o]!==""&&(e[a]=String(n[o]));return e}function Or(n,e){let o=n.amnezia,a=o.obfuscation??{},r=c=>a[c]!=null&&a[c]!==""?String(a[c]):Rr[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Br(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r ${u.detail}`:""}`,where:Ft(u.src),by:""}))].sort((u,w)=>u.ts-w.ts).map(({ts:u,...w})=>({time:new Date(u*1e3).toISOString(),...w})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${s?`-${s}`:""}-${l}.${o}`;if(o==="json"){Ne(d,JSON.stringify(i,null,2),"application/json");return}let c=["time","category","type","person","device","detail","where","by"],p={time:_("Time"),category:_("Category"),type:_("Type"),person:_("Person"),device:_("Device"),detail:_("Detail"),where:_("Where"),by:_("By")};Ne(d,Ss(c,i,p),"text/csv")}var fi=["","7","30","90"],gi=n=>n?W(Number(n),"Older than %s day","Older than %s days"):_("Everything"),Ps=n=>n?W(n,"%s event removed","%s events removed"):_("Nothing matched");function lt(n,e,o,s,r,a=!1){let i=t("select",{class:"cbi-input-select"},[t("option",{value:""},_("All categories")),...Nt.map(d=>t("option",{value:d,selected:d===r?"selected":null},Ye(d))),a?t("option",{value:"system",selected:r==="system"?"selected":null},_("System")):""]),l=t("select",{class:"cbi-input-select"},fi.map(d=>t("option",{value:d},gi(d))));de(n,[t("p",{class:"dl-muted"},`${e} ${_("This cannot be undone; export first if you want a copy.")}`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Category")),i]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},_("Which events")),l])],[ue()," ",A(_("Clear"),async()=>{let d=0;if(i.value!=="system")try{d+=(await N.logsClear({...o,category:i.value,older_days:l.value})).removed}catch(c){q(Ce(c),"error",1e4);return}if(a&&(i.value==="system"||i.value===""))try{d+=(await N.serviceLogClear(l.value)).removed}catch(c){ce();let p=m(_("The service log was not cleared: %s"),Ce(c));q(i.value==="system"?p:`${m(_("Activity: %s."),Ps(d).toLowerCase())} ${p}`,"error",1e4),s();return}ce(),q(Ps(d),"success",3e3),s()},"negative")])}function Ht(n,e,o,s){let r=n==="device"?m(_("Clears %s's daily and monthly traffic history. Their person's totals and data limit are not changed."),o):n==="person"?m(_("Clears %s's traffic history and that of their devices. Their data limit starts again from zero."),o):_("Clears traffic history for everyone. Data limits start again from zero.");de(n==="all"?_("Reset all traffic history?"):m(_("Reset traffic history for %s?"),o),[t("p",{class:"dl-muted"},r)],[ue()," ",A(_("Reset"),async()=>{await F(()=>N.usageClear(n,e),_("Traffic history reset"))&&(ce(),s())},"negative")])}function ye(n,e,o){let s=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!s.classList.contains("on");uo(s,r),o?.(r)}},t("i"));return s}function uo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var ze=n=>n.classList.contains("on");function Me(n,e,o={}){n.some(([a])=>a===e)||(n=[...n,[e,e]]);let s=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>s.querySelectorAll(":scope > button").forEach(a=>{let i=a.dataset.v===s.dataset.value;a.classList.toggle("on",i),a.setAttribute("aria-checked",i?"true":"false")});for(let[a,i]of n)s.appendChild(t("button",{type:"button",role:"radio","data-v":a,click:()=>{a!==s.dataset.value&&(o.optimistic!==!1&&(s.dataset.value=a,r()),o.onChange?.(a))}},i));return r(),s}function Xe(n,e,o,s={}){return t("button",{type:"button",...s,class:`dl-chipbtn${e?" on":""}${s.class?` ${s.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function xn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function he(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var vi={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},bi={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function xi(n){let e={};for(let[o,s]of Object.entries(bi))n[o]!=null&&n[o]!==""&&(e[s]=String(n[o]));return e}function wi(n,e){let o=n.amnezia,s=o.obfuscation??{},r=d=>s[d]!=null&&s[d]!==""?String(s[d]):vi[d],a=o.host.replace(/^\[(.*)\]$/,"$1"),i={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...xi(s),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function jr(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ur(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),a=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function An(n,e,o=!0){let a=new TextEncoder().encode(JSON.stringify(Or(n,e))),r=o?await Ur(a):null;return`vpn://${jr(r??a)}`}var Mo=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"balanced",title:"Balanced",ic:"shieldplus",stealth:3,speed:3,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Pt=n=>Mo.find(e=>e.id===n),Wr={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Gr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function Lo(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function Qt(n,e,o,a,r=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,Mo.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===a?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[Lo(l.stealth,"Stealth"),Lo(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[v("phone"),t("span",{},l.apps)]:[v("alert"),t("span",{},(r?Wr:Gr)[l.needs])])])}));return s(),i}function So(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var To=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function Fr(n){let e=d=>n[d]!=null&&n[d]!=="",o=To.filter(([d])=>e(d));if(!o.length)return null;let a=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),r=(d,p,u,w)=>{let g=To.filter(([m])=>w.includes(m)&&e(m));return g.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},g.map(([m,k])=>a(m,k)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(` `),hostName:a,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(i),port:String(o.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function yi(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ki(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),s=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+s.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(s,4),r}catch{return null}}async function mo(n,e,o=!0){let s=new TextEncoder().encode(JSON.stringify(wi(n,e))),r=o?await ki(s):null;return`vpn://${yi(r??s)}`}function Ds(){return[{id:"off",title:_("Off"),ic:"zap",stealth:0,speed:4,text:_("Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block."),apps:_("Any WireGuard app"),short:_("Any WireGuard app")},{id:"balanced",title:_("Balanced"),ic:"shield",stealth:3,speed:4,needs:"v2",text:_("AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk."),apps:_("AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps"),short:_("AmneziaWG 2.0+ apps")},{id:"max",title:_("Maximum"),ic:"lock",stealth:4,speed:3,needs:"v3",text:_("AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS."),apps:_("Apps with AmneziaWG 3.1 (current AmneziaVPN)"),short:_("AmneziaWG 3.1 apps")}]}var Kt=n=>Ds().find(e=>e.id===n),wn=n=>n.v3?"max":n.v2?"balanced":"off",Yt=n=>n==="standard"?_("Standard (old)"):n==="strong"?_("Strong (old)"):null;function _i(n,e){return e?n==="v2"?_("Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on)."):_("Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."):n==="v2"?_("Needs AmneziaWG on the router."):_("Needs AmneziaWG 3.1 on the router: install it first.")}function $s(n,e){return t("span",{class:"dl-dots",title:m(_("%s: %s of 4"),e,n)},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function yn(n,e,o,s,r=!0){let a=t("div",{class:"dl-methods",role:"radiogroup","aria-label":_("Disguise method")}),i=()=>dom.content(a,Ds().map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,i(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===s?t("span",{class:"dl-pill ok"},_("Current")):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[$s(l.stealth,_("Stealth")),$s(l.speed,_("Speed"))]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},_i(l.needs,r))])])}));return i(),a}function As(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var Ns=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function Ci(n){let e=c=>n[c]!=null&&n[c]!=="",o=Ns.filter(([c])=>e(c));if(!o.length)return null;let s=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),r=(c,p,u,w)=>{let M=Ns.filter(([g])=>w.includes(g)&&e(g));return M.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},M.map(([g,h])=>s(g,h)))]):""},a=Number(n.jc||0),i=(n.i1??"").includes("0x8580")?_("A first packet shaped like a DNS answer."):_("Extra packets sent before the handshake."),l=o.map(([c,p])=>`${p} = ${n[c]}`).join(`
`),c=t("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),c])}function _o(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",a&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function qr(n){let e=!1,o=t("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(` `),d=t("div",{class:"dl-pgrid"},[r(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),K(a),n.jmin,n.jmax):_("No junk packets."),["jc","jmin","jmax"]),r(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),r(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),r(_("Signatures"),"globe",i,["i1","i2","i3","i4","i5"]),r(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},_("Current parameters")),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),xe(l,_("Parameters copied"))}},_("Copy as config"))]),d])}function Hs(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",s&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Li(n){let e=!1,o=t("pre",{class:"dl-conf"}),s=()=>dom.content(o,n.conf.split(`
`).flatMap((s,l)=>l?[` `).flatMap((i,l)=>l?[`
`,_o(s,e)]:[_o(s,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([v("download")," Download"],()=>Le(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),o])])}async function Kr(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await An(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>t("div",{class:"dl-qr-pane"},[qe(ft(n.conf),"dl-qr"),t("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),D("Copy",()=>ue(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>qr(n)},r=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(r,a[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,r])}async function Jr(n,e,o,a){let r=Pt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await re(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":o==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await W(()=>P.serverObfuscation(e.id,o),a?"New values applied":`${r.title} applied`)&&(F("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Vr(n,e){let o=n.st,a=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=`${e.mtus.computer} for computers and routers, ${e.mtus.phone} for phones and tablets`,s=e.mtu?`Now ${i}. Empty = automatic.`:`Automatic by device type and disguise: now ${i}. Lower it if some sites hang.`,l=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),c=Pt(e.preset)?e.preset:void 0,d=c??"standard",p=D("",()=>Jr(n,e,d,d===c),"neutral"),u=()=>dom.content(p,d===c?[v("reset")," Generate new values"]:[`Switch to ${Pt(d).title}`]);u();let w=o.awg_state?.tools!==!1;return Tt("",[So("AmneziaWG",e.ifname),he("globe","Listening","Where devices reach this core from the internet",[ne("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ne("MTU",r,s),ne("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Qt(o.awg,d,g=>{d=g,u()},c,w),w&&!o.awg.v3?ht("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Fr(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),p])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ne("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ne("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ne("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),D([v("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:l.value},"AmneziaWG saved"),"positive")])}function Yr(n){let e=Pt(n.preset),o=n.obf??{},a=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(c=>t("i",{class:c<s?"on":""}))),r=[];+o.jc&&r. Line truncated `,Hs(i,e)]:[Hs(i,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("key"),_("Show key")]);s();let a=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${W(a,"%s byte","%s bytes")}`)]),A([v("download")," ",_("Download")],()=>Ne(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},_("Configuration")),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),xe(n.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function ho(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function Mi(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},_("This device generated its own keys in the browser, so its full configuration only exists on that device."));let o=await mo(n,n.server),s={qr:()=>t("div",{class:"dl-qr-pane"},[un(n.conf),t("span",{class:"dl-sub"},ho(n)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),A(_("Copy"),()=>xe(o,_("Key copied")))]),t("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>Li(n)},r=t("div",{class:"dl-connect-body"}),a=t("div",{class:"dl-seg"}),i=l=>{a.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])a.appendChild(t("button",{type:"button","data-id":l,click:()=>i(l)},d));return i(e),t("div",{class:"dl-stack gap12"},[a,r])}async function Ei(n,e,o,s){let r=Kt(o),i=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await me(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[W(i,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",n.st.servers.length===1&&i?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await F(()=>N.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(q(_("Devices are marked “Update config” until they import again."),"info",6e3),await n.refresh())}function Ti(n,e){let o=n.st,s=he(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=he(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=he(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=Kt(e.preset)?e.preset:void 0,l=i??wn(o.awg),d=A("",()=>Ei(n,e,l,l===i),"neutral"),c=()=>dom.content(d,l===i?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Kt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],w=_e(_("UDP port"),s,()=>Gt(Number(s.value),u,[_("Opened on the WAN firewall automatically."),Number(s.value)===4500?_("4500 is IPsec’s port: most networks let it through."):""].filter(Boolean).join(" ")));N.serverPorts(e.id).then(h=>{u=h.udp_taken??[],w.refresh()}).catch(()=>{});let M=_e("MTU",r,()=>ps(r.value,e.mtus)),g=_e(_("Keep-alive"),a,()=>us(a.value));return Wt("",[As("AmneziaWG",e.ifname),ke("globe",_("Listening"),_("Where devices reach this core from the internet"),[w]),ke("file",_("In every device configuration"),_("Changing these marks devices “Update config” until they import again"),[M,g]),ke("shield",_("Disguise"),_("So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard"),[Yt(e.preset)?bt("warn",ae(_("%s is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to %s or %s: devices import their configuration again."),t("b",{},Yt(e.preset)),t("b",{},_("Balanced")),t("b",{},_("Maximum")))):"",yn(o.awg,l,h=>{l=h,c()},i,p),p&&!o.awg.v3?bt("info",ae(_("This router runs an older AmneziaWG. %s becomes available with kmod-amneziawg and amneziawg-tools 3.1."),t("b",{},_("Maximum")))):"",Ci(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},_("Applies at once: every AmneziaWG device imports its configuration again.")),d])]),t("deta Line truncated
`),"Log copied"))]),p,u]),[w],"wide"),m([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let N=o??null,B=o?.id,E,y=0,S=h=>{B!==h.id&&(B=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await P.updatesStatus().catch(()=>null);E=h?.job?.id,y=h?.now??0;let f=await P.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==E&&(N=f.job,S(f.job))}catch(h){return g=[ve(h)],p.textContent=g[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},ve(h))])),m([k(!0)]),F(ve(h),"error"),null}let b=null,x=0;for(;;){if(await sa(1e3),b=await P.updatesStatus().catch(()=>null),!b){if(++x>60)break;continue}x=0;let h=b.job;if(!h||!ia(h,B,E,y)){if(Date.now()-i>15e3)break;continue}if(S(h),N=h,h.log.length){g=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=g.join(` `),_("Log copied")))]),p,u]),[w],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?_("Checking…"):_("Working…"))]);let E=o??null,H=o?.id,S,$=0,b=x=>{H!==x.id&&(H=x.id,e.onJob?.(x))};if(o)e.onJob?.(o);else try{let x=await N.updatesStatus().catch(()=>null);S=x?.job?.id,$=x?.now??0;let T=await N.updatesRun(n);T.job&&T.job.state==="running"&&T.job.id!==S&&(E=T.job,b(T.job))}catch(x){return M=[Ce(x)],p.textContent=M[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},Ce(x))])),g([h(!0)]),q(Ce(x),"error"),null}let C=null,y=0;for(;;){if(await $o(1e3),C=await N.updatesStatus().catch(()=>null),!C){if(++y>60)break;continue}y=0;let x=C.job;if(!x||!Lr(x,H,S,$)){if(Date.now()-a>15e3)break;continue}if(b(x),E=x,x.log.length){M=x.log;let T=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=M.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=aa(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=oa((h.finished??b.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!N||N.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),m([k()]),e.onDone?.(b),N;if(N.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},N.error??"Operation failed"),r?"":". Nothing else was changed."])])),m([D("Copy log",()=>ue(g.join(` `),T&&(p.scrollTop=p.scrollHeight)}if(l.textContent=_r(x,e.version??""),!l.isConnected&&l.textContent&&i.after(l),c.textContent=kr((x.finished??C.now)-x.started),x.state==="running"){d.hidden=!x.phase,d.textContent=x.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),g([h()]),e.onDone?.(C),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},(E.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),g([A(_("Copy log"),()=>xe(M.join(`
`),"Log copied")),k(!0)]),F(`${cn[a]??"Update"}: ${N.error??"failed"}`,"error"),e.onDone?.(b),N;if(c.className="dl-pill ok",c.textContent="Finished",r&&b){let h=ra(b,a);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[v(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),F(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(b),h.update&&e.onUpdate){let f=b;m([k(),D(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else m([k()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&de(),1200);return N}if(a==="app"&&N.to){let h=N.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let R=()=>{ui.menu?.flushCache(),location.reload()};m([k(),D("Reload now",R,"positive")]),F(`Dawnline updated to ${h}`,"success",6e3);for(let C=1;C<=30;C++)if(f.textContent=`Waiting for the router to restart its services (${C} of 30)…`,await sa(1500),(await P.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(R,800),N;return f.textContent="Services restarted. Reload the page to use the new version.",N}let M=a==="pkgs"?`Updated ${[...N.result?.pkgs?.updated??[],...N.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${N.to?` ${N.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},M)])),m([k()]),F(M,"success"),e.onDone?.(b),N}var $i={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function la(n,e,o,a){return!await re(`Install ${e}?`,o,"Install")||(await Bt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function un(n){return la("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Ot(n,e,o){return n==="awg"?un(o):e.length?la(`pkgs:${e.join(",")}`,$i[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function da(n,e){if(n==="awg")return un(e);let o=await W(()=>P.updatesStatus());return o?Ot(n,o.needs?.[n]??[],e):!1}var Ei=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Li={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function ca(n,e,o){let a=n.id,r=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,g=ea(r,a,o),m=new Set,k="",N=()=>JSON.stringify([p,l,l?"":c,d,[...m].sort()]),B=()=>s.detected.lan||s.saved.lan||"",E=()=>(l?s.detected.wan||s.saved.wan:c)||"",y=()=>new Map(s.devices.map(z=>[z.name,z])),S=()=>{let z=y();return[...d&&B()?[B()]:[],...[...m].filter(X=>X!==B())].filter(X=>X!==E()).map(X=>z.get(X)??{name:X,nets:[],missing:!0})},b=(z,K)=>{s=z,K&&(l=z.config.auto_wan,c=z.config.wan_device||z.detected.wan||z.saved.wan||"",d=z.config.auto_lan,p=z.config.lan_like,u=z.config.mesh??(z.config.device_mesh?"all":"off"),m=new Set(z.config.lan_devices),k=N()),G()},x=async z=>{let K=await P.interfaces(a).catch(X=>(F(X.message,"error"),null));K&&b(K,z)};function M(z){let K=d&&z.name===B(),X=!!z.own||!!z.master||z.name===E()||K;return K||m.has(z.name)||!X&&(z.nets.length>0||!!z.missing)}function h(z){let K=d&&z.name===B(),X=z.name===E(),ce=!K&&m.has(z.name),O=!(!!z.own||!!z.master||X||K)&&(z.nets.length>0||ce||!!z.missing),U=(ce||K)&&!z.zone&&!z.missing,q=z.missing?"Not present right now":z.own?"This server":z.master?`Port of ${z.master}`:X?`Internet${z.zone?` · zone ${z.zone}`:""}`:z.nets.length?z.nets.join(", "):"No IPv4 network",oe=t("button",{type:"button",class:`dl-if${ce?" sel":""}${K?" auto":""}${!O&&!ce&&!K?" off":""}${U?" warn":""}`,"aria-pressed":ce||K?"true":"false","aria-disabled":O?null:"true",click:()=>{O&&(m.has(z.name)?m.delete(z.name):m.add(z.name),G())}},[t("span",{class:"dl-if-ic"},v(Li[z.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},z.name),t("span",{class:"dl-if-sub"},q)]),K?t("span",{class:"dl-if-badge ok"},"Auto"):ce?t("span",{class:"dl-if-check"},v("check")):""]);return me(oe,()=>[t("div",{class:"dl-tip-title"},z.name),t("div",{class:"dl-muted"},[z.logical?`Interface ${z.logical}`:"No netifd interface",z.zone?` · zone ${z.zone}`:" · no firewall zone"]),z.members.length?t("div",{class:"dl-muted"},`Ports: ${z.members.join(", ")}`):"",z.nets.length?t("div",{class:"dl-mono"},z.nets.join(", ")):"",U?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",z.master?t("div",{class:"dl-muted"},`Choose ${z.master} to include it.`):""]),oe}function f(){let z=s.like_home;return!p||!s.config.lan_like Line truncated `),_("Log copied"))),h(!0)]),q(`${Dn(s)??_("Update","noun")}: ${E.error??_("failed")}`,"error"),e.onDone?.(C),E;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&C){let x=Cr(C,s);if(dom.content(u,t("div",{class:`dl-comp-status ${x.tone}`},[v(x.tone==="ok"?"check":x.tone==="warn"?"alert":"download"),t("span",{},x.text)])),q(x.text,x.tone==="warn"?"warning":"success"),e.onDone?.(C),x.update&&e.onUpdate){let T=C;g([h(),A(m(_("Update to %s"),x.update),()=>e.onUpdate(T),"positive")])}else g([h()]),x.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return E}let z=/^app:(lang:|nolang$)/.exec(E.component??"");if(z){let x=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},z[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),g([h(),A(_("Reload now"),x,"positive")]),await $o(4e3),u.isConnected&&x(),E}if(s==="app"&&E.to){let x=E.to,T=t("span",{},_("Waiting for the router to restart its services…"));dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},m(_("Dawnline %s is installed."),x))," ",T])]));let I=()=>{ui.menu?.flushCache(),location.reload()};g([h(),A(_("Reload now"),I,"positive")]),q(m(_("Dawnline updated to %s"),x),"success",6e3);for(let V=1;V<=30;V++)if(T.textContent=m(_("Waiting for the router to restart its services (%s of 30)…"),V),await $o(1500),(await N.updatesStatus().catch(()=>null))?.version===x)return T.textContent=_("Services are back. Reloading…"),setTimeout(I,800),E;return T.textContent=_("Services restarted. Reload the page to use the new version."),E}let k=[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]],f=s==="pkgs"?k.length?m(_("Updated %s"),k.join(", ")):_("Updated system packages"):s==="amneziawg"?E.to?m(_("AmneziaWG %s is installed"),E.to):_("AmneziaWG is installed"):_("Operation completed");return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},f)])),g([h()]),q(f,"success"),e.onDone?.(C),E}function el(n){return{https:[_("Install HTTPS for the portal?"),_("Installing HTTPS for the portal")],acme:[_("Install ACME certificates?"),_("Installing ACME certificates")],home:[_("Install the home-like link?"),_("Installing the home-like link")],awg:[_("Install AmneziaWG?"),_("Installing AmneziaWG")]}[n]}async function Mr(n,e,o,s){let[r,a]=el(e);return!await me(r,o,_("Install"))||(await tn(n,{title:a}))?.state!=="done"?!1:(setTimeout(()=>s?.(),4e3),!0)}function Nn(n){return Mr("amneziawg:auto","awg",_("Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds."),n)}async function nn(n,e,o){return n==="awg"?Nn(o):e.length?Mr(`pkgs:${e.join(",")}`,n,m(_("%s from the OpenWrt feeds. Dawnline sets the rest up when they arrive."),e.join(", ")),o):!0}async function Er(n,e){if(n==="awg")return Nn(e);let o=await F(()=>N.updatesStatus());return o?nn(n,o.needs?.[n]??[],e):!1}var tl=()=>[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn",_("VPN & tunnels")],["other",_("Other")]],nl={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Tr(n,e,o){let s=n.id,r=e,a=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},_("Loading interfaces…"))))),i,l=!0,d="",c=!0,p=!0,u="all",w=!1,M=xr(r,s,o),g=new Set,h="",E=()=>JSON.stringify([p,l,l?"":d,c,[...g].sort()]),H=()=>i.detected.lan||i.saved.lan||"",S=()=>(l?i.detected.wan||i.saved.wan:d)||"",$=()=>new Map(i.devices.map(B=>[B.name,B])),b=()=>{let B=$();return[...c&&H()?[H()]:[],...[...g].filter(ne=>ne!==H())].filter(ne=>ne!==S()).map(ne=>B.get(ne)??{name:ne,nets:[],missing:!0})},C=(B,Q)=>{i=B,Q&&(l=B.config.auto_wan,d=B.config.wan_device||B.detected.wan||B.saved.wan||"",c=B.config.auto_lan,p=B.config.lan_like,u=B.config.mesh??(B.config.device_mesh?"all":"off"),g=new Set(B.config.lan_devices),h=E()),J()},y=async B=>{let Q=await N.interfaces(s).catch(ne=>(q(ne.message,"error"),null));Q&&C(Q,B)};function z(B){let Q=c&&B.name===H(),ne=!!B.own||!!B.master||B.name===S()||Q;return Q||g.has(B.name)||!ne&&(B.nets.length>0||!!B.missing)}function k(B){let Q=c&&B.name===H(),ne=B.name===S(),fe=!Q&&g.has(B.name),j=!(!!B.own||!!B.master||ne||Q)&&(B.nets.length>0||fe||!!B.missing),Y=(fe||Q)&&!B.zone&&!B.missing,ie=B.missing?_("Not present right now"):B.own?_("This server"):B.master?m(_("Port of %s"),B.master):ne?`${_("Internet")}${B.zone?` · ${m(_("zone %s"),B.zone)}`:""}`:B.nets.length?B.nets.join(", "):_("No IPv4 network"),ve=t("button",{type:"button",class:`dl-if${fe?" sel":""}${Q?" auto":""}${!j&&!fe&&!Q?" off":""}${Y?" warn":""}`,"aria-pressed":fe||Q?"true":"false","aria-disabled":j?null:"true",click:()=>{j&&(g.has(B.name)?g.delete(B.name):g.add(B.name),J())}},[t("span",{class:"dl-if-ic"},v(nl[B.kind]??"link")),t( Line truncated
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(` `).map(e=>At(e)).join(`
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(r.length&&s(),a||(a=t("ul",{}),e.push(a)),a.appendChild(t("li",{},o(p[1])))):c.trim()?(a&&(a=null),r.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(` `);function Hn(n,e,o,s){let r=n.by==="admin",a=At(n.msg),i=t("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${dl[n.level]??""}`}${n.detail?" has-detail":""}`},[r?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):t("span",{class:"dl-ev-tile sys",title:pl(n.level)},v(cl[n.src]??"zap")),t("span",{class:"dl-row-main"},r?[...ul(n),n.note?t("span",{class:"dl-muted"},` · ${Ms(n.note)}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},`${_("Server")} `):"",t("b",{class:"dl-sys-src",title:Ft(n.src)},n.who?n.src==="awg"?n.who:At(n.who):Ft(n.src)),/^[:,]/.test(a)?"":" ",t("span",{class:"dl-muted"},a),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]),t("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString(le())},s)]);return n.detail&&i.addEventListener("click",l=>{l.target.closest("pre")||o()}),i}function Pr(n){let e=new Date(n*1e3),o=new Date,s=new Date;if(s.setDate(o.getDate()-1),e.toDateString()===o.toDateString())return _("Today");if(e.toDateString()===s.toDateString())return _("Yesterday");let r=e.toLocaleDateString(le(),{weekday:"long",day:"numeric",month:"long"});return r.charAt(0).toLocaleUpperCase(le())+r.slice(1)}var Ot=n=>Mt(n).toLocaleDateString(le(),{day:"numeric",month:"short"});function zn(n,e,o,s=!1){let r=n.slice(-15),a=r[r.length-1],i=a&&e-a[0]<180,l=i?a[2]:0,d=i?a[1]:0,[c,p]=o,u=200,w=40,M=Math.max(1,...r.map($=>Math.max($[1],$[2]))),g=$=>r.map((b,C)=>`${r.length>1?C/(r.length-1)*u:u},${w-2-b[$]/M*(w-6)}`),h=g(2),E=g(1),H=r.length>1&&!s?Tt(`<svg viewBox="0 0 ${u} ${w}" preserveAspectRatio="none" class="dl-speed-chart" aria-hidden="true"><path d="M${h.join(" L")} L${u},${w} L0,${w}Z" class="area"/><path d="M${h.join(" L")}" class="line"/><path d="M${E.join(" L")}" class="line up"/></svg>`):t("div",{class:"dl-speed-wait"},[t("i"),s?"":t("span",{},_("Collecting… 1 point a minute"))]),S=($,b,C,y)=>t("div",{class:"dl-speed-col"},[t("span",{class:"dl-sub"},[t("span",{class:C},b),` ${$}`]),s?t("span",{class:"dl-speed-val off"},"—"):t("span",{class:"dl-speed-val"},Fe(y))]);return r.length>1&&!s&&we(H,()=>{let $=r[r.length-1];return[t("div",{class:"dl-tip-title"},new Date($[0]*1e3).toLocaleTimeString(le(),{hour:"2-digit",minute:"2-digit"})),t("div",{},`↓ ${Fe($[2])} · ↑ ${Fe($[1])}`)]}),t("div",{class:"dl-bento-tile"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},_("Speed now")),s?"":t("span",{class:"dl-sub"},_("last 15 min"))]),t("div",{class:"dl-speed-cols"},[S(_("Download","speed"),"↓","dl-dn",l),S(_("Upload","speed"),"↑","dl-up",d)]),H,t("div",{class:"dl-speed-today"},[t("span",{},ae(_("Today %s"),t("b",{},se(c+p)))),t("span",{},[t("span",{class:"dl-dn"},"↓"),` ${se(p)} `,t("span",{class:"dl-up"},"↑"),` ${se(c)}`])])])}function Rn(n,e){let o=n.slice(-30),s=o.map(d=>d.rx+d.tx),r=Math.max(1,...s),a=s.reduce((d,c)=>d+c,0),i=s.reduce((d,c,p)=>c>s[d]?p:d,0),l=t("div",{class:"dl-bento-bars"},o.map((d,c)=>{let p=s[c],u=t("i",{class:c===o.length-1?"hi":"",style:`height:${Math.max(4,p/r*100)}%`}),w=t("span",{},[u]);return we(w,()=>[t("div",{class:"dl-tip-title"},c===o.length-1?`${_("Today")} · ${Ot(d.day)}`:Ot(d.day)),t("div",{},se(p)),t("div",{class:"dl-muted dl-mono"},`↓ ${se(d.tx)} ↑ ${se(d.rx)}`)]),w}));return t("div",{class:"dl-bento-tile month"},[t("div",{class:"dl-bento-head"},[t("span",{},[t("span",{class:"dl-metric-label"},_("Last 30 days")),t("b",{class:"dl-bento-total"},se(a))]),s[i]>0?t("span",{class:"dl-sub"},`${m(_("peak %s"),se(s[i]))} · ${Ot(o[i].day)}`):""]),o.length?l:t("p",{class:"dl-muted"},_("No traffic yet.")),t("div",{class:"dl-bento-head"},[t("span",{class:"dl-sub"},o.length?Ot(o[0].day):""),t("span",{class:"dl-sub"},e),t("span",{class:"dl-sub"},_("today"))])])}function $r(n){let e=n.slice(-30),o=e.map(r=>r.rx+r.tx),s=Math.max(1,...o);return t("div",{class:"dl-dbars"},e.map((r,a)=>{let i=t("i",{class:`${o[a]?"":"zero"}${a===e.length-1?" hi":""}`});i.style.height=`${Math.max(8,o[a]/s*100)}%`;let l=t("span",{},[i]);return we(l,()=>[t("div",{class:"dl-tip-title"},a===e.length-1?`${_("Today")} · ${Ot(r.day)}`:Ot(r.day)),t("div",{},se(o[a]))]),l}))}function Dr(n){return{apply:_("Repair"),sync:_("Reload devices"),restart:_("Restart service"),netrestart:_("Restart network"),updates:_("Open Components")}[n]??_("Fix")}async function In(n){return n==="netrestart"&&!await me(_("Restart the network?"),_("Every interface restarts. Connections drop for a few seconds."),_("Restart network"))?null:await F(()=>N.healthFix(n),_("Done"))??null}function Ao(n,e,o,s="action"){let r=n.fix;return r?r.startsWith("install:")?A(_("Install"),()=>Er(r.slice(8),o),s):r==="updates"?t("a",{class:`cbi-button cbi-button-${s}`,href:L.url("admin/network/dawnline/uLine truncated
`))),s(),e}function Ta(n){let e=[],o=!1;for(let a of n.replace(/\r/g,"").split(` `)){let d=l.trimEnd();if(a){/^```/.test(d.trim())?(e.push(t("pre",{},a.join(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||e.push(a)}return e.join(` `))),a=null):a.push(l);continue}if(/^```/.test(d.trim())){i(),a=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(i(),e.push(t("h5",{},o(c[2])))):p?(r.length&&i(),s||(s=t("ul",{}),e.push(s)),s.appendChild(t("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):i()}return a&&e.push(t("pre",{},a.join(`
`))),i(),e}function Kr(n){let e=[],o=!1;for(let s of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(s);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(s)&&(o=!1);o||e.push(s)}return e.join(`
`).replace(/\n{3,}/g,` `).replace(/\n{3,}/g,`
`).trim()}async function Ut(n,e,o,a){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([v("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",le("Close")],"wide");try{let l=await P.updatesNotes(n,e,a??"");s=Ta(l.body||"");let c=Ma(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},He(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(r,s.trim()?Sa(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,t("p",{class:"dl-muted"},ve(l)))}}var _a={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Zn=n=>n?He(n):"";function Oi(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Pa(n,e){let o=n.st,a=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Ut("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?ji(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,p=(w,g)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},g)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await re(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Zn(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Zn(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Ui(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[a.auto?ye("ok","On"):ye("","Off"),t("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${_a[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${_a[a.interval]}`:"checks off")]),p("Last check",o.check?[ie(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${pt(d-o.now)}`):""]:["Never"]),p("Rollback",r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ji(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(` `).trim()}async function sn(n,e,o,s){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),a=t("div",{class:"dl-op-head"}),i="";de(o,[a,r],[A([v("copy")," ",_("Copy")],()=>xe(i,_("Release notes copied")))," ",ue(_("Close"))],"wide");try{let l=await N.updatesNotes(n,e,s??"");i=Kr(l.body||"");let d=qr(l.url);dom.content(a,[l.published?t("span",{class:"dl-pill"},Oe(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},_("Pre-release")):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",v("open")]):""]),dom.content(r,i.trim()?Fr(i):t("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,t("p",{class:"dl-muted"},Ce(l)))}}function yl(n){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[n]??e["1d"]}var Ro=n=>n?Oe(n):"";function kl(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Vr(n,e){let o=n.st,s=o.policy,r=o.kept?.app,a=e?.update&&e.tag?e.tag:o.version,i=w=>()=>sn("app",w,m(_("What’s new in Dawnline %s"),w.replace(/^v/,""))),l=e?.tag&&(e.update||e.status==="latest")?_l(n,e.tag,e.update?o.version:""):null,d=e?.tag??a,c=s.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[s.interval]??24)*3600:0,p=(w,M)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},M)]),u=[{label:_("What’s new"),ic:"file",run:i(a)},{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:m(_("Reinstall %s"),o.version),ic:"reset",warn:!0,run:()=>n.op("app:reinstall",_("Reinstalling Dawnline"),o.version)},r?{label:m(_("Roll back to %s"),r.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back to Dawnline %s?"),r.version),m(_("The copy kept on the router replaces %s. A backup of the settings is made first."),o.version),_("Roll back"))&&n.op("app:rollback",_("Rolling back Dawnline"),o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app",_("Checking Dawnline"),o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},m(_("release %s"),e.latest)):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?m(_("released %s"),Ro(e.published)):"":e?.status==="dev"?_("ahead of the latest release"):e?[_("latest release"),e.published?m(_("released %s"),Ro(e.published)):""].filter(Boolean).join(" · "):_("not checked yet"))])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:i(d)},W(l.total-l.items.length,"+%s more in What’s new","+%s more in What’s new")):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[A(_("Update now"),()=>n.op("app",_("Updating Dawnline"),o.version),"positive",{disabled:n.busy}),A(_("What’s new"),i(a))]):"",Ll(n),Cl(n)]),t("div",{class:"dl-comp-hero-side"},[p(_("Source"),[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p(_("Auto-update"),[s.auto?Pe("ok",_("On")):Pe("",_("Off")),t("span",{class:"dl-muted"},s.auto?s.mode==="immediate"?_("as soon as found"):m(s.interval==="7d"?_("weekly at %s"):_("daily at %s"),s.time):s.check?yl(s.interval):_("checks off"))]),p(_("Last check"),o.check?[pe(o.check.time,o.now),c>o.now?t("span",{class:"dl-faint"},`· ${m(_("next in %s"),ot(c-o.now))}`):""]:[_("Never")]),p(_("Rollback"),r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},_("kept on flash"))]:[t("span",{class:"dl-muted"},s.keep?_("Kept after the next update"):_("Off"))])])])}function _l(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let s=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(a,i)=>i??"").trim();return(async()=>{let a=((await N.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Oi(a(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ui(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&xn(n,e)}),n.versOpen&&xn(n,e),o}async function xn(n,e){let o=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return F("Enter a release tag like 0.3.1","warning");Ca(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),a(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),xn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${ve(p)}`),D("Try again",()=>xn(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[r,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[r,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Zn(p.published)),p.prerelease?ye("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},$e("file","What’s new",()=>Ut("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?ye("ok","Installed"):D("Install",()=>Ca(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function Ca(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await re(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function Da(n,e){let o=n.st,a=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),s=e?.current??null,l=s?r[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),a&&u.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await re(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Ut("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,R)=>h!==null||f>0&&R[f-1]!==null),g=o.tunnels??[],m=g.length?`Switching restarts ${g.length===1?"the tunnel":`${g.length} tunnels`} for a few seconds: ${g.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",k=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0],N=g.length?`Switching restarts ${k} for a few seconds.`:"Switching takes a few seconds.",B=async h=>{let f=r[h];await re(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${m}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},E=h=>{let f=r[h],R=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},R?ye("ok","Active"):f.version?D(p?"Switch":"Install",()=>B(h),p?"neutral":"positive",{disabled:n.busy}):ye("","No build"))])},y=i.map(h=>r[h]?.newer?`${r[h].label} moves to ${r[h].newer.gen} with OpenWrt ${r[h].newer.tag.replace( Line truncated `).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);a.length||(a=(await N.updatesChanges(o,e).catch(()=>null))?.items??[]);let i={items:a.slice(0,3).map(l=>kl(s(l))),total:a.length};n.notes.set(e,i),i.items.length&&n.root.isConnected&&n.paint()})(),null}function jn(n){return n==="ru"?_("Russian translation"):n}function Cl(n){let e=(n.st.translations??[]).includes("ru"),o=ye(e,jn("ru"),r=>{n.op(r?"app:lang:ru":"app:nolang",r?_("Adding the Russian translation"):_("Removing the Russian translation"),n.st.version)});o.disabled=n.busy;let s=t("details",{class:"dl-params dl-comp-fold",open:n.langOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},_("Translation")),t("span",{class:"dl-sub"},e?_("Russian"):_("English only"))]),t("div",{class:"dl-params-body"},[t("div",{class:"dl-list"},[t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},jn("ru")),t("span",{class:"dl-sub"},_("LuCI pages for Dawnline"))]),t("span",{class:"dl-comp-bact"},o)])])])]);return s.addEventListener("toggle",()=>n.langOpen=s.open),s}function Ll(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},_("Versions")),t("span",{class:"dl-sub"},_("install any release"))]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&Un(n,e)}),n.versOpen&&Un(n,e),o}async function Un(n,e){let o=he("",{placeholder:_("Tag, e.g. 0.3.1"),class:"cbi-input-text dl-mono","aria-label":_("Release tag")}),s=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return q(_("Enter a release tag like 0.3.1"),"warning");Yr(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),s(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,A(_("Install"),()=>s(o.value),"neutral",{disabled:n.busy})]),a=n.versPage,i=p=>{n.versPage=Math.max(1,n.versPage+p),Un(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:a<=1?"disabled":null,click:()=>i(-1)},_("← Newer")),t("span",{class:"dl-faint"},m(_("Page %s"),a)),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>i(1)},_("Older →"))]),d=n.versCache.get(a);if(!d){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},_("Loading versions…"))]);try{d=(await N.updatesReleases(a)).releases}catch(p){if(a!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},m(_("Failed to load versions: %s"),Ce(p))),A(_("Try again"),()=>Un(n,e))]),l(!1)]);return}if(n.versCache.set(a,d),a!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[r,t("p",{class:"dl-muted"},a>1?_("No more versions."):_("No versions found.")),l(!1)]);let c=n.st.version;dom.content(e,[r,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Ro(p.published)),p.prerelease?Pe("warn",_("Pre-release")):"",t("span",{class:"dl-comp-ic"},$e("file",_("What’s new"),()=>sn("app",p.tag,m(_("What’s new in Dawnline %s"),u)))),u===c?Pe("ok",_("Installed")):A(_("Install"),()=>Yr(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Yr(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await me(m(_("Install Dawnline %s?"),o),m(_("It is older than %s. A backup of the settings is made first; restore it from Settings if something looks wrong."),n.st.version),_("Install"))||n.op(`app@${e}`,m(_("Installing Dawnline %s"),o),n.st.version)}function Jr(n,e){let o=n.st,s=o.kept?.amneziawg,r=e?.sources??{},a=Object.keys(r),i=e?.current??null,l=i?r[i]:void 0,d=!!e?.ru,c=o.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];i&&p&&u.push({label:_("Reinstall this build"),warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${i}${d?":ru":""}`,_("Reinstalling AmneziaWG"),p)}),s&&u.push({label:m(_("Roll back to %s"),s.version),ic:"archive",warn:!0,run:async()=>{await me(m(_("Roll back AmneziaWG to %s?"),s.version),_("The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds."),_("Roll back"))&&n.op("amneziawg:rollback",_("Rolling back AmneziaWG"),p??void 0)}});let w=[e?.release?{label:_("What’s new"),ic:"file",run:()=>sn("amneziawg",e.release,m(_("What’s new in the %s build"),l?.label??"AmneziaWG"),i??"slava")}:null,{label:_("Open on GitHub"),ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((k,f,x)=>k!==null||f>0&&x[f-1]!==null),M=o.tunnels??[],g=M.length?M.length===1?m(_("Switching restarts the tunnel for a few seconds: %s. Devices keep their configurations."),M[0]):m(N_(M.length,"Switching restarts %s tunnel for a few seconds: %s. Devices keep their configurations.","Switching restarts %s tunnels for a few seconds: %s. Devices keep their configurations."),K(M.length),M.join(", ")):_("Switching takes a few Line truncated
`)}r.push(p),l+=d-1}let s=D([v("more")],()=>we(s,[{label:"Export CSV",icon:v("download"),run:()=>Ue(o,a,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Ue(o,a,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>Ke(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),t("span",{class:"dl-spacer"}),s]),r.length?r:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var yn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,a,r]=await Promise.all([P.status(30),e?P.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let a=t("div",{},[t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:wt(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:wt(o.server)},"People"),t("span",{},"/"),t("span",{},o.name)]),this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>Be(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>it(this.p,this.deviceOpts()),50),this.poller=Ve({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=wt(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let a=await W(()=>P.personUpdate(this.p.id,e),o);if(!a)return!1;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);return(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint(),!0}get today(){return Re(this.series.length?this.series:this.st.series)}get core(){return bt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(e=!1){Me(this.parts.head,ja(this),e),Me(this.parts.traffic,Ua(this),e),Me(this.parts.devices,Wa(this),e),Me(this.parts.limits,Ya(this),e),this.paintPlaces(e),Me(this.parts.activity,Qa(this),e)}paintPlaces(e=!1){let o=Za(this);o&&Me(this.parts.places,o,e&&!this.mapOpen)}};var Qi={ok:"check",warn:"alert",error:"x",skip:"pause"},kn=class{constructor(e,o,a,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(e){let o=e?await gn(e):await P.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,a=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ht("error",`${o} problem${o>1?"s":""} need attention.`):a?ht("warn",`${a} warning${a>1?"s":""}.`):ht("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog Line truncated `)}r.push(p),l+=c-1}let i=A([v("more")],()=>Se(i,[{label:_("Export CSV"),icon:v("download"),run:()=>Qe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Qe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("trash"),danger:!0,run:()=>lt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{person:e.id},()=>n.refresh())}]),"neutral",{title:_("Export or clear"),class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Activity")),t("span",{class:"dl-sub"},s.length>10?m(_("latest 10 of %s"),K(s.length)):""),t("span",{class:"dl-spacer"}),i]),r.length?r:t("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var Gn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,s,r]=await Promise.all([N.status(30),e?N.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?N.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(i=>i.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},_("Person not found")),t("p",{},_("They may have been removed.")),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},_("Back to Servers"))]);this.p=o;for(let i of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[i]=t("div",{});this.parts.devices.className="dl-person-devices";let s=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),a=r.get("device")&&o.devices.find(i=>i.id===r.get("device"));return a?setTimeout(()=>Je(this.p,a,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ct(this.p,this.deviceOpts()),50),this.poller=pt({fetch:i=>{let l=i||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(i,l)=>this.apply(i,l)}),s}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=It(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var a;this.poller?.claim();let s=await F(()=>N.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(i=>i.id===this.p.id);return(a=s.person).rate??(a.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return Ge(this.series.length?this.series:this.st.series)}get core(){return zt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[t("a",{href:It(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),t("span",{},"/"),t("a",{href:It(e.server)},_("People")),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Ae(this.parts.crumbs,this.crumbs(),e),Ae(this.parts.head,aa(this),e),Ae(this.parts.traffic,ia(this),e),Ae(this.parts.devices,la(this),e),Ae(this.parts.limits,fa(this),e),this.paintPlaces(e),Ae(this.parts.activity,va(this),e)}paintPlaces(e=!1){let o=ga(this);o&&Ae(this.parts.places,o,e&&!this.mapOpen)}};var zl={ok:"check",warn:"alert",error:"x",skip:"pause"},qn=class{constructor(e,o,s,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await In(e):await N.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},_("Checks"))]),t("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);return}let o=e.filter(i=>i.status==="error").length,s=e.filter(i=>i.status==="warn").length;dom.content(this.summary,o?bt("error",W Line truncated
`);function hr(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=gs,n}function lt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async a=>{let r=await e.render(a),i=document.createElement("div");return i.className="dl-root",i.append(hr(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var zg=lt(jt),Ng=lt(st),Hg=lt(jt),Rg=lt(bn),Ig=lt(yn),Bg=lt(Ln),Og=lt(wn);function fr(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var jg=fr(""),Ug=fr("log");return baseclass.extend({ activity: Ug, diagnostics: Bg, health: jg, overview: zg, people: Ng, person: Ig, server: Hg, settings: Rg, updates: Og }); `);function Aa(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=td,n}function yt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),a=document.createElement("div");return a.className="dl-root",a.append(Aa(),r),a},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Jb=yt(on),Zb=yt(wt),Qb=yt(on),Xb=yt(On),e0=yt(Gn),t0=yt(Yn),n0=yt(Wn);function Na(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var o0=Na(""),s0=Na("log");return baseclass.extend({ activity: s0, diagnostics: t0, health: o0, overview: Jb, people: Zb, person: e0, server: Qb, settings: Xb, updates: n0 });
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+171 -35
View File
@@ -12,11 +12,32 @@ import * as pc from 'dawnline.portalcert';
import * as watchdog from 'dawnline.watchdog'; import * as watchdog from 'dawnline.watchdog';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import { L_ } from 'dawnline.i18n';
import { import {
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util'; } from 'dawnline.util';
const args = ARGV; /** Options that take no value. */
const FLAGS = [ 'json', 'yes', 'conf' ];
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
const opts = {};
const args = [];
for (let i = 0; i < length(ARGV); i++) {
let a = ARGV[i];
if (a == '-n')
a = '--n';
if (substr(a, 0, 2) == '--') {
let name = substr(a, 2);
if (index(FLAGS, name) >= 0)
opts[name] = true;
else
opts[name] = ARGV[++i] ?? '';
}
else
push(args, a);
}
const cmd = args[0] ?? 'help'; const cmd = args[0] ?? 'help';
function out(v) { function out(v) {
@@ -24,10 +45,41 @@ function out(v) {
} }
function opt(name, dflt) { function opt(name, dflt) {
for (let i = 1; i < length(args); i++) return opts[name] ?? dflt;
if (args[i] == `--${name}`) }
return args[i + 1];
return dflt; /** Fixed-width columns: a header, then one line per row. */
function table(cols, rows) {
let w = map(cols, (c) => length(c));
for (let r in rows)
for (let i, v in r)
w[i] = max(w[i], length(`${v}`));
let line = (r) => rtrim(join(' ', map(r, (v, i) => sprintf(`%-${w[i]}s`, `${v}`))));
out(line(cols));
for (let r in rows)
out(line(r));
}
/** `--since 30m|2h|3d|YYYY-MM-DD` as a time, or null. */
function since_time(s) {
if (!s)
return null;
let m = match(s, /^([0-9]+)([mhd])$/);
if (m)
return time() - +m[1] * { m: 60, h: 3600, d: 86400 }[m[2]];
m = match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
if (m)
return timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 0, min: 0, sec: 0 });
die('--since takes 30m, 2h, 3d or a date like 2026-10-18.');
}
/** "5m", "3h", "2d": how long ago, for the lists. */
function ago(secs) {
return secs < 3600 ? `${int(secs / 60)}m` : secs < 86400 ? `${int(secs / 3600)}h` : `${int(secs / 86400)}d`;
}
function the_person(m, slug) {
return m.people[slug ?? ''] ?? die(slug ? `Unknown person: ${slug}.` : 'Which person? Give their id (dawnline person ls).');
} }
function help() { function help() {
@@ -39,19 +91,24 @@ Usage: dawnline <command>
sync Push devices and access rules to the tunnels sync Push devices and access rules to the tunnels
status People and devices with live state (JSON) status People and devices with live state (JSON)
health Run health checks (JSON) health Run health checks (JSON)
person ls [--json] Everyone: id, name, access, state, devices, last seen
person add <name> [--slug s] [--access lan|internet|both] [--devices n] person add <name> [--slug s] [--access lan|internet|both] [--devices n]
[--expires YYYY-MM-DD] [--quota GB] [--expires YYYY-MM-DD] [--quota GB] [--server id]
person link <slug> Print the personal portal link person link <id> Print the personal portal link
person rm <slug> Remove a person and their devices person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
device add <slug> <name> [--kind phone|computer|tablet|router] device ls [person] [--json]
device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
device conf <id> Print a device configuration (.conf) device conf <id> Print a device configuration (.conf)
device rm <id> Remove a device device rm <id> Remove a device
backup Create a backup in /etc/dawnline/backups backup Create a backup in /etc/dawnline/backups
portal-cert Print the certificate and key the portal uses portal-cert Print the certificate and key the portal uses
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
log Service log: tunnel and service starts, stops, repairs (newest first) log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
Service log: tunnel and service starts, stops, repairs (newest first)
teardown Remove everything Dawnline created on the router teardown Remove everything Dawnline created on the router
version`); version
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
} }
/* /*
@@ -83,7 +140,7 @@ function ifup_failed(ifname, who) {
return out; return out;
}); });
if (r) if (r)
slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start", slog('awg', 'error', r.n > 1 ? sprintf(L_("couldn't start · %d failed attempts in %d min"), r.n, r.mins) : L_("couldn't start"),
watchdog.iface_errors(ifname), who); watchdog.iface_errors(ifname), who);
} }
@@ -106,40 +163,100 @@ try {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u); let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true }))); out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
} }
else if (cmd == 'health') else if (cmd == 'health') {
out(health.health()); let checks = health.health();
out(checks);
if (length(filter(checks, (c) => c.status == 'error')))
exit(1);
}
else if (cmd == 'person' && args[1] == 'ls') {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
if (opts.json)
out(people);
else
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
]));
}
else if (cmd == 'person' && args[1] == 'add') { else if (cmd == 'person' && args[1] == 'add') {
let id = store.transact((c, m) => core.create_person(c, m, { let id = store.transact((c, m) => core.create_person(c, m, {
name: args[2], slug: opt('slug'), access: opt('access', 'internet'), name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'), device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
})); }));
let m2 = core.load(); let m2 = core.load();
out(core.portal_url(m2, m2.people[id]) ?? id); live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
out(`Added ${m2.people[id].name} (${id})`);
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
} }
else if (cmd == 'person' && args[1] == 'link') { else if (cmd == 'person' && args[1] == 'link') {
let m = core.load(); let m = core.load();
let p = m.people[args[2]] ?? die('Unknown person.'); let p = the_person(m, args[2]);
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.'); out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
} }
else if (cmd == 'person' && args[1] == 'rm') { else if (cmd == 'person' && args[1] == 'rm') {
store.transact((c, m) => core.delete_person(c, m, args[2])); let m = core.load();
apply.sync(); let p = the_person(m, args[2]);
let n = length(p.devices);
if (n && !opts.yes)
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
store.transact((c, m) => core.delete_person(c, m, p.id));
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
let s = apply.sync();
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
if (s.warning)
warn(`dawnline: ${s.warning}\n`);
}
else if (cmd == 'device' && args[1] == 'ls') {
let m = core.load(), d = live.dump(m);
let who = args[2] ? the_person(m, args[2]) : null;
let rows = [];
for (let id, dev in m.devices) {
let p = m.people[dev.person];
if (!p || (who && p.id != who.id))
continue;
let peer = d.peers[dev.public_key];
let online = live.online(d, id, peer);
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
online, handshake: +(peer?.handshake ?? 0) });
}
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
if (opts.json)
out(rows);
else
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
r.id, r.person, r.name, r.kind, r.address,
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
]));
} }
else if (cmd == 'device' && args[1] == 'add') { else if (cmd == 'device' && args[1] == 'add') {
// Keys first: generating them runs the awg tool, not worth holding the config lock for. // Through the same door as LuCI and the portal: event, "issued" marker, capability check.
let keys = awg.new_keys(); let m = core.load();
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys })); let p = the_person(m, args[2]);
apply.sync(); if (!args[3])
out(id); die('Which name? dawnline device add <person> <name>.');
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
if (opts.conf)
print(r.config.conf);
else
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
} }
else if (cmd == 'device' && args[1] == 'conf') { else if (cmd == 'device' && args[1] == 'conf') {
let m = core.load(); let m = core.load();
let d = m.devices[args[2]] ?? die('Unknown device.'); let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
awg.mark_issued(m, d.id);
print(awg.client_config(m, d).conf); print(awg.client_config(m, d).conf);
} }
else if (cmd == 'device' && args[1] == 'rm') { else if (cmd == 'device' && args[1] == 'rm') {
store.transact((c, m) => core.delete_device(c, m, args[2])); let m = core.load();
apply.sync(); let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
let r = devices.remove(d.id, { by: 'admin' });
out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
} }
else if (cmd == 'backup') else if (cmd == 'backup')
out(backup.backup_create(opt('reason'))); out(backup.backup_create(opt('reason')));
@@ -153,7 +270,22 @@ try {
out(`${core.portal_http_port(m)}`); out(`${core.portal_http_port(m)}`);
} }
else if (cmd == 'log') { else if (cmd == 'log') {
for (let e in watchdog.view(core.load()).log) { let n = +opt('n', 0) || 0;
let since = since_time(opt('since'));
let level = opt('level'), src = opt('src');
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
die('--level takes error, down, repair, up or info.');
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
die('--src takes awg, dawnline or portal.');
let log = filter(slog_read(n && !since && !level && !src ? n : null),
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
if (n && length(log) > n)
log = slice(log, 0, n);
if (opts.json) {
out(log);
exit(0);
}
for (let e in log) {
let t = localtime(e.ts); let t = localtime(e.ts);
let text = e.by == 'admin' let text = e.by == 'admin'
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x)) ? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
@@ -177,16 +309,16 @@ try {
if (args[1] == 'ifup') { if (args[1] == 'ifup') {
ifup_ok(ifname); ifup_ok(ifname);
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`); let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who); slog('awg', 'up', port ? sprintf(L_('started · accepting connections on port %s'), port) : L_('started'), null, who);
} }
else if (args[1] == 'ifdown') { else if (args[1] == 'ifdown') {
// Stops Dawnline made itself are explained by the admin's own line // Stops Dawnline made itself are explained by the admin's own line
// (changed, turned off, removed); only an AmneziaWG update gets one here. // (changed, turned off, removed); only an AmneziaWG update gets one here.
if (it?.reason == 'update') if (it?.reason == 'update')
slog('awg', 'info', 'restarting for the AmneziaWG update', null, who); slog('awg', 'info', L_('restarting for the AmneziaWG update'), null, who);
else if (!it) else if (!it)
slog('awg', 'down', 'stopped unexpectedly', join('\n', filter([ slog('awg', 'down', L_('stopped unexpectedly'), join('\n', filter([
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.", L_("Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed."),
watchdog.iface_errors(ifname), watchdog.iface_errors(ifname),
], (x) => x)), who); ], (x) => x)), who);
} }
@@ -197,8 +329,12 @@ try {
apply.teardown(); apply.teardown();
else if (cmd == 'version') else if (cmd == 'version')
out(VERSION); out(VERSION);
else else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
help(); help();
else {
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
exit(2);
}
} }
catch (e) { catch (e) {
warn(`dawnline: ${e.message}\n`); warn(`dawnline: ${e.message}\n`);
@@ -13,7 +13,7 @@
import * as uloop from 'uloop'; import * as uloop from 'uloop';
import { open, readfile, writefile, stat, unlink } from 'fs'; import { open, readfile, writefile, stat, unlink } from 'fs';
import { import {
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util'; } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
@@ -26,6 +26,7 @@ import * as net from 'dawnline.net';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import * as upd from 'dawnline.updates'; import * as upd from 'dawnline.updates';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
import { L_ } from 'dawnline.i18n';
const TICK = 60 * 1000; const TICK = 60 * 1000;
const WATCH = 1000; const WATCH = 1000;
@@ -154,41 +155,6 @@ function check_people(m, states, events) {
} }
} }
let last_home = 0;
// Addresses the watcher saw connect since the last tick: looked up first.
let geo_pending = {};
/**
* Locate client addresses for the admin map: the ones that just connected
* first, then anything still shown that is missing or stale — a few per
* minute, within a time budget, so a slow service never holds the tick.
*/
function check_geo(m) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
let cache = geo.load();
let ips = keys(geo_pending);
geo_pending = {};
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
let changed = geo.resolve(m.settings, cache, uniq(ips), 3, 12);
if (time() - last_home > 3600) {
last_home = time();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
changed = geo.resolve_home(m.settings, cache, wan) || changed;
}
if (changed)
geo.save(cache);
}
function place_of(ip) {
let pl = geo.place(geo.load(), ip);
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
}
/** Connections from home: the DHCP name of the address, as it is now. */ /** Connections from home: the DHCP name of the address, as it is now. */
function named(e) { function named(e) {
let h = net.event_hosts(e, net.lan_names()); let h = net.event_hosts(e, net.lan_names());
@@ -225,6 +191,116 @@ function save_presence(people) {
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600); write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
} }
/* ---------- locations ---------- */
// A lookup run: this many addresses at most, within this many seconds; a run
// still going after GEO_KILL seconds (past every timeout) is given up.
const GEO_PER_RUN = 3;
const GEO_BUDGET = 12;
const GEO_KILL = 60;
let last_home = 0;
// Addresses the watcher saw connect or roam that wait for a run.
let geo_pending = {};
// The run in a child process (uloop.task) and when it started; null when none.
let geo_task = null, geo_since = 0;
/** Every client address still shown on the map (the cache never pushes these out). */
function geo_shown() {
let ips = [];
for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {}))
push(ips, ip);
return uniq(ips);
}
/*
* A run's results: into the cache (the agent is its only writer), onto the
* connections in the activity log that were logged before their place was
* known, and to open pages at once: the revision moves for the people seen
* from those addresses.
*/
function geo_done(found) {
let cache = geo.load();
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
return;
geo.save(cache);
let where = {};
for (let ip, r in found)
if (r)
where[ip] = geo.label(r);
if (!length(keys(where)))
return;
let m = watch_model(), people = {};
for (let id, rec in usage.devices)
for (let ip in keys(where))
if (rec.ips?.[ip] && m.devices[id])
people[m.devices[id].person] = true;
live.set_places(where, time() - 3600);
save_presence(keys(people));
}
/*
* Locate client addresses for the admin map in a child process: a lookup
* waits on the network for seconds, and neither the 1-second watcher nor the
* tick may wait with it. Addresses that just connected go first, at once
* (the watcher calls this on a connect); the tick adds anything still shown
* that is missing or stale (`more`). One run at a time, a few addresses each;
* what just connected and did not fit waits for the next run.
*/
function geo_lookup(m, more) {
if (!m.settings.geo_enabled) {
geo_pending = {};
return;
}
if (geo_task && !geo_task.finished()) {
if (time() - geo_since < GEO_KILL)
return;
geo_task.kill();
}
geo_task = null;
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
let want = slice(todo, 0, GEO_PER_RUN);
let rest = {};
for (let ip in slice(todo, GEO_PER_RUN))
if (geo_pending[ip])
rest[ip] = true;
geo_pending = rest;
if (!length(want))
return;
let provider = m.settings.geo_provider;
let t = null;
t = uloop.task(() => {
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
instance.close();
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
}, (found) => {
if (geo_task == t)
geo_task = null;
geo_done(found);
if (length(keys(geo_pending)))
geo_lookup(watch_model());
});
geo_task = t;
geo_since = time();
}
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
function check_geo(m) {
geo_lookup(m, geo_shown());
if (!m.settings.geo_enabled || time() - last_home <= 3600)
return;
last_home = time();
let cache = geo.load();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
if (geo.resolve_home(m.settings, cache, wan))
geo.save(cache);
}
function place_of(ip) {
return geo.label(geo.place(geo.load(), ip));
}
/* /*
* One look at the tunnels. Connects (a new handshake from a device that was * One look at the tunnels. Connects (a new handshake from a device that was
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW; * away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
@@ -282,16 +358,19 @@ function watch() {
return; return;
live.collect(m, usage, d); live.collect(m, usage, d);
live.save_usage(usage, false); live.save_usage(usage, false);
// A location lookup waits on the network: never here, on the next tick // The event carries the place when the cache already knows it. A new
// (check_geo). The event carries the place when the cache already knows it. // address is looked up at once, in a child process (geo_lookup): its place
if (m.settings.geo_enabled) // goes onto this event and the revision moves again when it is known.
for (let ip in ips)
geo_pending[ip] = true;
for (let e in events) for (let e in events)
if (e.type == 'connect') if (e.type == 'connect')
e.where = place_of(e.detail); e.where = place_of(e.detail);
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention)); live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
save_presence(keys(people)); save_presence(keys(people));
if (m.settings.geo_enabled && length(ips)) {
for (let ip in ips)
geo_pending[ip] = true;
geo_lookup(m);
}
} }
// What the service log was already told. On flash: the public address often // What the service log was already told. On flash: the public address often
@@ -306,6 +385,33 @@ function note(k, v) {
write_json(NOTES, notes, 0o600); write_json(NOTES, notes, 0o600);
} }
/*
* End dates in the activity log: a heads-up once per end date when its
* warning window opens, and "keep access" passing it (which changes no
* state, so nothing else would say it). Not on a clock that is not set.
*/
function check_expiry(m, events) {
let ts = time();
if (localtime(ts).year < 2025)
return;
for (let id, p in m.people) {
if (!p.expires)
continue;
let end = date_end(p.expires);
if (end == null)
continue;
let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
note(`warned:${id}`, p.expires);
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
}
if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
note(`kept:${id}`, p.expires);
push(events, { type: 'expired_kept', person: id, detail: p.expires });
}
}
}
/** "Jan 1 2027" from the certificate, or null. */ /** "Jan 1 2027" from the certificate, or null. */
function cert_end(path) { function cert_end(path) {
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/); let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
@@ -318,7 +424,7 @@ function check_cert(m) {
let c = pc.portal_cert(m.settings); let c = pc.portal_cert(m.settings);
let mt = stat(c.cert)?.mtime; let mt = stat(c.cert)?.mtime;
if (cert_mtime != null && mt != null && mt != cert_mtime) { if (cert_mtime != null && mt != null && mt != cert_mtime) {
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal'); slog('portal', 'up', sprintf(L_('certificate renewed · valid until %s'), cert_end(c.cert) ?? '?'), null, L_('Personal portal'));
system('/etc/init.d/dawnline reload >/dev/null 2>&1 &'); system('/etc/init.d/dawnline reload >/dev/null 2>&1 &');
} }
cert_mtime = mt; cert_mtime = mt;
@@ -327,8 +433,9 @@ function check_cert(m) {
return; return;
last_cert_check = time(); last_cert_check = time();
if (notes.cert_warned != mt && system(`openssl x509 -checkend 604800 -noout -in ${q(c.cert)} >/dev/null 2>&1`) != 0) { if (notes.cert_warned != mt && system(`openssl x509 -checkend 604800 -noout -in ${q(c.cert)} >/dev/null 2>&1`) != 0) {
slog('portal', 'error', `certificate expires ${cert_end(c.cert) ?? 'within 7 days'}`, let end = cert_end(c.cert);
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.', 'Personal portal'); slog('portal', 'error', end ? sprintf(L_('certificate expires %s'), end) : L_('certificate expires within 7 days'),
L_('Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.'), L_('Personal portal'));
note('cert_warned', mt); note('cert_warned', mt);
} }
} }
@@ -349,10 +456,13 @@ function check_wan(m) {
return; return;
let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name); let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name);
if (length(stuck)) if (length(stuck))
slog('dawnline', 'error', `public address changed · ${was} → ${ip}`, slog('dawnline', 'error', sprintf(L_('public address changed · %s → %s'), was, ip),
`${join(', ', stuck)} still give${length(stuck) == 1 ? 's' : ''} devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.`, 'Router'); sprintf(length(stuck) == 1
? L_('%s still gives devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.')
: L_('%s still give devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.'),
join(', ', stuck)), L_('Router'));
else else
slog('dawnline', 'info', `public address changed · ${was} → ${ip}`, null, 'Router'); slog('dawnline', 'info', sprintf(L_('public address changed · %s → %s'), was, ip), null, L_('Router'));
} }
let last_backup_day = null; let last_backup_day = null;
@@ -371,7 +481,7 @@ function nightly_backup() {
} }
catch (e) { catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly). // Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
slog('dawnline', 'error', `nightly backup failed: ${e.message}`, null, 'Backup'); slog('dawnline', 'error', sprintf(L_('nightly backup failed: %s'), e.message), null, L_('Backup'));
} }
} }
} }
@@ -440,7 +550,7 @@ function check_network(t) {
return; return;
} }
pending_net = null; pending_net = null;
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router'); slog('dawnline', 'info', L_('network changed - Dawnline set itself up again'), null, L_('Router'));
apply.apply(); apply.apply();
base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load()); base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load());
} }
@@ -456,32 +566,33 @@ const STEPS = [
t.m = core.load(); t.m = core.load();
t.pol = live.policy(t.m.settings.retention); t.pol = live.policy(t.m.settings.retention);
} }, } },
{ who: 'Traffic', run: (t) => { { who: L_('Traffic'), run: (t) => {
t.reset = check_usage_reset(t.m); t.reset = check_usage_reset(t.m);
live.collect(t.m, usage, live.dump(t.m)); live.collect(t.m, usage, live.dump(t.m));
} }, } },
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) }, { who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) },
{ who: 'People', run: (t) => { { who: L_('People'), run: (t) => {
t.states = apply.states_for(t.m, usage); t.states = apply.states_for(t.m, usage);
check_people(t.m, t.states, t.events); check_people(t.m, t.states, t.events);
check_expiry(t.m, t.events);
} }, } },
{ who: 'Access rules', run: (t) => { { who: L_('Access rules'), run: (t) => {
if (t.states) if (t.states)
sync_runtime(t); sync_runtime(t);
} }, } },
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons. // Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
{ who: 'Activity', run: (t) => { { who: L_('Activity'), run: (t) => {
live.add_events(t.events, t.pol); live.add_events(t.events, t.pol);
// Pauses and resumes on their own: the UI shows them without waiting for its next poll. // Pauses and resumes on their own: the UI shows them without waiting for its next poll.
if (length(t.events)) if (length(t.events))
save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person))); save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person)));
} }, } },
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) }, { who: L_('Internet like a home device'), run: (t) => apply.sync_loop(t.m, usage) },
{ who: 'Router', run: check_network }, { who: L_('Router'), run: check_network },
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) }, { who: L_('Watchdog'), run: (t) => watchdog.run(core.load()) },
{ who: 'Personal portal', run: (t) => check_cert(t.m) }, { who: L_('Personal portal'), run: (t) => check_cert(t.m) },
{ who: 'Router', quiet: true, run: (t) => check_wan(t.m) }, { who: L_('Router'), quiet: true, run: (t) => check_wan(t.m) },
{ who: 'Backup', run: (t) => nightly_backup() }, { who: L_('Backup'), run: (t) => nightly_backup() },
{ who: 'updates', quiet: true, run: (t) => check_updates(t.m) }, { who: 'updates', quiet: true, run: (t) => check_updates(t.m) },
{ who: 'geo', quiet: true, run: (t) => check_geo(t.m) }, { who: 'geo', quiet: true, run: (t) => check_geo(t.m) },
]; ];
@@ -497,7 +608,7 @@ function step(i, s, fn) {
catch (e) { catch (e) {
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`); system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
if (!s.quiet && step_err[i] != e.message) if (!s.quiet && step_err[i] != e.message)
slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who); slog('dawnline', 'error', sprintf(L_('failed: %s'), e.message), e.stacktrace?.[0]?.context, s.who);
step_err[i] = e.message; step_err[i] = e.message;
} }
} }
@@ -519,7 +630,7 @@ function tick() {
step(i, s, () => s.run(t)); step(i, s, () => s.run(t));
let persist = t.reset || time() - last_flush >= FLUSH_EVERY; let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
step('save', { who: 'Traffic' }, () => { step('save', { who: L_('Traffic') }, () => {
live.save_usage(usage, persist); live.save_usage(usage, persist);
if (persist) { if (persist) {
last_flush = time(); last_flush = time();
@@ -527,7 +638,7 @@ function tick() {
} }
}); });
step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist)); step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
step('events', { who: 'Activity' }, () => { step('events', { who: L_('Activity') }, () => {
let pol = t.pol ?? live.policy(); let pol = t.pol ?? live.policy();
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) { if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
live.persist_events(pol); live.persist_events(pol);
@@ -561,20 +672,20 @@ slog_restore();
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? ''); let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
unlink(`${RUN_DIR}/update-rolled-back`); unlink(`${RUN_DIR}/update-rolled-back`);
if (rolled) if (rolled)
slog('dawnline', 'error', `update to ${rolled} failed its check — rolled back to ${VERSION}`, slog('dawnline', 'error', sprintf(L_('update to %s failed its check - rolled back to %s'), rolled, VERSION),
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.', 'Dawnline'); L_('The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.'), 'Dawnline');
else if (was && was != VERSION) else if (was && was != VERSION)
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline'); slog('dawnline', 'up', sprintf(L_('updated · %s → %s'), was, VERSION), null, 'Dawnline');
else if (crashed) else if (crashed)
slog('dawnline', 'repair', 'stopped unexpectedly — started again', slog('dawnline', 'repair', L_('stopped unexpectedly - started again'),
// Why, when syslog knows: procd, the kernel (out of memory, segfault), ucode errors. // Why, when syslog knows: procd, the kernel (out of memory, segfault), ucode errors.
sh_out('logread -l 400 2>/dev/null | grep -iE "kernel:.*(out of memory|killed process|oom-kill|segfault)|procd:.*dawnline|dawnline/agent" | tail -n 6'), 'Dawnline'); sh_out('logread -l 400 2>/dev/null | grep -iE "kernel:.*(out of memory|killed process|oom-kill|segfault)|procd:.*dawnline|dawnline/agent" | tail -n 6'), 'Dawnline');
else if (stopped && time() - stopped < 300) else if (stopped && time() - stopped < 300)
slog('dawnline', 'info', `restarted · version ${VERSION}`, null, 'Dawnline'); slog('dawnline', 'info', sprintf(L_('restarted · version %s'), VERSION), null, 'Dawnline');
else if (live.uptime() < 600) else if (live.uptime() < 600)
slog('dawnline', 'info', `started with the router · version ${VERSION}`, null, 'Dawnline'); slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
else else
slog('dawnline', 'info', `started · version ${VERSION}`, null, 'Dawnline'); slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline');
uloop.init(); uloop.init();
@@ -584,14 +695,14 @@ timer = uloop.timer(1000, function() {
tick(); tick();
} }
catch (e) { catch (e) {
slog('dawnline', 'error', `background check failed: ${e.message}`, e.stacktrace?.[0]?.context, 'Dawnline'); slog('dawnline', 'error', sprintf(L_('background check failed: %s'), e.message), e.stacktrace?.[0]?.context, 'Dawnline');
} }
timer.set(TICK); timer.set(TICK);
}); });
let watcher; let watcher;
watcher = uloop.timer(WATCH, function() { watcher = uloop.timer(WATCH, function() {
step('watch', { who: 'Connections' }, watch); step('watch', { who: L_('Connections') }, watch);
watcher.set(WATCH); watcher.set(WATCH);
}); });
@@ -12,6 +12,9 @@ KEEP=/etc/dawnline/keep/app
to="${1:-?}" to="${1:-?}"
sleep 2 sleep 2
# LuCI reads a language's catalogs once per web server: a replaced translation
# needs a fresh one, before the new version answers and the page reloads.
ls /usr/lib/lua/luci/i18n/dawnline.*.lmo >/dev/null 2>&1 && /etc/init.d/uhttpd restart >/dev/null 2>&1
/etc/init.d/rpcd reload >/dev/null 2>&1 /etc/init.d/rpcd reload >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1 /etc/init.d/dawnline restart >/dev/null 2>&1
@@ -21,12 +21,18 @@ import * as upd from 'dawnline.updates';
import * as app from 'dawnline.upd_app'; import * as app from 'dawnline.upd_app';
import * as awg from 'dawnline.upd_awg'; import * as awg from 'dawnline.upd_awg';
import * as pkgs from 'dawnline.upd_pkgs'; import * as pkgs from 'dawnline.upd_pkgs';
import * as i18n from 'dawnline.i18n';
import { _, L_ } from 'dawnline.i18n';
// The phases and errors of a job LuCI started are in the admin's language (rpc/updates.uc hands it over).
i18n.use(getenv('DAWNLINE_LANG'));
const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0]; const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0];
const POL = core.load().settings.updates; const POL = core.load().settings.updates;
const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check }; const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check };
const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install }; const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install };
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' }; // Names in the service log (English there, like the rest of it); the phases are checking() and updating().
const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: L_('System packages'), packages: L_('System packages') };
let job = { let job = {
id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null, id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
@@ -82,6 +88,24 @@ const ctx = {
after: (what) => after[what] = true, after: (what) => after[what] = true,
}; };
/** The phase of a component's check (app, amneziawg, packages). */
function checking(name) {
if (name == 'app')
return _('Checking Dawnline');
if (name == 'amneziawg')
return _('Checking AmneziaWG');
return _('Checking system packages');
}
/** The phase of a component's update (app, amneziawg, pkgs). */
function updating(name) {
if (name == 'app')
return _('Updating Dawnline');
if (name == 'amneziawg')
return _('Updating AmneziaWG');
return _('Updating system packages');
}
/* ---------- check results ---------- */ /* ---------- check results ---------- */
function checks_file() { function checks_file() {
@@ -98,7 +122,10 @@ function save_check(res) {
write_json(upd.CHECK_FILE, c, 0o644); write_json(upd.CHECK_FILE, c, 0o644);
} }
/** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */ /**
* What a check found, as short names ("Dawnline 0.3.3", "2 system packages"):
* kept in the history and shown later, so English whatever the job's language.
*/
function found_in(res) { function found_in(res) {
let found = []; let found = [];
if (res.app?.update) if (res.app?.update)
@@ -106,19 +133,19 @@ function found_in(res) {
if (res.amneziawg?.update && res.amneziawg.installed) if (res.amneziawg?.update && res.amneziawg.installed)
push(found, `AmneziaWG ${res.amneziawg.latest}`); push(found, `AmneziaWG ${res.amneziawg.latest}`);
if (res.packages?.updates) if (res.packages?.updates)
push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`); push(found, sprintf(res.packages.updates == 1 ? L_('%d system package') : L_('%d system packages'), res.packages.updates));
return found; return found;
} }
function run_checks(which) { function run_checks(which) {
let res = {}; let res = {};
for (let name in which) { for (let name in which) {
phase(`Checking ${WHO[name]}`); phase(checking(name));
try { try {
res[name] = CHECKS[name](ctx); res[name] = CHECKS[name](ctx);
} }
catch (e) { catch (e) {
log(`Error: ${e.message}`); log(sprintf(_('Error: %s'), e.message));
res[name] = { error: e.message, status: '' }; res[name] = { error: e.message, status: '' };
} }
} }
@@ -132,7 +159,7 @@ function note_found(res, st, auto) {
let sig = join(', ', found); let sig = join(', ', found);
if (length(found) && sig != st.announced) { if (length(found) && sig != st.announced) {
if (auto) if (auto)
slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components'); slog('dawnline', 'info', sprintf(L_('updates available · %s'), sig), null, L_('Components'));
upd.history_add({ kind: 'found', items: found, auto }); upd.history_add({ kind: 'found', items: found, auto });
} }
st.announced = sig; st.announced = sig;
@@ -142,14 +169,14 @@ function note_found(res, st, auto) {
/** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */ /** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
function log_update(name, r) { function log_update(name, r) {
let how = job.auto ? ' automatically' : '';
if (name == 'amneziawg') { if (name == 'amneziawg') {
let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg']; let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}` slog('awg', 'up', b && a && b != a ? sprintf(job.auto ? L_('updated automatically · %s → %s') : L_('updated · %s → %s'), b, a)
: `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, 'AmneziaWG'); : a ? sprintf(L_('installed the %s build · %s'), r?.build ?? '', a) : sprintf(L_('installed the %s build'), r?.build ?? ''), null, 'AmneziaWG');
} }
else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ])) else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
slog('dawnline', 'up', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages'); slog('dawnline', 'up', sprintf(job.auto ? L_('updated automatically · %s') : L_('updated · %s'),
join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])), null, L_('System packages'));
} }
function split_target(w) { function split_target(w) {
@@ -172,9 +199,9 @@ function install(what) {
for (let w in what) { for (let w in what) {
let t = split_target(w), name = t[0], arg = t[1]; let t = split_target(w), name = t[0], arg = t[1];
if (!INSTALLS[name]) if (!INSTALLS[name])
die(`Unknown component ${name}`); die(sprintf(_('Unknown component %s'), name));
job.current = name; job.current = name;
phase(`Updating ${WHO[name]}`); phase(updating(name));
let r = INSTALLS[name](ctx, arg); let r = INSTALLS[name](ctx, arg);
job.result[name] = r; job.result[name] = r;
log_update(name, r); log_update(name, r);
@@ -228,7 +255,7 @@ function auto() {
if (a.current && !a.gen_change) if (a.current && !a.gen_change)
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`); push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
else else
slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG'); slog('awg', 'info', a.latest ? sprintf(L_('%s needs a manual switch in Components'), a.latest) : L_('a new build needs a manual switch in Components'), null, 'AmneziaWG');
} }
if (index(POL.targets, 'app') >= 0 && res.app?.update) if (index(POL.targets, 'app') >= 0 && res.app?.update)
push(todo, 'app'); push(todo, 'app');
@@ -239,7 +266,7 @@ function auto() {
job.component = join(' ', todo); job.component = join(' ', todo);
job.auto = true; job.auto = true;
job.log = []; job.log = [];
log(`Automatic update: ${join(', ', todo)}`); log(sprintf(_('Automatic update: %s'), join(', ', todo)));
install(todo); install(todo);
} }
@@ -257,7 +284,8 @@ function restarts() {
let cmds = []; let cmds = [];
if (after.apply) if (after.apply)
push(cmds, '/usr/bin/dawnline apply'); push(cmds, '/usr/bin/dawnline apply');
if (after.uhttpd) // LuCI's own web server reads a language's catalogs once: a new translation needs a fresh one.
if (after.uhttpd || after.luci)
push(cmds, '/etc/init.d/uhttpd restart'); push(cmds, '/etc/init.d/uhttpd restart');
if (after.apply || after.uhttpd) if (after.apply || after.uhttpd)
push(cmds, '/etc/init.d/dawnline restart'); push(cmds, '/etc/init.d/dawnline restart');
@@ -265,6 +293,46 @@ function restarts() {
system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`); system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
} }
/** The job the command line asks for, to its final state: done, or failed with the error in the log and the history. */
function main() {
try {
if (job.action == 'check') {
let which = job.component ? [ job.component ] : upd.TARGETS;
for (let w in which)
if (!CHECKS[w])
die(sprintf(_('Unknown component %s'), w));
job.result = run_checks(which);
let st = upd.auto_state();
note_found(job.result, st, false);
if (length(which) == length(upd.TARGETS))
st.check = time();
upd.auto_save(st);
}
else if (job.action == 'install')
install([ job.component ]);
else if (job.action == 'auto')
auto();
else
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done';
phase(_('Finished'));
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(sprintf(_('Error: %s'), e.message));
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
if (job.action != 'check') {
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', job.auto ? L_('automatic update failed') : L_('update failed'), e.message, WHO[name] ?? 'Dawnline');
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
took: time() - job.started });
}
else
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
}
}
/* ---------- main ---------- */ /* ---------- main ---------- */
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
@@ -279,43 +347,7 @@ if (!LOCK)
exit(0); exit(0);
fs.mkdir(ctx.work, 0o700); fs.mkdir(ctx.work, 0o700);
save(); save();
main();
try {
if (job.action == 'check') {
let which = job.component ? [ job.component ] : upd.TARGETS;
for (let w in which)
if (!CHECKS[w])
die(`Unknown component ${w}`);
job.result = run_checks(which);
let st = upd.auto_state();
note_found(job.result, st, false);
if (length(which) == length(upd.TARGETS))
st.check = time();
upd.auto_save(st);
}
else if (job.action == 'install')
install([ job.component ]);
else if (job.action == 'auto')
auto();
else
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done';
phase('Finished');
}
catch (e) {
quiet = false;
job.state = 'failed';
job.error = e.message;
log(`Error: ${e.message}`);
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
if (job.action != 'check') {
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', `${job.auto ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline');
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
took: time() - job.started });
}
else
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
}
system(`rm -rf '${ctx.work}'`); system(`rm -rf '${ctx.work}'`);
job.finished = time(); job.finished = time();
@@ -1 +1 @@
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--line);border-radius:12px;background:var(--card);font-size:14px;line-height:20px}.alert-ic{width:30px;height:30px;border-radius:9px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:var(--warn-wash);color:var(--warn)}.alert-ic.bad{background:var(--bad-wash);color:var(--bad)}.alert-ic .ic-svg{width:15px;height:15px}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{backgrouLine truncated @font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var ut=Object.create;var Ke=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var vt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of ft(t))!pt.call(e,l)&&l!==r&&Ke(e,l,{get:()=>t[l],enumerable:!(s=dt(t,l))||s.enumerable});return e};var mt=(e,t,r)=>(r=e!=null?ut(ht(e)):{},gt(t||!e||!e.__esModule?Ke(r,"default",{value:e,enumerable:!0}):r,e));var Qe=vt((ze,Je)=>{"use strict";var je=(function(){var e=function(x,k){var b=236,f=17,c=x,y=r[k],i=null,a=0,w=null,h=[],m={},L=function(u,d){a=c*4+17,i=(function(o){for(var p=new Array(o),g=0;g<o;g+=1){p[g]=new Array(o);for(var M=0;M<o;M+=1)p[g][M]=null}return p})(a),D(0,0),D(a-7,0),D(0,a-7),G(),K(),J(u,d),c>=7&&z(u),w==null&&(w=ct(c,y,h)),Q(w,d)},D=function(u,d){for(var o=-1;o<=7;o+=1)if(!(u+o<=-1||a<=u+o))for(var p=-1;p<=7;p+=1)d+p<=-1||a<=d+p||(0<=o&&o<=6&&(p==0||p==6)||0<=p&&p<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=p&&p<=4?i[u+o][d+p]=!0:i[u+o][d+p]=!1)},S=function(){for(var u=0,d=0,o=0;o<8;o+=1){L(!0,o);var p=l.getLostPoint(m);(o==0||u>p)&&(u=p,d=o)}return d},K=function(){for(var u=8;u<a-8;u+=1)i[u][6]==null&&(i[u][6]=u%2==0);for(var d=8;d<a-8;d+=1)i[6][d]==null&&(i[6][d]=d%2==0)},G=function(){for(var u=l.getPatternPosition(c),d=0;d<u.length;d+=1)for(var o=0;o<u.length;o+=1){var p=u[d],g=u[o];if(i[p][g]==null)for(var M=-2;M<=2;M+=1)for(var C=-2;C<=2;C+=1)M==-2||M==2||C==-2||C==2||M==0&&C==0?i[p+M][g+C]=!0:i[p+M][g+C]=!1}},z=function(u){for(var d=l.getBCHTypeNumber(c),o=0;o<18;o+=1){var p=!u&&(d>>o&1)==1;i[Math.floor(o/3)][o%3+a-8-3]=p}for(var o=0;o<18;o+=1){var p=!u&&(d>>o&1)==1;i[o%3+a-8-3][Math.floor(o/3)]=p}},J=function(u,d){for(var o=y<<3|d,p=l.getBCHTypeInfo(o),g=0;g<15;g+=1){var M=!u&&(p>>g&1)==1;g<6?i[g][8]=M:g<8?i[g+1][8]=M:i[a-15+g][8]=M}for(var g=0;g<15;g+=1){var M=!u&&(p>>g&1)==1;g<8?i[8][a-g-1]=M:g<9?i[8][15-g-1+1]=M:i[8][15-g-1]=M}i[a-8][8]=!u},Q=function(u,d){for(var o=-1,p=a-1,g=7,M=0,C=l.getMaskFunction(d),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(i[p][_-R]==null){var F=!1;M<u.length&&(F=(u[M]>>>g&1)==1);var T=C(p,_-R);T&&(F=!F),i[p][_-R]=F,g-=1,g==-1&&(M+=1,g=7)}if(p+=o,p<0||a<=p){p-=o,o=-o;break}}},re=function(u,d){for(var o=0,p=0,g=0,M=new Array(d.length),C=new Array(d.length),_=0;_<d.length;_+=1){var R=d[_].dataCount,F=d[_].totalCount-R;p=Math.max(p,R),g=Math.max(g,F),M[_]=new Array(R);for(var T=0;T<M[_].length;T+=1)M[_][T]=255&u.getBuffer()[T+o];o+=R;var Y=l.getErrorCorrectPolynomial(F),j=A(M[_],Y.getLength()-1),He=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ie=T+He.getLength()-C[_].length;C[_][T]=Ie>=0?He.getAt(Ie):0}}for(var Oe=0,T=0;T<d.length;T+=1)Oe+=d[T].totalCount;for(var xe=new Array(Oe),he=0,T=0;T<p;T+=1)for(var _=0;_<d.length;_+=1)T<M[_].length&&(xe[he]=M[_][T],he+=1);for(var T=0;T<g;T+=1)for(var _=0;_<d.length;_+=1)T<C[_].length&&(xe[he]=C[_][T],he+=1);return xe},ct=function(u,d,o){for(var p=E.getRSBlocks(u,d),g=N(),M=0;M<o.length;M+=1){var C=o[M];g.put(C.getMode(),4),g.put(C.getLength(),l.getLengthInBits(C.getMode(),u)),C.write(g)}for(var _=0,M=0;M<p.length;M+=1)_+=p[M].dataCount;if(g.getLengthInBits()>_*8)throw"code length overflow. ("+g.getLengthInBits()+">"+_*8+")";for(g.getLengthInBits()+4<=_*8&&g.put(0,4);g.getLengthInBits()%8!=0;)g.putBit(!1);for(;!(g.getLengthInBits()>=_*8||(g.put(b,8),g.getLengthInBits()>=_*8));)g.put(f,8);return re(g,p)};m.addData=function(u,d){d=d||"Byte";var o=null;switch(d){case"Numeric":o=$(u);break;case"Alphanumeric":o=P(u);break;case"Byte":o=q(u);break;case"Kanji":o=O(u);break;default:throw"mode:"+d}h.push(o),w=null},m.isDark=function(u,d){if(u<0||a<=u||d<0||a<=d)throw u+","+d;return i[u][d]},m.getModuleCount=function(){return a},m.make=function(){if(c<1){for(var u=1;u<40;u++){for(var d=E.getRSBlocks(u,y),o=N(),p=0;p<h.length;p++){var g=h[p];o.put(g.getMode(),4),o.put(g.getLength(),l.getLengthInBits(g.getMode(),u)),g.write(o)}for(var M=0,p=0;p<d.length;p++)M+=d[p].dataCount;if(o.getLengthInBits()<=M*8)break}c=u}L(!1,S())},m.createTableTag=function(u,d){u=u||2,d=typeof d=="undefined"?u*4:d;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+d+"px;",o+='">',o+="<tbody>";for(var p=0;p<m.getModuleCount();p+=1){o+="<tr>";for(var g=0;g<m.getModuleCount();g+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+u+"px;",o+=" height: "+u+"px;",o+=" background-color: ",o+=m.isDark(p,g)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},m.createSvgTag=function(u,d,o,p){var g={};typeof arguments[0]=="object"&&(g=arguments[0],u=g.cellSize,d=g.margin,o=g.alt,p=g.title),u=u||2,d=typeof d=="undefined"?u*4:d,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated "use strict";(()=>{var fs=Object.create;var or=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var gs=Object.getPrototypeOf,vs=Object.prototype.hasOwnProperty;var ys=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var bs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ms(t))!vs.call(e,o)&&o!==n&&or(e,o,{get:()=>t[o],enumerable:!(r=hs(t,o))||r.enumerable});return e};var xs=(e,t,n)=>(n=e!=null?fs(gs(e)):{},bs(t||!e||!e.__esModule?or(n,"default",{value:e,enumerable:!0}):n,e));var Vr=ys((Ur,Fr)=>{"use strict";var Kr=(function(){var e=function(d,v){var a=236,h=17,p=d,A=n[v],u=null,c=0,T=null,w=[],C={},I=function(M,k){c=p*4+17,u=(function(y){for(var L=new Array(y),S=0;S<y;S+=1){L[S]=new Array(y);for(var R=0;R<y;R+=1)L[S][R]=null}return L})(c),G(0,0),G(c-7,0),G(0,c-7),re(),J(),ue(M,k),p>=7&&le(M),T==null&&(T=se(p,A,w)),Y(T,k)},G=function(M,k){for(var y=-1;y<=7;y+=1)if(!(M+y<=-1||c<=M+y))for(var L=-1;L<=7;L+=1)k+L<=-1||c<=k+L||(0<=y&&y<=6&&(L==0||L==6)||0<=L&&L<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=L&&L<=4?u[M+y][k+L]=!0:u[M+y][k+L]=!1)},V=function(){for(var M=0,k=0,y=0;y<8;y+=1){I(!0,y);var L=o.getLostPoint(C);(y==0||M>L)&&(M=L,k=y)}return k},J=function(){for(var M=8;M<c-8;M+=1)u[M][6]==null&&(u[M][6]=M%2==0);for(var k=8;k<c-8;k+=1)u[6][k]==null&&(u[6][k]=k%2==0)},re=function(){for(var M=o.getPatternPosition(p),k=0;k<M.length;k+=1)for(var y=0;y<M.length;y+=1){var L=M[k],S=M[y];if(u[L][S]==null)for(var R=-2;R<=2;R+=1)for(var q=-2;q<=2;q+=1)R==-2||R==2||q==-2||q==2||R==0&&q==0?u[L+R][S+q]=!0:u[L+R][S+q]=!1}},le=function(M){for(var k=o.getBCHTypeNumber(p),y=0;y<18;y+=1){var L=!M&&(k>>y&1)==1;u[Math.floor(y/3)][y%3+c-8-3]=L}for(var y=0;y<18;y+=1){var L=!M&&(k>>y&1)==1;u[y%3+c-8-3][Math.floor(y/3)]=L}},ue=function(M,k){for(var y=A<<3|k,L=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var R=!M&&(L>>S&1)==1;S<6?u[S][8]=R:S<8?u[S+1][8]=R:u[c-15+S][8]=R}for(var S=0;S<15;S+=1){var R=!M&&(L>>S&1)==1;S<8?u[8][c-S-1]=R:S<9?u[8][15-S-1+1]=R:u[8][15-S-1]=R}u[c-8][8]=!M},Y=function(M,k){for(var y=-1,L=c-1,S=7,R=0,q=o.getMaskFunction(k),z=c-1;z>0;z-=2)for(z==6&&(z-=1);;){for(var X=0;X<2;X+=1)if(u[L][z-X]==null){var ie=!1;R<M.length&&(ie=(M[R]>>>S&1)==1);var K=q(L,z-X);K&&(ie=!ie),u[L][z-X]=ie,S-=1,S==-1&&(R+=1,S=7)}if(L+=y,L<0||c<=L){L-=y,y=-y;break}}},te=function(M,k){for(var y=0,L=0,S=0,R=new Array(k.length),q=new Array(k.length),z=0;z<k.length;z+=1){var X=k[z].dataCount,ie=k[z].totalCount-X;L=Math.max(L,X),S=Math.max(S,ie),R[z]=new Array(X);for(var K=0;K<R[z].length;K+=1)R[z][K]=255&M.getBuffer()[K+y];y+=X;var ye=o.getErrorCorrectPolynomial(ie),be=l(R[z],ye.getLength()-1),tr=be.mod(ye);q[z]=new Array(ye.getLength()-1);for(var K=0;K<q[z].length;K+=1){var nr=K+tr.getLength()-q[z].length;q[z][K]=nr>=0?tr.getAt(nr):0}}for(var rr=0,K=0;K<k.length;K+=1)rr+=k[K].totalCount;for(var wn=new Array(rr),Nt=0,K=0;K<L;K+=1)for(var z=0;z<k.length;z+=1)K<R[z].length&&(wn[Nt]=R[z][K],Nt+=1);for(var K=0;K<S;K+=1)for(var z=0;z<k.length;z+=1)K<q[z].length&&(wn[Nt]=q[z][K],Nt+=1);return wn},se=function(M,k,y){for(var L=m.getRSBlocks(M,k),S=g(),R=0;R<y.length;R+=1){var q=y[R];S.put(q.getMode(),4),S.put(q.getLength(),o.getLengthInBits(q.getMode(),M)),q.write(S)}for(var z=0,R=0;R<L.length;R+=1)z+=L[R].dataCount;if(S.getLengthInBits()>z*8)throw"code length overflow. ("+S.getLengthInBits()+">"+z*8+")";for(S.getLengthInBits()+4<=z*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=z*8||(S.put(a,8),S.getLengthInBits()>=z*8));)S.put(h,8);return te(S,L)};C.addData=function(M,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=f(M);break;case"Alphanumeric":y=E(M);break;case"Byte":y=x(M);break;case"Kanji":y=b(M);break;default:throw"mode:"+k}w.push(y),T=null},C.isDark=function(M,k){if(M<0||c<=M||k<0||c<=k)throw M+","+k;return u[M][k]},C.getModuleCount=function(){return c},C.make=function(){if(p<1){for(var M=1;M<40;M++){for(var k=m.getRSBlocks(M,A),y=g(),L=0;L<w.length;L++){var S=w[L];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),M)),S.write(y)}for(var R=0,L=0;L<k.length;L++)R+=k[L].dataCount;if(y.getLengthInBits()<=R*8)break}p=M}I(!1,V())},C.createTableTag=function(M,k){M=M||2,k=typeof k=="undefined"?M*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var L=0;L<C.getModuleCount();L+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+M+"px;",y+=" height: "+M+"px;",y+=" background-color: ",y+=C.isDark(L,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(M,k,y,L){var S={};typeof arguments[0]=="object"&&(S=arguments[0],M=S.cellSize,k=S.margin,y=S.alt,L=S.title),M=M||2,k=typeof k=="undefined"?M*4:k,y=typeof y=="string"?{text:y}:y|Line truncated
`}return o%2&&u>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return m.createASCII=function(u,d){if(u=u||1,u<2)return lt(d);u-=1,d=typeof d=="undefined"?u*2:d;var o=m.getModuleCount()*u+d*2,p=d,g=o-d,M,C,_,R,F=Array(u+1).join("██"),T=Array(u+1).join(" "),Y="",j="";for(M=0;M<o;M+=1){for(_=Math.floor((M-p)/u),j="",C=0;C<o;C+=1)R=1,p<=C&&C<g&&p<=M&&M<g&&m.isDark(_,Math.floor((C-p)/u))&&(R=0),j+=R?F:T;for(_=0;_<u;_+=1)Y+=j+` `}return y%2&&M>0?be.substring(0,be.length-y-1)+Array(y+1).join("▀"):be.substring(0,be.length-1)};return C.createASCII=function(M,k){if(M=M||1,M<2)return Bt(k);M-=1,k=typeof k=="undefined"?M*2:k;var y=C.getModuleCount()*M+k*2,L=k,S=y-k,R,q,z,X,ie=Array(M+1).join("██"),K=Array(M+1).join(" "),ye="",be="";for(R=0;R<y;R+=1){for(z=Math.floor((R-L)/M),be="",q=0;q<y;q+=1)X=1,L<=q&&q<S&&L<=R&&R<S&&C.isDark(z,Math.floor((q-L)/M))&&(X=0),be+=X?ie:K;for(z=0;z<M;z+=1)ye+=be+`
`}return Y.substring(0,Y.length-1)},m.renderTo2dContext=function(u,d){d=d||2;for(var o=m.getModuleCount(),p=0;p<o;p++)for(var g=0;g<o;g++)u.fillStyle=m.isDark(p,g)?"black":"white",u.fillRect(p*d,g*d,d,d)},m};e.stringToBytesFuncs={default:function(x){for(var k=[],b=0;b<x.length;b+=1){var f=x.charCodeAt(b);k.push(f&255)}return k}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(x,k){var b=(function(){for(var c=le(x),y=function(){var K=c.read();if(K==-1)throw"eof";return K},i=0,a={};;){var w=c.read();if(w==-1)break;var h=y(),m=y(),L=y(),D=String.fromCharCode(w<<8|h),S=m<<8|L;a[D]=S,i+=1}if(i!=k)throw i+" != "+k;return a})(),f=63;return function(c){for(var y=[],i=0;i<c.length;i+=1){var a=c.charCodeAt(i);if(a<128)y.push(a);else{var w=b[c.charAt(i)];typeof w=="number"?(w&255)==w?y.push(w):(y.push(w>>>8),y.push(w&255)):y.push(f)}}return y}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},l=(function(){var x=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,b=7973,f=21522,c={},y=function(i){for(var a=0;i!=0;)a+=1,i>>>=1;return a};return c.getBCHTypeInfo=function(i){for(var a=i<<10;y(a)-y(k)>=0;)a^=k<<y(a)-y(k);return(i<<10|a)^f},c.getBCHTypeNumber=function(i){for(var a=i<<12;y(a)-y(b)>=0;)a^=b<<y(a)-y(b);return i<<12|a},c.getPatternPosition=function(i){return x[i-1]},c.getMaskFunction=function(i){switch(i){case s.PATTERN000:return function(a,w){return(a+w)%2==0};case s.PATTERN001:return function(a,w){return a%2==0};case s.PATTERN010:return function(a,w){return w%3==0};case s.PATTERN011:return function(a,w){return(a+w)%3==0};case s.PATTERN100:return function(a,w){return(Math.floor(a/2)+Math.floor(w/3))%2==0};case s.PATTERN101:return function(a,w){return a*w%2+a*w%3==0};case s.PATTERN110:return function(a,w){return(a*w%2+a*w%3)%2==0};case s.PATTERN111:return function(a,w){return(a*w%3+(a+w)%2)%2==0};default:throw"bad maskPattern:"+i}},c.getErrorCorrectPolynomial=function(i){for(var a=A([1],0),w=0;w<i;w+=1)a=a.multiply(A([1,v.gexp(w)],0));return a},c.getLengthInBits=function(i,a){if(1<=a&&a<10)switch(i){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+i}else if(a<27)switch(i){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+i}else if(a<41)switch(i){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+a},c.getLostPoint=function(i){for(var a=i.getModuleCount(),w=0,h=0;h<a;h+=1)for(var m=0;m<a;m+=1){for(var L=0,D=i.isDark(h,m),S=-1;S<=1;S+=1)if(!(h+S<0||a<=h+S))for(var K=-1;K<=1;K+=1)m+K<0||a<=m+K||S==0&&K==0||D==i.isDark(h+S,m+K)&&(L+=1);L>5&&(w+=3+L-5)}for(var h=0;h<a-1;h+=1)for(var m=0;m<a-1;m+=1){var G=0;i.isDark(h,m)&&(G+=1),i.isDark(h+1,m)&&(G+=1),i.isDark(h,m+1)&&(G+=1),i.isDark(h+1,m+1)&&(G+=1),(G==0||G==4)&&(w+=3)}for(var h=0;h<a;h+=1)for(var m=0;m<a-6;m+=1)i.isDark(h,m)&&!i.isDark(h,m+1)&&i.isDark(h,m+2)&&i.isDark(h,m+3)&&i.isDark(h,m+4)&&!i.isDark(h,m+5)&&i.isDark(h,m+6)&&(w+=40);for(var m=0;m<a;m+=1)for(var h=0;h<a-6;h+=1)i.isDark(h,m)&&!i.isDark(h+1,m)&&i.isDark(h+2,m)&&i.isDark(h+3,m)&&i.isDark(h+4,m)&&!i.isDark(h+5,m)&&i.isDark(h+6,m)&&(w+=40);for(var z=0,m=0;m<a;m+=1)for(var h=0;h<a;h+=1)i.isDark(h,m)&&(z+=1);var J=Math.abs(100*z/a/a-50)/5;return w+=J*10,w},c})(),v=(function(){for(var x=new Array(256),k=new Array(256),b=0;b<8;b+=1)x[b]=1<<b;for(var b=8;b<256;b+=1)x[b]=x[b-4]^x[b-5]^x[b-6]^x[b-8];for(var b=0;b<255;b+=1)k[x[b]]=b;var f={};return f.glog=function(c){if(c<1)throw"glog("+c+")";return k[c]},f.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return x[c]},f})();function A(x,k){if(typeof x.length=="undefined")throw x.length+"/"+k;var b=(function(){for(var c=0;c<x.length&&x[c]==0;)c+=1;for(var y=new Array(x.length-c+k),i=0;i<x.length-c;i+=1)y[i]=x[i+c];return y})(),f={};return f.getAt=function(c){return b[c]},f.getLength=function(){return b.length},f.multiply=function(c){for(var y=new Array(f.getLength()+c.getLength()-1),i=0;i<f.getLength();i+=1)for(var a=0;a<c.getLength();a+=1)y[i+a]^=v.gexp(v.glog(f.getAt(i))+v.glog(c.getAt(a)));return A(y,0)},f.mod=function(c){if(f.getLe Line truncated `}return ye.substring(0,ye.length-1)},C.renderTo2dContext=function(M,k){k=k||2;for(var y=C.getModuleCount(),L=0;L<y;L++)for(var S=0;S<y;S++)M.fillStyle=C.isDark(L,S)?"black":"white",M.fillRect(L*k,S*k,k,k)},C};e.stringToBytesFuncs={default:function(d){for(var v=[],a=0;a<d.length;a+=1){var h=d.charCodeAt(a);v.push(h&255)}return v}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(d,v){var a=(function(){for(var p=P(d),A=function(){var J=p.read();if(J==-1)throw"eof";return J},u=0,c={};;){var T=p.read();if(T==-1)break;var w=A(),C=A(),I=A(),G=String.fromCharCode(T<<8|w),V=C<<8|I;c[G]=V,u+=1}if(u!=v)throw u+" != "+v;return c})(),h=63;return function(p){for(var A=[],u=0;u<p.length;u+=1){var c=p.charCodeAt(u);if(c<128)A.push(c);else{var T=a[p.charAt(u)];typeof T=="number"?(T&255)==T?A.push(T):(A.push(T>>>8),A.push(T&255)):A.push(h)}}return A}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,a=7973,h=21522,p={},A=function(u){for(var c=0;u!=0;)c+=1,u>>>=1;return c};return p.getBCHTypeInfo=function(u){for(var c=u<<10;A(c)-A(v)>=0;)c^=v<<A(c)-A(v);return(u<<10|c)^h},p.getBCHTypeNumber=function(u){for(var c=u<<12;A(c)-A(a)>=0;)c^=a<<A(c)-A(a);return u<<12|c},p.getPatternPosition=function(u){return d[u-1]},p.getMaskFunction=function(u){switch(u){case r.PATTERN000:return function(c,T){return(c+T)%2==0};case r.PATTERN001:return function(c,T){return c%2==0};case r.PATTERN010:return function(c,T){return T%3==0};case r.PATTERN011:return function(c,T){return(c+T)%3==0};case r.PATTERN100:return function(c,T){return(Math.floor(c/2)+Math.floor(T/3))%2==0};case r.PATTERN101:return function(c,T){return c*T%2+c*T%3==0};case r.PATTERN110:return function(c,T){return(c*T%2+c*T%3)%2==0};case r.PATTERN111:return function(c,T){return(c*T%3+(c+T)%2)%2==0};default:throw"bad maskPattern:"+u}},p.getErrorCorrectPolynomial=function(u){for(var c=l([1],0),T=0;T<u;T+=1)c=c.multiply(l([1,i.gexp(T)],0));return c},p.getLengthInBits=function(u,c){if(1<=c&&c<10)switch(u){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+u}else if(c<27)switch(u){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+u}else if(c<41)switch(u){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+u}else throw"type:"+c},p.getLostPoint=function(u){for(var c=u.getModuleCount(),T=0,w=0;w<c;w+=1)for(var C=0;C<c;C+=1){for(var I=0,G=u.isDark(w,C),V=-1;V<=1;V+=1)if(!(w+V<0||c<=w+V))for(var J=-1;J<=1;J+=1)C+J<0||c<=C+J||V==0&&J==0||G==u.isDark(w+V,C+J)&&(I+=1);I>5&&(T+=3+I-5)}for(var w=0;w<c-1;w+=1)for(var C=0;C<c-1;C+=1){var re=0;u.isDark(w,C)&&(re+=1),u.isDark(w+1,C)&&(re+=1),u.isDark(w,C+1)&&(re+=1),u.isDark(w+1,C+1)&&(re+=1),(re==0||re==4)&&(T+=3)}for(var w=0;w<c;w+=1)for(var C=0;C<c-6;C+=1)u.isDark(w,C)&&!u.isDark(w,C+1)&&u.isDark(w,C+2)&&u.isDark(w,C+3)&&u.isDark(w,C+4)&&!u.isDark(w,C+5)&&u.isDark(w,C+6)&&(T+=40);for(var C=0;C<c;C+=1)for(var w=0;w<c-6;w+=1)u.isDark(w,C)&&!u.isDark(w+1,C)&&u.isDark(w+2,C)&&u.isDark(w+3,C)&&u.isDark(w+4,C)&&!u.isDark(w+5,C)&&u.isDark(w+6,C)&&(T+=40);for(var le=0,C=0;C<c;C+=1)for(var w=0;w<c;w+=1)u.isDark(w,C)&&(le+=1);var ue=Math.abs(100*le/c/c-50)/5;return T+=ue*10,T},p})(),i=(function(){for(var d=new Array(256),v=new Array(256),a=0;a<8;a+=1)d[a]=1<<a;for(var a=8;a<256;a+=1)d[a]=d[a-4]^d[a-5]^d[a-6]^d[a-8];for(var a=0;a<255;a+=1)v[d[a]]=a;var h={};return h.glog=function(p){if(p<1)throw"glog("+p+")";return v[p]},h.gexp=function(p){for(;p<0;)p+=255;for(;p>=256;)p-=255;return d[p]},h})();function l(d,v){if(typeof d.length=="undefined")throw d.length+"/"+v;var a=(function(){for(var p=0;p<d.length&&d[p]==0;)p+=1;for(var A=new Array(d.length-p+v),u=0;u<d.length-p;u+=1)A[u]=d[u+p];return A})(),h={};return h.getAt=function(p){return a[p]},h.getLength=function(){return a.length},h.multiply=function(p){for(var A=new Array(h.getLength()+p.getLength()-1),u=0;u<h.getLength();u+=1)for(var c=0;c<p.getLength();c+=1)A[u+c]^=i.gexp(i.glog(h.getAt(u))+i.glog(p.getAt(c)));return l(A,0)},h.mod=function( Line truncated
`),hostName:v,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},E={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(A),port:String(r.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:v};return r.dns[0]&&(E.dns1=r.dns[0]),r.dns[1]&&(E.dns2=r.dns[1]),E}function _t(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ct(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),s=new Uint8Array(await new t.Response(r).arrayBuffer()),l=new Uint8Array(4+s.length);return new DataView(l.buffer).setUint32(0,e.length,!1),l.set(s,4),l}catch{return null}}async function Te(e,t,r=!0){let s=new TextEncoder().encode(JSON.stringify(At(e,t))),l=r?await Ct(s):null;return`vpn://${_t(l!=null?l:s)}`}var $e=()=>{var e;return(e=B==null?void 0:B.today)!=null?e:pe(new Date)};function n(e,t={},...r){let s=document.createElement(e);for(let[v,A]of Object.entries(t))A==null||A===!1||(v.startsWith("on")&&typeof A=="function"?s.addEventListener(v.slice(2),A):v==="class"?s.className=String(A):A===!0?s.setAttribute(v,""):s.setAttribute(v,String(A)));let l=v=>{v==null||v===!1||(Array.isArray(v)?v.forEach(l):s.appendChild(typeof v=="string"?document.createTextNode(v):v))};return r.forEach(l),s}function U(e){let t=n("span",{class:"ic"});return t.innerHTML=Ye(e,"ic-svg"),t}var Tt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Se=document.getElementById("app"),tt,me=(tt=Se.dataset.base)!=null?tt:"",Lt=Se.dataset.title||"Dawnline",De=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),B=null,Dt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Ee=class extends Error{constructor(r,s,l){super(s);this.status=r;this.httpsUrl=l}};async function ne(e,t){var l;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),s=null;try{s=await r.json()}catch{}if(!r.ok)throw new Ee(r.status,(l=s==null?void 0:s.error)!=null?l:`Request failed (${r.status})`,(s==null?void 0:s.https_url)||void 0);return s}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function oe(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let s=document.execCommand("copy");if(r.remove(),!s)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function nt(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),s=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(r),s.remove()},1e3)}var W=null;function rt(e,t){let r=s=>{W!=null||(W=document.body.appendChild(n("div",{class:"tip"}))),W.replaceChildren(...t().map((l,v)=>n("div",{class:v?"muted":"tip-title"},l))),W.style.display="",W.style.left=`${s.clientX}px`,W.style.top=`${s.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>W&&(W.style.display="none"))}function Et(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((s,l)=>{let v=n("i",{class:s?"":"zero"});v.style.height=`${Math.max(8,s/t*100)}%`;let A=e.length-1-l;rt(v,()=>[A===0?"Today":A===1?"Yesterday":ve(Ue($e(),-A)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),se(s)]),r.appendChild(v)}),r}async function Pe(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var ie=null,ue=null;function ee(e=!1){if(!ie)return;let t=ie;if(ie=null,document.body.classList.remove("locked"),ue==null||ue(),ue=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function ce(e,t,...r){let s=!!ie;ee(!0);let l=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},U("x"))),n("div",{class:"sheet-body"},...r)),v=n("div",{class:"sheet",onclick:A=>{A.target===v&&ee()}},l);return document.body.appendChild(v),document.body.classList.add("locked"),s?v.classList.add("open Line truncated `),hostName:i,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},m={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(l),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return n.dns[0]&&(m.dns1=n.dns[0]),n.dns[1]&&(m.dns2=n.dns[1]),m}function si(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ii(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let n=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),r=new Uint8Array(await new t.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,e.length,!1),o.set(r,4),o}catch{return null}}async function Fn(e,t,n=!0){let r=new TextEncoder().encode(JSON.stringify(oi(e,t))),o=n?await ii(r):null;return`vpn://${si(o!=null?o:r)}`}var Po=e=>e.replace(/^vpn:\/\//,"");var Do=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function Ye(e,t={}){let n=s("div",{class:`acc${t.inset?" inset":""}`}),r=e.map((f,E)=>{var D;let x=f.body.filter(d=>!!d),b=!x.length,O=[f.icon,s("span",{class:"acc-title"},s("span",{class:"t"},f.title),(D=f.tag)!=null?D:null),f.val?s("span",{class:`acc-val${f.valHide?" hide-open":""}`},f.val):null],H=E===t.open&&!b,P=b?s("div",{class:"acc-head"},...O):s("button",{type:"button",class:"acc-head","aria-expanded":String(H),onclick:()=>g(B)},...O,W("chevron","i acc-chev")),B=s("div",{class:`acc-row${b?" still":""}${H?" open":""}`},P,s("div",{class:"acc-body"},...x));return n.appendChild(B),B}),o=f=>f.querySelector(".acc-body"),i=()=>r.forEach((f,E)=>{let x=f.classList.contains("open");f.classList.toggle("rt",E===0||x||r[E-1].classList.contains("open")),f.classList.toggle("rb",E===r.length-1||x||r[E+1].classList.contains("open"))}),l=f=>{let E=getComputedStyle(f),x={};for(let b of Do)x[b]=b==="height"?`${f.getBoundingClientRect().height}px`:E[b];return x},m=()=>r.forEach(f=>{var E;return(E=f.querySelector("button.acc-head"))==null?void 0:E.setAttribute("aria-expanded",String(f.classList.contains("open")))});function g(f){var H;let E=r.map(l);r.forEach(P=>P.getAnimations().forEach(B=>B.cancel())),r.forEach(P=>o(P).getAnimations().forEach(B=>B.cancel()));let x=!f.classList.contains("open"),b=r.filter(P=>P.classList.contains("open")&&(P===f||x));r.forEach(P=>{P.classList.remove("closing"),P!==f&&P.classList.remove("open","opened")}),f.classList.toggle("open",x),f.classList.toggle("opened",x),i();let O=yt();r.forEach((P,B)=>{let D=l(P);Do.some(d=>E[B][d]!==D[d])&&(b.includes(P)&&P.classList.add("closing"),$(P,[E[B],D],{duration:Le.duration,easing:Le.easing}).onfinish=()=>P.classList.remove("closing"))}),b.forEach(P=>$(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:Z,fill:"forwards"})),x&&$(o(f),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),bt(O),m(),(H=t.onToggle)==null||H.call(t,r.indexOf(f),x,!1)}return i(),{el:n,openIndex:()=>r.findIndex(f=>f.classList.contains("open")),setOpen(f){r.forEach((E,x)=>E.classList.toggle("open",x===f&&!E.classList.contains("still"))),i(),m(),r.forEach((E,x)=>{var b;return(b=t.onToggle)==null?void 0:b.call(t,x,E.classList.contains("open"),!0)})}}}function $o(e,t,n){let r=s("span",{class:"seg-pill"}),o=s("div",{class:"seg appseg",role:"tablist"},r),i=e.map(b=>{let O=s("button",{type:"button",class:"seg-b",role:"tab","aria-label":b.label,title:b.label,onclick:()=>x(b.value)},W(b.icon),s("span",{class:"seg-l"},b.label));return O.dataset.v=b.value,o.appendChild(O),O}),l=b=>b.querySelector(".seg-l"),m=()=>i.forEach(b=>{let O=b.dataset.v===t;b.classList.toggle("on",O),b.setAttribute("aria-selected",String(O))}),g=()=>{let b=i.find(O=>O.dataset.v===t);return b&&b.offsetWidth?[b.offsetLeft,o.clientWidth-b.offsetLeft-b.offsetWidth]:null},f=()=>{let b=g();b&&(r.style.left=`${b[0]}px`,r.style.right=`${b[1]}px`)},E=0;function x(b){if(b===t)return;let O=i.findIndex(C=>C.dataset.v===t),H=i.findIndex(C=>C.dataset.v===b),P=getComputedStyle(r),B=parseFloat(P.left)||0,D=parseFloat(P.right)||0,d=i.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),v=l(i[O]),a=v.getBoundingClientRect().width;[...i,...i.map(l)].forEach(C=>C.getAnimations().forEach(I=>I.cancel())),t=b,m(),i.forEach((C,I)=>{let G=I===H?1:0;d[I]!==G&&$(C,[{flexGrow:d[I]},{flexGrow:G}],{duration:U.duration,easing:U.easing})}),$(v,[{opacity:1,maxWidth:`${a}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),$(l(i[H]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:j,fill:"backwards"});let h=H>O, Line truncated
`).flatMap((v,A)=>A?[` `).flatMap((x,b)=>b?[`
`,et(v,t)]:[et(v,t)])),l=n("button",{class:"btn small",onclick:v=>{v.preventDefault(),t=!t,l.replaceChildren(U(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),s()}},U("key"),n("span",{},"Show key"));return s(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>nt(e.filename,e.conf)},U("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},U("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),l,n("button",{class:"btn small",onclick:v=>{v.preventDefault(),oe(e.conf,"Configuration copied")}},U("copy"),n("span",{},"Copy"))),r))}async function de(e,t,r){let s=r!=null?r:await Re(e);if(!s)return;let l=await Te(s,`${s.server} · ${s.name}`),v=De(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:l},U("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let f=n("div",{class:"qr"});return f.innerHTML=Ze(s.conf),n("div",{class:"pane center"},f,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},l),n("button",{class:"btn small",onclick:()=>oe(l,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Ut(s)},E=v?["app","qr","key","file"]:["qr","key","file"],N={app:"Open in app",qr:"QR code",key:"Key",file:"File"},$=n("div",{class:"tab-body"}),P=n("div",{class:"tabs",role:"tablist"}),q=f=>{P.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===f)),$.replaceChildren(A[f]())};for(let f of E)P.appendChild(n("button",{role:"tab","data-id":f,onclick:()=>q(f)},N[f]));q(t&&E.includes(t)?t:E[0]);let O=n("div",{class:"waiting"}),H=f=>{f!=null&&f.online?O.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):f!=null&&f.handshake?O.replaceChildren(n("span",{class:"muted"},`Last connected ${Me(f.handshake)}`)):O.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};H(e);let I=0,le=0,Z=!!e.handshake||e.disabled,we=Date.now(),x=async()=>{if(I=0,!(Z||Date.now()-we>6e5)){if(document.hidden){k();return}try{let f=await ne("state");B=f;let c=f.person.devices.find(y=>y.id===e.id);if(H(c),c!=null&&c.online||c!=null&&c.handshake){Z=!0;return}}catch(f){if(f.status===404||f.status===401){Z=!0;return}}le++,k()}},k=()=>{!Z&&!I&&(I=window.setTimeout(x,le<6?5e3:le<12?15e3:3e4))},b=()=>{!document.hidden&&!Z&&!I&&x()};document.addEventListener("visibilitychange",b),k(),ce(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,v?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",P,$,O),ue=()=>{Z=!0,I&&clearTimeout(I),document.removeEventListener("visibilitychange",b),B&&fe(B)}}function Ft(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");ce(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:s=>{s.preventDefault(),Pe(r,async()=>{try{B=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),fe(B),te("Renamed")}catch(l){te(l.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Gt(e,t){let r=t.here===e.id;ce(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:s=>Pe(s.currentTarget,async()=>{try{let l=await ne(`devices/${e.id}`,{action:"rotate"});B=l.state,fe(B),await de(e,void 0,l.config)}catch(l){te(l.message,!0)}})},"New keys")))}function qt(e){ce(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Pe(t.currentTarget,async()=>{try{B=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),fe(B),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,ot=/iPad/.test(V)||/Macintosh/.test(V)&&navi Line truncated `,Oo(x,t)]:[Oo(x,t)]));r();let o=!!Xe(e.filename,e.conf),i=W("key"),l=s("span",{},_("Show key")),m=s("button",{type:"button",class:"btn soft sm",onclick:()=>{t=!t,i=$n(i,t?"x":"key"),ee(l,t?_("Hide key"):_("Show key")),r(),n.querySelectorAll(".mask, .secret").forEach(x=>$(x,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:j}))}},i,l),g=s("button",{type:"button",class:"btn soft sm",onclick:x=>he(e.conf,_("Configuration copied"),x.currentTarget)},W("copy"),s("span",{class:"lbl"},_("Copy"))),f=s("div",{class:"filecard"},s("div",{class:"fc-row"},s("span",{class:"filecard-ic"},".conf"),s("span",{class:"t"},s("span",{class:"mono"},e.filename),s("span",{},_("For computers and routers")))),s("button",{type:"button",class:"btn accent sm block",onclick:()=>Tt(e.filename,e.conf)},W(o?"open":"download"),s("span",{},o?_("Share file"):_("Download")))),E=Ye([{icon:Q("file"),title:_("Configuration"),body:[s("div",{class:"confbar"},m,g),n]}],{inset:!0});return s("div",{class:"step-box"},f,E.el)}function Ko(e){let t=s("span",{class:"osm-p"},ce[e]),n=uo(Ct(e,"ios"),Ct(e,"android"));return{el:s("span",{class:"scanline"},s("span",{},...st(_("In %s:"),t)),n.el),set(r){ee(t,ce[r],void 0,{whole:!0}),n.set(Ct(r,"ios"),Ct(r,"android"))}}}function Uo(e){let t=s("span",{class:"tt"}),n=s("span",{class:"tt-m"}),r=s("span",{class:"hp-tip","aria-hidden":"true"},t,n),o=s("button",{type:"button",class:"hp-b",onclick:()=>Tt(e().file,e().text)},W("download")),i=s("button",{type:"button",class:"hp-b"},W("copy")),l=s("div",{class:"hpill",role:"group","aria-label":_("The connection"),"data-key":"conn"},o,i,r),m=null,g=0,f=0,E=a=>{var h;return a===i&&i.classList.contains("done")?_("Copied"):(h=a.getAttribute("aria-label"))!=null?h:""},x=(a,h)=>{n.textContent=h;let p=n.offsetWidth+20;return Math.min(a.offsetLeft+a.offsetWidth/2,l.offsetWidth+46-p/2)},b=a=>`translateX(${a}px) translateX(-50%)`,O=a=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(p=>p.cancel()),r.style.transform=b(a),$(r,[{transform:h},{transform:b(a)}],{duration:U.duration,easing:U.easing})},H=a=>ee(t,a),P=a=>{if(clearTimeout(g),m===a&&r.classList.contains("on"))return;if(m=a,r.classList.contains("on")){let p=E(a);return O(x(a,p)),H(p)}let h=()=>{let p=E(a);Pe(t,p);let A=x(a,p);r.getAnimations().forEach(u=>u.cancel()),r.style.transform=b(A),r.classList.add("on"),$(r,[{opacity:0,transform:`${b(A)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:b(A),filter:"blur(0px)"}],{duration:220,easing:j})};performance.now()<f?h():g=window.setTimeout(h,420)},B=()=>{clearTimeout(g),m=null,r.classList.contains("on")&&(f=performance.now()+500,r.classList.remove("on"),$(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let a of[o,i])a.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(a)}),a.addEventListener("focus",()=>{a.matches(":focus-visible")&&P(a)}),a.addEventListener("blur",B);l.addEventListener("pointerleave",B);let D=a=>{let h=W(a);i.querySelector("svg").replaceWith(h),$(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:xe.duration,easing:xe.easing})},d=()=>{if(m!==i||!r.classList.contains("on"))return;let a=E(i);O(x(i,a)),H(a)},v=0;return i.addEventListener("click",()=>{let a=e();he(a.text,a.msg),clearTimeout(v),i.classList.contains("done")||(i.classList.add("done"),D("check"),d()),v=window.setTimeout(()=>{i.classList.remove("done"),D("copy"),d()},1600)}),{el:l,sync(){let a=e().app;o.setAttribute("aria-label",N(_("Download %s config"),a)),i.setAttribute("aria-label",N(_("Copy %s config"),a))}}}function Vo(e){let t=s("b",{},_("Waiting for the connection")),n=s("span",{class:"ws",hidden:!0}),r=s("div",{class:"way",role:"status","aria-live":"polite"},s("div",{class:"way-row"},s("span",{class:"way-end"},W(e.kind)),s("span",{class:"way-track"},s("span",{class:"way-glow"},s("i")),s("span",{class:"way-fill"})),s("span",{class:"way-end home"},W("server"))),s("div",{class:"way-text"},s("span",{class:"t"},t,n)));return{el:r,connected(){r.classList.add("done"),ee(t,N(_("%s connected"),e.name))},gaveUp(){r.classList.add("stopped"),ee(t,_("No connection yet")),n.textContent=_("Close this and open it again to keep checking."),n.hidden=!1,$(t.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:j})}}}function Yo(e,t=4){window.setTimeout(async()=>{var n;try{let r=await fe("state");Me(r),At()||_e(),!((n=r.person.devices.find(o=>o.id===e))!=null&&n.online)&&t>1&&Yo(e,t-1)}catch{}},1500)}function jo(e,t,n){let r=ct(),o=0,i=0,l=!1,m=Date.now(),g=async()=>{if(o=0,!l){if(Date.now()-m>6e5){l=!0,n();return}if(document.hidden)return f();try{let x=await fe("state");Me(x);let b=x.person.devices.find(O=>O.id===e.id);if(b&&b.handshake>r){l=!0,t(),b.online||Yo(e.id);return}}catch(x){if(jt(x)){l=!0;return}}i++,f()}},f=()=>{!l&&!o&&(o=window.setTimeout(g,i<6?5e3:i<12?15e3:3e4))},E=()=>{!document.hidden&&!l&&!o&&g()};retur Line truncated
@@ -9,7 +9,7 @@ import { serve } from 'dawnline.portal';
let env = {}; let env = {};
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE', for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's). // The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ]) 'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k); env[k] = getenv(k);
@@ -18,6 +18,8 @@
"settings_get", "settings_get",
"portal_info", "portal_info",
"interfaces", "interfaces",
"server_ports",
"endpoint_probe",
"events" "events"
] ]
} }
@@ -4,7 +4,9 @@
// servers, people (and their devices), settings, home (services, circles), // servers, people (and their devices), settings, home (services, circles),
// maint (Diagnostics, backups, removal) and updates (Components). Each module // maint (Diagnostics, backups, removal) and updates (Components). Each module
// exports `methods` as { name: { args, call } }; read-only users get the // exports `methods` as { name: { args, call } }; read-only users get the
// methods listed under "read" in acl.d/luci-app-dawnline.json. // methods listed under "read" in acl.d/luci-app-dawnline.json. Every method
// also takes `lang`, the admin page's language, and answers in it (its
// errors and the texts the backend writes, through dawnline.i18n).
'use strict'; 'use strict';
import * as status from 'dawnline.rpc.status'; import * as status from 'dawnline.rpc.status';
@@ -14,9 +16,29 @@ import * as settings from 'dawnline.rpc.settings';
import * as home from 'dawnline.rpc.home'; import * as home from 'dawnline.rpc.home';
import * as maint from 'dawnline.rpc.maint'; import * as maint from 'dawnline.rpc.maint';
import * as updates from 'dawnline.rpc.updates'; import * as updates from 'dawnline.rpc.updates';
import * as i18n from 'dawnline.i18n';
/** The methods with `lang` added: the language is set for the call, the method never sees it. */
function in_lang(methods) {
let out = {};
for (let name, m in methods) {
let call = m.call;
out[name] = {
...m,
args: { ...(m.args ?? {}), lang: '' },
call: function(req) {
i18n.use(req.args?.lang);
if (req.args)
delete req.args.lang;
return call(req);
},
};
}
return out;
}
return { return {
'luci.dawnline': { 'luci.dawnline': in_lang({
...status.methods, ...status.methods,
...servers.methods, ...servers.methods,
...people.methods, ...people.methods,
@@ -24,5 +46,5 @@ return {
...home.methods, ...home.methods,
...maint.methods, ...maint.methods,
...updates.methods, ...updates.methods,
}, }),
}; };
@@ -1,5 +1,6 @@
// Dawnline: "Check access" — walks the same rules the nft table and the // Dawnline: "Check access" — walks the same rules the nft table and the
// client configuration apply, and says in words where a connection stops. // client configuration apply, and says in words where a connection stops
// (in the admin's language: each step is a whole sentence).
'use strict'; 'use strict';
@@ -9,17 +10,68 @@ import * as net from 'dawnline.net';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import * as view from 'dawnline.view'; import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
import { _ } from 'dawnline.i18n';
const STATE_TEXT = { /** "Bob can't connect: they are paused", by the person's state (core.person_state). */
no_server: 'they have no server', function cant_connect(name, st) {
server_off: 'their server is turned off', if (st == 'no_server')
paused: 'they are paused', return sprintf(_("%s can't connect: they have no server"), name);
expired: 'their access has ended', if (st == 'server_off')
quota: 'they used up their data', return sprintf(_("%s can't connect: their server is turned off"), name);
hours: 'it is outside their allowed hours', if (st == 'paused')
}; return sprintf(_("%s can't connect: they are paused"), name);
if (st == 'expired')
return sprintf(_("%s can't connect: their access has ended"), name);
if (st == 'quota')
return sprintf(_("%s can't connect: they used up their data"), name);
if (st == 'hours')
return sprintf(_("%s can't connect: it is outside their allowed hours"), name);
return sprintf(_("%s can't connect: %s"), name, st);
}
const ACCESS_TEXT = { lan: 'Home only', internet: 'Internet only', both: 'Home and Internet' }; /** "Bob · Phone can't be reached: it is turned off", by the device and its person's state. */
function cant_reach(who, disabled, st) {
if (disabled)
return sprintf(_("%s can't be reached: it is turned off"), who);
if (st == 'no_server')
return sprintf(_("%s can't be reached: they have no server"), who);
if (st == 'server_off')
return sprintf(_("%s can't be reached: their server is turned off"), who);
if (st == 'paused')
return sprintf(_("%s can't be reached: they are paused"), who);
if (st == 'expired')
return sprintf(_("%s can't be reached: their access has ended"), who);
if (st == 'quota')
return sprintf(_("%s can't be reached: they used up their data"), who);
if (st == 'hours')
return sprintf(_("%s can't be reached: it is outside their allowed hours"), who);
return sprintf(_("%s can't be reached: %s"), who, st);
}
/** A person's access as the admin page names it. */
function access_text(a) {
if (a == 'lan')
return _('Home only');
if (a == 'internet')
return _('Internet only');
if (a == 'both')
return _('Home and Internet');
return a;
}
/** "Bob has Internet only": the step where access stops a connection. */
function has_access(name, a) {
if (a == 'lan')
return sprintf(_('%s has Home only'), name);
if (a == 'internet')
return sprintf(_('%s has Internet only'), name);
return sprintf(_('%s has Home and Internet'), name);
}
/** "Bob reaches lan, guest." (the person's home networks), or that there is none. */
function reaches(name, devs) {
return length(devs) ? sprintf(_('%s reaches %s.'), name, join(', ', devs)) : sprintf(_('%s reaches no home network.'), name);
}
function step(ok, title, detail) { function step(ok, title, detail) {
return { ok: !!ok, title, detail: detail ?? '' }; return { ok: !!ok, title, detail: detail ?? '' };
@@ -65,7 +117,7 @@ function peer_of(dmp, d) {
/** What the device sends to the router: its configuration's AllowedIPs. */ /** What the device sends to the router: its configuration's AllowedIPs. */
function routed(m, srv, p, d) { function routed(m, srv, p, d) {
return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null }; return awg.allowed_ips(m, srv, p);
} }
/** The home network (interface) of a server that holds an address. */ /** The home network (interface) of a server that holds an address. */
@@ -87,19 +139,19 @@ function router_addrs(snap) {
function person_ok(m, p, d, states) { function person_ok(m, p, d, states) {
let st = states[p.id] ?? 'active'; let st = states[p.id] ?? 'active';
if (d.disabled) if (d.disabled)
return step(false, `${d.name} is turned off`, 'Turn the device on again on its page.'); return step(false, sprintf(_('%s is turned off'), d.name), _('Turn the device on again on its page.'));
if (st != 'active') if (st != 'active')
return step(false, `${p.name} can't connect: ${STATE_TEXT[st] ?? st}`, ''); return step(false, cant_connect(p.name, st), '');
return step(true, `${p.name} is active`, ACCESS_TEXT[p.access]); return step(true, sprintf(_('%s is active'), p.name), access_text(p.access));
} }
function connected(dmp, d, who) { function connected(dmp, d, who) {
let peer = peer_of(dmp, d); let peer = peer_of(dmp, d);
if (!peer || !(peer.handshake > 0)) if (!peer || !(peer.handshake > 0))
return step(false, `${who} has never connected`, 'There is no session the router could reach.'); return step(false, sprintf(_('%s has never connected'), who), _('There is no session the router could reach.'));
if (!live.online(dmp, d.id, peer)) if (!live.online(dmp, d.id, peer))
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.'); return step(false, sprintf(_("%s isn't connected right now"), who), _('The router reaches it only while its VPN is on.'));
return step(true, `${who} is connected`, ''); return step(true, sprintf(_('%s is connected'), who), '');
} }
/** A device → somewhere: the router, home, another device or the internet. */ /** A device → somewhere: the router, home, another device or the internet. */
@@ -107,18 +159,18 @@ function from_device(m, d, t, states, dmp, snap) {
let p = m.people[d.person]; let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null; let srv = p ? m.servers[p.server] : null;
if (!p || !srv) if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ]; return [ step(false, sprintf(_('%s has no server'), d.name), '') ];
let steps = [ person_ok(m, p, d, states) ]; let steps = [ person_ok(m, p, d, states) ];
if (!steps[0].ok) if (!steps[0].ok)
return steps; return steps;
let r = routed(m, srv, p, d); let allowed = routed(m, srv, p, d);
let allowed = r.nets;
let via = (ip) => { let via = (ip) => {
let hit = in_nets(ip, allowed); let hit = in_nets(ip, allowed);
let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`; // The configuration's own words: the option and its value.
let what = `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
return hit return hit
? step(true, `${r.what} sends it to the router`, what) ? step(true, _('Its configuration sends it to the router'), what)
: step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`); : step(false, _("Its configuration doesn't send it to the router"), sprintf(_("%s: the device's own network handles it."), what));
}; };
// Another device. // Another device.
@@ -126,27 +178,27 @@ function from_device(m, d, t, states, dmp, snap) {
let q = m.people[t.dev.person]; let q = m.people[t.dev.person];
let who = `${q?.name ?? '?'} · ${t.dev.name}`; let who = `${q?.name ?? '?'} · ${t.dev.name}`;
if (t.dev.id == d.id) if (t.dev.id == d.id)
return [ step(false, 'That is the same device', '') ]; return [ step(false, _('That is the same device'), '') ];
if (!q || q.server != p.server) if (!q || q.server != p.server)
return stop(steps, step(false, `${who} is on another server`, 'Devices of different servers never reach each other.')); return stop(steps, step(false, sprintf(_('%s is on another server'), who), _('Devices of different servers never reach each other.')));
if (!home_access(p)) if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${ACCESS_TEXT[p.access]}`, 'Only people with home access reach other devices.')); return stop(steps, step(false, has_access(p.name, p.access), _('Only people with home access reach other devices.')));
if (!home_access(q)) if (!home_access(q))
return stop(steps, step(false, `${q.name} has ${ACCESS_TEXT[q.access]}`, 'Only devices of people with home access can be reached.')); return stop(steps, step(false, has_access(q.name, q.access), _('Only devices of people with home access can be reached.')));
if (srv.mesh == 'off') if (srv.mesh == 'off')
return stop(steps, step(false, `"Devices reach each other" is off on ${srv.name}`, 'Server → Access → Home network.')); return stop(steps, step(false, sprintf(_('"Devices reach each other" is off on %s'), srv.name), _('Server → Access → Home network.')));
if (srv.mesh == 'circles' && q.id != p.id) { if (srv.mesh == 'circles' && q.id != p.id) {
let a = core.person_circle(m, p), b = core.person_circle(m, q); let a = core.person_circle(m, p), b = core.person_circle(m, q);
if (!a || !b || a.id != b.id) if (!a || !b || a.id != b.id)
return stop(steps, step(false, `${p.name} and ${q.name} are not in one circle`, return stop(steps, step(false, sprintf(_('%s and %s are not in one circle'), p.name, q.name),
`${p.name}: ${a?.name ?? 'no circle'} · ${q.name}: ${b?.name ?? 'no circle'}`)); `${p.name}: ${a?.name ?? _('no circle')} · ${q.name}: ${b?.name ?? _('no circle')}`));
push(steps, step(true, `Both are in ${a.name}`, 'Devices in one circle reach each other.')); push(steps, step(true, sprintf(_('Both are in %s'), a.name), _('Devices in one circle reach each other.')));
} }
else else
push(steps, step(true, q.id == p.id ? `Both are ${p.name}'s devices` : 'Devices reach each other on this server', '')); push(steps, step(true, q.id == p.id ? sprintf(_("Both are %s's devices"), p.name) : _('Devices reach each other on this server'), ''));
let st = states[q.id] ?? 'active'; let st = states[q.id] ?? 'active';
if (st != 'active' || t.dev.disabled) if (st != 'active' || t.dev.disabled)
return stop(steps, step(false, `${who} can't be reached: ${t.dev.disabled ? 'it is turned off' : STATE_TEXT[st] ?? st}`, '')); return stop(steps, step(false, cant_reach(who, t.dev.disabled, st), ''));
push(steps, via(t.ip)); push(steps, via(t.ip));
push(steps, connected(dmp, t.dev, who)); push(steps, connected(dmp, t.dev, who));
return steps; return steps;
@@ -156,17 +208,20 @@ function from_device(m, d, t, states, dmp, snap) {
if (index(router_addrs(snap), t.ip) >= 0) { if (index(router_addrs(snap), t.ip) >= 0) {
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m))); let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
if (t.port == 53) if (t.port == 53)
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, '')); push(steps, step(true, sprintf(_('%s is this router: DNS is open to everyone'), t.ip), ''));
else if (portal) else if (portal)
push(steps, step(true, `${t.ip} is this router: the personal portal is open to everyone`, '')); push(steps, step(true, sprintf(_('%s is this router: the personal portal is open to everyone'), t.ip), ''));
else if (!home_access(p)) else if (!home_access(p))
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS and the portal on the router.`)); return stop(steps, step(false, sprintf(_('%s is this router'), t.ip), sprintf(p.access == 'lan'
? _('%s has Home only: only DNS and the portal on the router.')
: _('%s has Internet only: only DNS and the portal on the router.'), p.name)));
else { else {
// Like any home address: only on the networks the person reaches. // Like any home address: only on the networks the person reaches.
let h = core.person_home(srv, p, snap); let h = core.person_home(srv, p, snap);
if (!h.all && !in_nets(t.ip, h.nets)) if (!h.all && !in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is this router on a network ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`)); return stop(steps, step(false, sprintf(_("%s is this router on a network %s doesn't reach"), t.ip, p.name), reaches(p.name, h.devs)));
push(steps, step(true, `${t.ip} is this router`, h.all ? 'Home access includes the router.' : `On one of the networks ${p.name} reaches.`)); push(steps, step(true, sprintf(_('%s is this router'), t.ip),
h.all ? _('Home access includes the router.') : sprintf(_('On one of the networks %s reaches.'), p.name)));
} }
push(steps, via(t.ip)); push(steps, via(t.ip));
return steps; return steps;
@@ -175,14 +230,14 @@ function from_device(m, d, t, states, dmp, snap) {
// A tunnel address no device has. // A tunnel address no device has.
let tn = in_tunnels(m, t.ip); let tn = in_tunnels(m, t.ip);
if (tn) if (tn)
return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${tn}.`)); return stop(steps, step(false, sprintf(_('No device uses %s'), t.ip), sprintf(_('It is in the tunnel network %s.'), tn)));
// Home. // Home.
let sn = net.server_net(srv, snap); let sn = net.server_net(srv, snap);
let hdev = home_dev_of(srv, t.ip, snap); let hdev = home_dev_of(srv, t.ip, snap);
if (hdev) { if (hdev) {
if (p.access == 'internet') if (p.access == 'internet')
return stop(steps, step(false, `${t.ip} is at home (${hdev})`, `${p.name} has Internet only.`)); return stop(steps, step(false, sprintf(_('%s is at home (%s)'), t.ip, hdev), sprintf(_('%s has Internet only.'), p.name)));
if (p.access == 'lan' && length(p.services)) { if (p.access == 'lan' && length(p.services)) {
let hit = null; let hit = null;
for (let sid in p.services) { for (let sid in p.services) {
@@ -192,28 +247,32 @@ function from_device(m, d, t, states, dmp, snap) {
} }
let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name)); let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name));
if (!hit) if (!hit)
return stop(steps, step(false, `${t.ip}${t.port ? `:${t.port}` : ''} is not one of ${p.name}'s home services`, `Allowed: ${names}`)); return stop(steps, step(false, sprintf(_("%s is not one of %s's home services"), t.port ? `${t.ip}:${t.port}` : t.ip, p.name),
push(steps, step(true, `${t.ip} is ${hit.name}, one of ${p.name}'s home services`, sprintf(_('Allowed: %s'), names)));
length(hit.ports) ? `Ports ${join(', ', hit.ports)}` : 'All ports')); push(steps, step(true, sprintf(_("%s is %s, one of %s's home services"), t.ip, hit.name, p.name),
length(hit.ports) ? sprintf(_('Ports %s'), join(', ', hit.ports)) : _('All ports')));
} }
else { else {
let h = core.person_home(srv, p, snap); let h = core.person_home(srv, p, snap);
if (!in_nets(t.ip, h.nets)) if (!in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`)); return stop(steps, step(false, sprintf(_("%s is in %s, which %s doesn't reach"), t.ip, hdev, p.name), reaches(p.name, h.devs)));
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`)); push(steps, step(true, sprintf(_('%s is in home network %s'), t.ip, hdev),
h.all ? _('Home access reaches every home network.') : sprintf(_('One of the networks %s reaches.'), p.name)));
} }
push(steps, via(t.ip)); push(steps, via(t.ip));
push(steps, step(true, 'The firewall lets it through', `${srv.ifname} → ${join(', ', sn.zones) || 'home'}`)); push(steps, step(true, _('The firewall lets it through'), `${srv.ifname} → ${join(', ', sn.zones) || _('home')}`));
return steps; return steps;
} }
// Another private address, or the internet. // Another private address, or the internet.
if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ])) if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.')); return stop(steps, step(false, sprintf(_("%s isn't in %s's home network"), t.ip, srv.name), _('Private addresses outside the home network are blocked.')));
if (p.access == 'lan') if (p.access == 'lan')
return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`)); return stop(steps, step(true, sprintf(_('%s is on the internet'), t.ip),
sprintf(_("%s has Home only: their device's own internet reaches it, not the tunnel."), p.name)));
push(steps, via(t.ip)); push(steps, via(t.ip));
push(steps, step(true, `${t.ip} is on the internet`, srv.lan_like ? 'It leaves like a home device would.' : `It leaves through ${sn.wan.dev ?? 'the WAN'}.`)); push(steps, step(true, sprintf(_('%s is on the internet'), t.ip), srv.lan_like ? _('It leaves like a home device would.')
: sn.wan.dev != null ? sprintf(_('It leaves through %s.'), sn.wan.dev) : _('It leaves through the WAN.')));
return steps; return steps;
} }
@@ -222,22 +281,22 @@ function to_device(m, ip, d, states, dmp, snap) {
let p = m.people[d.person]; let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null; let srv = p ? m.servers[p.server] : null;
if (!p || !srv) if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ]; return [ step(false, sprintf(_('%s has no server'), d.name), '') ];
let who = `${p.name} · ${d.name}`; let who = `${p.name} · ${d.name}`;
let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap); let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap);
if (!hdev) if (!hdev)
return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ]; return [ step(false, sprintf(_("%s isn't in %s's home network"), ip, srv.name), _("Only home devices reach people's devices.")) ];
let steps = [ step(true, `${ip} is at home (${hdev})`, '') ]; let steps = [ step(true, sprintf(_('%s is at home (%s)'), ip, hdev), '') ];
if (!home_access(p)) if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`, return stop(steps, step(false, p.access == 'lan' ? sprintf(_('%s has only some home services'), p.name) : has_access(p.name, p.access),
'Home devices reach only people with home access.')); _('Home devices reach only people with home access.')));
let h = core.person_home(srv, p, snap); let h = core.person_home(srv, p, snap);
if (!in_nets(ip, h.nets)) if (!in_nets(ip, h.nets))
return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.')); return stop(steps, step(false, sprintf(_("%s doesn't reach %s"), p.name, hdev), _('Networks a person does not reach cannot reach them either.')));
push(steps, person_ok(m, p, d, states)); push(steps, person_ok(m, p, d, states));
if (!steps[length(steps) - 1].ok) if (!steps[length(steps) - 1].ok)
return steps; return steps;
push(steps, step(true, 'The firewall lets it through', `${join(', ', net.server_net(srv, snap).zones) || 'home'} → ${srv.ifname}`)); push(steps, step(true, _('The firewall lets it through'), `${join(', ', net.server_net(srv, snap).zones) || _('home')} → ${srv.ifname}`));
push(steps, connected(dmp, d, who)); push(steps, connected(dmp, d, who));
return steps; return steps;
} }
@@ -246,9 +305,9 @@ function to_device(m, ip, d, states, dmp, snap) {
export function check(m, from, to) { export function check(m, from, to) {
let a = parse_target(m, from), b = parse_target(m, to); let a = parse_target(m, from), b = parse_target(m, to);
if (!a) if (!a)
die(`"${from}" is not a device or an IPv4 address.`); die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
if (!b) if (!b)
die(`"${to}" is not a device or an IPv4 address.`); die(sprintf(_('"%s" is not a device or an IPv4 address.'), to));
let usage = core.load_usage(); let usage = core.load_usage();
let states = view.states(m, usage); let states = view.states(m, usage);
let dmp = live.dump(m); let dmp = live.dump(m);
@@ -259,7 +318,7 @@ export function check(m, from, to) {
else if (b.dev) else if (b.dev)
steps = to_device(m, a.ip, b.dev, states, dmp, snap); steps = to_device(m, a.ip, b.dev, states, dmp, snap);
else else
die('Choose a device on at least one side.'); die(_('Choose a device on at least one side.'));
let ok = length(filter(steps, (s) => !s.ok)) == 0; let ok = length(filter(steps, (s) => !s.ok)) == 0;
return { ok, steps }; return { ok, steps };
}; };
@@ -22,6 +22,7 @@ import * as nft from 'dawnline.nft';
import * as fw from 'dawnline.fw'; import * as fw from 'dawnline.fw';
import * as netifd from 'dawnline.netifd'; import * as netifd from 'dawnline.netifd';
import * as migrate from 'dawnline.migrate'; import * as migrate from 'dawnline.migrate';
import { _, L_ } from 'dawnline.i18n';
const HOSTS_FILE = '/tmp/hosts/dawnline'; const HOSTS_FILE = '/tmp/hosts/dawnline';
/** The network signature the last apply() worked from (the agent compares against it). */ /** The network signature the last apply() worked from (the agent compares against it). */
@@ -35,19 +36,17 @@ function log(who, msg, level, detail) {
/* ---------- hostnames ---------- */ /* ---------- hostnames ---------- */
function host_label(s) {
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
l = replace(l, /^-+|-+$/g, '');
return substr(l, 0, 40) || 'device';
}
export function sync_hosts(m) { export function sync_hosts(m) {
let lines = []; let lines = [];
if (m.settings.hostnames) if (m.settings.hostnames)
for (let id, d in m.devices) { for (let pid, p in m.people) {
let p = m.people[d.person]; // One label per device, unique within the person (the UI shows the same).
if (p && ip2int(d.address) != null) let labels = core.device_labels(m, p);
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`); for (let id in p.devices) {
let d = m.devices[id];
if (ip2int(d.address) != null)
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
}
} }
let ls = loop.status(); let ls = loop.status();
if (ls.active) if (ls.active)
@@ -95,9 +94,9 @@ function nft_result(err, present) {
return null; return null;
} }
if (was != err) { if (was != err) {
log('Access rules', present log(L_('Access rules'), present
? "couldn't be updated — the previous rules stay, and changes to access wait until they load" ? L_("couldn't be updated - the previous rules stay, and changes to access wait until they load")
: "couldn't load — no device is loaded into the tunnels until they do", 'error', err); : L_("couldn't load - no device is loaded into the tunnels until they do"), 'error', err);
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
writefile(NFT_ERR, err); writefile(NFT_ERR, err);
} }
@@ -140,18 +139,19 @@ export function firewall_drift(m) {
/** /**
* What an admin should hear when a sync did not fully take: the access table * What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices. Null when all went in. * failed, or a server did not accept its devices (sentences in the caller's
* language, with what nft or awg said). Null when all went in.
*/ */
function sync_warning(m, table, peers) { function sync_warning(m, table, peers) {
let out = []; let out = [];
if (table != null) if (table != null)
push(out, nft.present() push(out, nft.present()
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.` ? sprintf(_("Access rules couldn't be updated (%s): the previous rules stay, so this change isn't in effect yet."), table)
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`); : sprintf(_("Access rules couldn't load (%s): no device is loaded into the tunnels until they do."), table));
for (let id, r in peers) for (let id, r in peers)
if (r != 'ok' && r != 'down') if (r != 'ok' && r != 'down')
push(out, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`); push(out, sprintf(_("Couldn't load devices into %s: %s."), m.servers[id]?.name ?? id, r));
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null; return length(out) ? join(' ', [ ...out, _('Open Diagnostics → Health.') ]) : null;
} }
/* /*
@@ -244,7 +244,7 @@ export function apply(opts) {
return { network, firewall, lp, peers: s.peers, warning: s.warning }; return { network, firewall, lp, peers: s.peers, warning: s.warning };
}); });
loop.remember(r.lp); loop.remember(r.lp);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning }; return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: loop.error_text(r.lp.error) } : !r.lp.off, peers: r.peers, warning: r.warning };
}; };
/** Remove everything Dawnline created (used by the uninstaller). */ /** Remove everything Dawnline created (used by the uninstaller). */
@@ -1,18 +1,19 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client // Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's // configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters and what the // tunnel, its peers (`awg syncconf`, no restart), live counters, the words for
// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the // why a tunnel is kept down (blocked_text) and what the watchdog and Health
// disguise off. // check about it. Plain WireGuard is AmneziaWG with the disguise off.
import { readfile, stat, unlink } from 'fs'; import { readfile, stat, unlink } from 'fs';
import { import {
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, ensure_dir, write_file, read_json, write_json, lock, unlock, q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, tunnel_name, ensure_dir, write_file, read_json, write_json, lock, unlock,
slog, iface_status, DATA_DIR, RUN_DIR slog, iface_status, DATA_DIR, RUN_DIR
} from 'dawnline.util'; } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
import * as pkg from 'dawnline.pkg'; import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds'; import * as builds from 'dawnline.awg_builds';
import { _, L_ } from 'dawnline.i18n';
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */ /** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = { export const OBF_CONF = {
@@ -98,15 +99,15 @@ export function genpsk() {
export function new_keys(public_key) { export function new_keys(public_key) {
let psk = genpsk(); let psk = genpsk();
if (!valid_key(psk)) if (!valid_key(psk))
die('Key generation failed (no random data).'); die(_('Key generation failed (no random data).'));
if (public_key) { if (public_key) {
if (!valid_key(public_key)) if (!valid_key(public_key))
die('Invalid public key.'); die(_('Invalid public key.'));
return { public_key, preshared_key: psk }; return { public_key, preshared_key: psk };
} }
let priv = genkey(), pub = pubkey(priv); let priv = genkey(), pub = pubkey(priv);
if (!pub) if (!pub)
die('Key generation failed (is amneziawg-tools installed?).'); die(_('Key generation failed (is amneziawg-tools installed?).'));
return { private_key: priv, public_key: pub, preshared_key: psk }; return { private_key: priv, public_key: pub, preshared_key: psk };
}; };
@@ -114,7 +115,7 @@ export function new_keys(public_key) {
export function server_keys() { export function server_keys() {
let priv = genkey(), pub = pubkey(priv); let priv = genkey(), pub = pubkey(priv);
if (!pub) if (!pub)
die('Key generation failed (is amneziawg-tools installed?).'); die(_('Key generation failed (is amneziawg-tools installed?).'));
return { private_key: priv, public_key: pub }; return { private_key: priv, public_key: pub };
}; };
@@ -172,10 +173,11 @@ export function caps() {
}; };
/** /**
* Why this AmneziaWG cannot run a server's disguise values, or null: a 3.1 * Why this AmneziaWG cannot run a server's disguise values, as a reason to
* preset after a rollback to a 2.0 build would come up without the header * keep the server down (blocked_text): { code: 'disguise', need, installed }
* protection every device expects, so such a server is kept down instead * (installed null: none), or null when it can. A 3.1 preset after a rollback
* (dawnline.netifd). * to a 2.0 build would come up without the header protection every device
* expects, so such a server is kept down instead (dawnline.netifd).
*/ */
export function obf_unsupported(o) { export function obf_unsupported(o) {
let c = caps(); let c = caps();
@@ -185,9 +187,9 @@ export function obf_unsupported(o) {
let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ]; let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ];
let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0; let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0;
if (has(v3) && !c.v3) if (has(v3) && !c.v3)
return `its disguise needs AmneziaWG 3.1 (installed: ${c.kmod ?? c.tools ?? 'none'})`; return { code: 'disguise', need: '3.1', installed: c.kmod ?? c.tools };
if ((has(v2) || ranged) && !c.v2) if ((has(v2) || ranged) && !c.v2)
return `its disguise needs AmneziaWG 2.0 (installed: ${c.kmod ?? c.tools ?? 'none'})`; return { code: 'disguise', need: '2.0', installed: c.kmod ?? c.tools };
return null; return null;
}; };
@@ -226,11 +228,14 @@ function dns_answer() {
/** /**
* Generate obfuscation parameters for a method: * Generate obfuscation parameters for a method:
* off plain WireGuard-compatible packets * off plain WireGuard-compatible packets
* standard junk packets and random headers (any AmneziaWG client) * balanced AmneziaWG 2.0: junk packets, random headers, padded cookie and
* strong more and larger junk (any AmneziaWG client) * data packets, DNS-shaped signature packets
* max AmneziaWG 3.1: protected headers, random trailers, padding, * max AmneziaWG 3.1: protected headers, random trailers, padding,
* jittered timers and a DNS-like first packet — the values * jittered timers and a DNS-like first packet — the values
* AmneziaVPN itself uses for 3.1 servers * AmneziaVPN itself uses for 3.1 servers
* Servers made before 0.8 may still carry the old "standard" or "strong"
* values (1.0-style junk only): they keep running as they are, the picker
* offers Balanced or Maximum instead.
*/ */
export function obf_preset(name) { export function obf_preset(name) {
if (name == 'max') if (name == 'max')
@@ -247,12 +252,11 @@ export function obf_preset(name) {
}; };
if (name == 'off') if (name == 'off')
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }; return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
let strong = name == 'strong', balanced = name == 'balanced';
let o = {}; let o = {};
o.jc = `${strong ? rand_int(6, 10) : balanced ? rand_int(4, 8) : rand_int(3, 6)}`; o.jc = `${rand_int(4, 8)}`;
let jmin = rand_int(64, strong || balanced ? 128 : 96); let jmin = rand_int(64, 128);
o.jmin = `${jmin}`; o.jmin = `${jmin}`;
o.jmax = `${jmin + rand_int(strong ? 200 : balanced ? 150 : 32, strong ? 600 : balanced ? 400 : 160)}`; o.jmax = `${jmin + rand_int(150, 400)}`;
let s1 = rand_int(15, 64), s2 = rand_int(15, 64); let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
while (s1 + 56 == s2) while (s1 + 56 == s2)
s2 = rand_int(15, 64); s2 = rand_int(15, 64);
@@ -261,7 +265,6 @@ export function obf_preset(name) {
let used = {}; let used = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
o[k] = rand_h(used); o[k] = rand_h(used);
if (balanced) {
// AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept // AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept
// small: core.tunnel_mtu) and DNS-shaped signature packets before each // small: core.tunnel_mtu) and DNS-shaped signature packets before each
// handshake — what 1.0 traffic lacks and gets recognised by. // handshake — what 1.0 traffic lacks and gets recognised by.
@@ -269,7 +272,6 @@ export function obf_preset(name) {
o.s4 = `${rand_int(4, 16)}`; o.s4 = `${rand_int(4, 16)}`;
o.i1 = dns_query(); o.i1 = dns_query();
o.i2 = dns_answer(); o.i2 = dns_answer();
}
return o; return o;
}; };
@@ -293,9 +295,9 @@ export function obf_errors(o) {
if (v == null || v == '') if (v == null || v == '')
continue; continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/)) if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, `${k} must be a number or range`); push(errs, sprintf(_('%s must be a number or range'), k));
else if (hs[v]) else if (hs[v])
push(errs, 'h1-h4 must be distinct'); push(errs, _('h1-h4 must be distinct'));
hs[v] = true; hs[v] = true;
} }
return errs; return errs;
@@ -336,25 +338,6 @@ export function obf_neutral(o) {
return true; return true;
}; };
/*
* The .conf file name doubles as the tunnel name in WireGuard apps (15
* characters at most): the device first, so a person's devices stay apart,
* and a number when the cut would still make two of them alike.
*/
function conf_filename(m, p, dev) {
let label = (d) => trim(substr(trim(replace(lc(d.name + '-' + p.id), /[^a-z0-9]+/g, '-'), '-'), 0, 15), '-');
let order = sort(map(p.devices, (id) => m.devices[id]),
(a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
let seen = {};
for (let d in order) {
let l = label(d);
let n = seen[l] = (seen[l] ?? 0) + 1;
if (d.id == dev.id)
return (n > 1 ? trim(substr(l, 0, 15 - length(`-${n}`)), '-') + `-${n}` : l) + '.conf';
}
return label(dev) + '.conf';
}
/** /**
* The junk a device sends is its own: within the preset's own ranges, the * The junk a device sends is its own: within the preset's own ranges, the
* count and sizes are shifted a little by the device (deterministic, so the * count and sizes are shifted a little by the device (deterministic, so the
@@ -423,7 +406,8 @@ export function client_config(m, dev) {
name: dev.name, name: dev.name,
person: p.name, person: p.name,
server: srv.name, server: srv.name,
filename: conf_filename(m, p, dev), // The file name is the tunnel's name in WireGuard apps: the server's, in the portal and the admin alike.
filename: `${tunnel_name(srv.name)}.conf`,
conf: join('\n', lines) + '\n', conf: join('\n', lines) + '\n',
has_private_key: dev.private_key != '', has_private_key: dev.private_key != '',
amnezia: { amnezia: {
@@ -464,6 +448,9 @@ export function netifd_options(srv) {
return o; return o;
}; };
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
/** Push the peer list of every server to the kernel without restarting it. */ /** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) { export function sync_peers(m, states) {
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
@@ -480,8 +467,11 @@ export function sync_peers(m, states) {
for (let did, d in m.devices) { for (let did, d in m.devices) {
let p = m.people[d.person]; let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device // One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it). // stays out (Health's Data check names it). Over the data limit or
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !valid_key(d.public_key) || ip2int(d.address) == null) // outside the allowed hours the tunnel stays: the access table blocks
// everything but the portal, which says why (a silent handshake failure
// would look like a broken VPN).
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
continue; continue;
push(lines, '[Peer]', `PublicKey = ${d.public_key}`); push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key) if (d.preshared_key)
@@ -494,7 +484,7 @@ export function sync_peers(m, states) {
unlink(f); unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out); res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0) if (r.code != 0)
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name); slog('awg', 'error', L_("couldn't load devices into the tunnel"), trim(r.out), srv.name);
} }
return res; return res;
}; };
@@ -540,6 +530,56 @@ export function server_state(srv) {
return { up: !!st?.up, uptime: st?.uptime ?? 0 }; return { up: !!st?.up, uptime: st?.uptime ?? 0 };
}; };
/* ---------- why a tunnel is kept down ---------- */
/*
* dawnline.netifd keeps a server's tunnel down for a reason, kept per server
* in core.BLOCKED and loaded as `srv.blocked`. apply writes it, at boot and
* from the agent with no language, so it holds a code and its values, made
* into text when read:
* { code: 'ifname', ifname } the interface name is invalid
* { code: 'taken', ifname } network.<ifname> exists and isn't Dawnline's
* { code: 'disguise', need, installed } obf_unsupported()
* Files written by older versions hold the English fragment ("has an invalid
* interface name …"), shown as it is.
*/
/** A reason as the service log says it after the server's name: English, like every log line. */
export function blocked_note(r) {
if (type(r) != 'object')
return `${r}`;
if (r.code == 'ifname')
return sprintf(L_('has an invalid interface name "%s"'), r.ifname);
if (r.code == 'taken')
return sprintf(L_("can't use the network interface %s: it exists and isn't Dawnline's"), r.ifname);
if (r.code == 'disguise')
return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed)
: sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need);
return L_('is kept down');
};
/**
* Why the server's tunnel is kept down (`srv.blocked`), as a sentence with
* its name in the reader's language: what the admin UI shows. Null when it
* is not kept down.
*/
export function blocked_text(srv) {
let r = srv?.blocked;
if (!r)
return null;
if (type(r) != 'object')
return `${srv.name} ${r}.`;
if (r.code == 'ifname')
return sprintf(_('%s has an invalid interface name "%s".'), srv.name, r.ifname);
if (r.code == 'taken')
return sprintf(_("%s can't use the network interface %s: it exists and isn't Dawnline's."), srv.name, r.ifname);
if (r.code == 'disguise')
return r.installed
? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed)
: sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need);
return sprintf(_('%s is kept down.'), srv.name);
};
/* ---------- watchdog ---------- */ /* ---------- watchdog ---------- */
/** Why a tunnel is down, from netifd and the last related syslog lines. */ /** Why a tunnel is down, from netifd and the last related syslog lines. */
@@ -565,19 +605,20 @@ export function probes(m, ctx) {
// AmneziaWG itself first: without it no tunnel can run (they come back on the next pass). // AmneziaWG itself first: without it no tunnel can run (they come back on the next pass).
// Missing packages and an unknown protocol are reported once; only the module can be loaded here. // Missing packages and an unknown protocol are reported once; only the module can be loaded here.
let st = state(); let st = state();
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' }; let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: L_('is ready again') };
if (!st.tools || !st.kmod) { if (!st.tools || !st.kmod) {
push(out, { ...base, ok: false, repair: null, push(out, { ...base, ok: false, repair: null,
problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`, problem: st.tools ? L_("kernel module isn't installed: no tunnel can run - install it in Dawnline → Components")
detail: () => `Missing: ${join(', ', st.missing)}.` }); : L_("isn't installed: no tunnel can run - install it in Dawnline → Components"),
detail: () => sprintf(L_('Missing: %s.'), join(', ', st.missing)) });
return out; return out;
} }
push(out, { ...base, ok: st.loaded && st.handler, push(out, { ...base, ok: st.loaded && st.handler,
problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot", problem: !st.loaded ? L_("kernel module isn't loaded") : L_("isn't known to the network service - restart the network or reboot"),
detail: !st.loaded detail: !st.loaded
? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4") ? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4")
: () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.', : () => L_('netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.'),
repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null, repair: !st.loaded ? { what: L_('loading it'), run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
}); });
// Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one. // Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one.
if (st.loaded && !st.handler) if (st.loaded && !st.handler)
@@ -586,13 +627,13 @@ export function probes(m, ctx) {
// A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted: // A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted:
// an interface of the same name that isn't Dawnline's may be your LAN. // an interface of the same name that isn't Dawnline's may be your LAN.
let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null; let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null;
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"` let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? { code: 'ifname', ifname: srv.ifname }
: own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null); : own != null && own != srv.id ? { code: 'taken', ifname: srv.ifname } : null);
if (why) { if (why) {
push(out, { push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null, id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: why, back: 'AmneziaWG is running again', problem: blocked_note(why), back: L_('AmneziaWG is running again'),
detail: () => 'Choose another interface name in the server settings.', detail: () => L_('Choose another interface name in the server settings.'),
}); });
continue; continue;
} }
@@ -600,10 +641,11 @@ export function probes(m, ctx) {
let up = !!s?.up; let up = !!s?.up;
push(out, { push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port), id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port),
problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`, problem: !s ? L_('AmneziaWG is missing from the router') : !up ? L_("AmneziaWG isn't running")
back: `AmneziaWG is running again · accepting connections on port ${srv.port}`, : sprintf(L_("AmneziaWG isn't accepting connections on port %d"), srv.port),
back: sprintf(L_('AmneziaWG is running again · accepting connections on port %d'), srv.port),
detail: () => iface_errors(srv.ifname), detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply }, repair: s ? { what: L_('restarting it'), run: () => system(`ifup ${q(srv.ifname)}`) } : { what: L_('setting it up again'), run: ctx.reapply },
}); });
} }
return out; return out;
@@ -654,3 +696,33 @@ export function mark_issued(m, id) {
unlock(l); unlock(l);
}; };
/* ---------- set up again (Reconnect) ---------- */
const RECONNECT = `${DATA_DIR}/reconnect.json`;
/** Device id → when the person asked to set it up again (router clock). */
export function reconnects() {
return read_json(RECONNECT, {});
};
/**
* The handshake a device counts with: none from before it was set up again,
* so it shows "Not set up yet" until it connects after that.
*/
export function handshake_since(hs, since) {
return since && hs <= since ? 0 : hs;
};
/** A device is set up again: handshakes up to `at` (router clock) are its old configuration's. */
export function mark_reconnect(m, id, at) {
let l = lock('reconnect');
let all = reconnects();
all[id] = at ?? time();
for (let k in keys(all))
if (!m.devices[k])
delete all[k];
ensure_dir(DATA_DIR, 0o700);
write_json(RECONNECT, all, 0o600);
unlock(l);
};
@@ -13,6 +13,7 @@ import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
import * as health from 'dawnline.health'; import * as health from 'dawnline.health';
import { _ } from 'dawnline.i18n';
const BACKUP_DIR = `${DATA_DIR}/backups`; const BACKUP_DIR = `${DATA_DIR}/backups`;
/** /**
@@ -51,17 +52,16 @@ export function config_errors(c) {
let internal = values(net.INTERNAL); let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = []; let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) { for (let id, srv in m.servers) {
let who = `Server ${srv.name}`;
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ])) for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
push(errs, `${who}: ${e}`); push(errs, sprintf(_('Server %s: %s'), srv.name, e));
if (ifnames[srv.ifname]) if (ifnames[srv.ifname])
push(errs, `${who}: interface ${srv.ifname} is also used by ${ifnames[srv.ifname]}.`); push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
ifnames[srv.ifname] = srv.name; ifnames[srv.ifname] = srv.name;
let t = nc.get('network', srv.ifname); let t = nc.get('network', srv.ifname);
if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null))) if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null)))
push(errs, `${who}: ${srv.ifname} is one of the router's own network interfaces.`); push(errs, sprintf(_("Server %s: %s is one of the router's own network interfaces."), srv.name, srv.ifname));
if (ports[srv.port]) if (ports[srv.port])
push(errs, `${who}: UDP ${srv.port} is also used by ${ports[srv.port]}.`); push(errs, sprintf(_('Server %s: UDP %s is also used by %s.'), srv.name, srv.port, ports[srv.port]));
ports[srv.port] = srv.name; ports[srv.port] = srv.name;
if (srv.subnet) if (srv.subnet)
push(subnets, srv.subnet); push(subnets, srv.subnet);
@@ -75,10 +75,10 @@ function check_config_dir(dir) {
// Its own delta directory: changes staged in LuCI must not leak into the check. // Its own delta directory: changes staged in LuCI must not leak into the check.
let c = cursor(dir, `${dir}/.delta`); let c = cursor(dir, `${dir}/.delta`);
if (!c.load('dawnline')) if (!c.load('dawnline'))
die('The configuration in this file cannot be read.'); die(_('The configuration in this file cannot be read.'));
let errs = config_errors(c); let errs = config_errors(c);
if (length(errs)) if (length(errs))
die(`This configuration can't be used: ${join(' ', errs)}`); die(sprintf(_("This configuration can't be used: %s"), join(' ', errs)));
} }
/** A private scratch directory under RUN_DIR (the caller removes it). */ /** A private scratch directory under RUN_DIR (the caller removes it). */
@@ -129,7 +129,8 @@ export function backup_create(reason, keep) {
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`); let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) { if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
unlink(tmp); unlink(tmp);
die(`Backup failed: ${trim(r.out) || 'the archive could not be written (is the flash full?)'}`); let why = trim(r.out);
die(why ? sprintf(_('Backup failed: %s'), why) : _('Backup failed: the archive could not be written (is the flash full?)'));
} }
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`); system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let by_kind = {}; let by_kind = {};
@@ -144,10 +145,10 @@ export function backup_create(reason, keep) {
function backup_path(name) { function backup_path(name) {
if (!match(name ?? '', NAME)) if (!match(name ?? '', NAME))
die('Invalid backup name.'); die(_('Invalid backup name.'));
let p = `${BACKUP_DIR}/${name}`; let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p)) if (!file_exists(p))
die('Backup not found.'); die(_('Backup not found.'));
return p; return p;
} }
@@ -158,24 +159,24 @@ function backup_path(name) {
function check_archive(path) { function check_archive(path) {
let r = sh(`tar -tvzf ${q(path)}`); let r = sh(`tar -tvzf ${q(path)}`);
if (r.code != 0) if (r.code != 0)
die('Not a valid backup archive.'); die(_('Not a valid backup archive.'));
let has_config = false, total = 0; let has_config = false, total = 0;
for (let line in split(trim(r.out), '\n')) { for (let line in split(trim(r.out), '\n')) {
let f = split(trim(line), /[ \t]+/); let f = split(trim(line), /[ \t]+/);
let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, ''); let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, '');
// "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b". // "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b".
if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0) if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0)
die(`Unexpected entry in backup: ${name}`); die(sprintf(_('Unexpected entry in backup: %s'), name));
if (index(FILES, name) < 0) if (index(FILES, name) < 0)
die(`Unexpected file in backup: ${name}`); die(sprintf(_('Unexpected file in backup: %s'), name));
total += +(f[2] ?? 0) || 0; total += +(f[2] ?? 0) || 0;
if (name == 'etc/config/dawnline') if (name == 'etc/config/dawnline')
has_config = true; has_config = true;
} }
if (!has_config) if (!has_config)
die('Backup does not contain /etc/config/dawnline.'); die(_('Backup does not contain /etc/config/dawnline.'));
if (total > MAX_UNPACKED) if (total > MAX_UNPACKED)
die('Backup is too large.'); die(_('Backup is too large.'));
} }
/** /**
@@ -190,7 +191,7 @@ function install_files(dir) {
for (let f in FILES) { for (let f in FILES) {
let data = readfile(`${dir}/${f}`); let data = readfile(`${dir}/${f}`);
if (data != null && !write_file(`/${f}`, data, 0o600)) if (data != null && !write_file(`/${f}`, data, 0o600))
die(`Couldn't write /${f}. Is the flash full?`); die(sprintf(_("Couldn't write %s. Is the flash full?"), `/${f}`));
} }
} }
catch (e) { catch (e) {
@@ -208,7 +209,7 @@ export function backup_restore(name, path) {
try { try {
let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`); let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`);
if (r.code != 0) if (r.code != 0)
die('Not a valid backup archive.'); die(_('Not a valid backup archive.'));
check_config_dir(`${dir}/etc/config`); check_config_dir(`${dir}/etc/config`);
backup_create('pre-restore', name); backup_create('pre-restore', name);
install_files(dir); install_files(dir);
@@ -238,7 +239,7 @@ export function backup_read(name) {
export function backup_upload(data_b64) { export function backup_upload(data_b64) {
let data = b64dec(data_b64 ?? ''); let data = b64dec(data_b64 ?? '');
if (!data || length(data) > 4 * 1024 * 1024) if (!data || length(data) > 4 * 1024 * 1024)
die('Upload is empty or too large.'); die(_('Upload is empty or too large.'));
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`; let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data); write_file(tmp, data);
@@ -273,23 +274,23 @@ export function export_json() {
/** An export as /etc/config/dawnline text; dies on anything that is not one. */ /** An export as /etc/config/dawnline text; dies on anything that is not one. */
function export_to_uci(data) { function export_to_uci(data) {
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array') if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
die('Not a Dawnline export.'); die(_('Not a Dawnline export.'));
let types = { settings: true, server: true, person: true, device: true, service: true, circle: true }; let types = { settings: true, server: true, person: true, device: true, service: true, circle: true };
let esc = (x) => replace(`${x}`, "'", "'\\''"); let esc = (x) => replace(`${x}`, "'", "'\\''");
let lines = []; let lines = [];
for (let s in data.sections) { for (let s in data.sections) {
if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/)) if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
die(`Invalid section ${s?.['.name']}.`); die(sprintf(_('Invalid section %s.'), s?.['.name']));
push(lines, `config ${s['.type']} '${s['.name']}'`); push(lines, `config ${s['.type']} '${s['.name']}'`);
for (let k, v in s) { for (let k, v in s) {
if (substr(k, 0, 1) == '.') if (substr(k, 0, 1) == '.')
continue; continue;
if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')) if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))
die(`Invalid option ${k}.`); die(sprintf(_('Invalid option %s.'), k));
if (type(v) == 'array') if (type(v) == 'array')
for (let x in v) { for (let x in v) {
if (type(x) != 'string') if (type(x) != 'string')
die(`Invalid option ${k}.`); die(sprintf(_('Invalid option %s.'), k));
push(lines, `\tlist ${k} '${esc(x)}'`); push(lines, `\tlist ${k} '${esc(x)}'`);
} }
else else
@@ -317,6 +318,6 @@ export function import_json(data) {
let ok = write_file('/etc/config/dawnline', text, 0o600); let ok = write_file('/etc/config/dawnline', text, 0o600);
unlock(l); unlock(l);
if (!ok) if (!ok)
die("Couldn't write /etc/config/dawnline. Is the flash full?"); die(sprintf(_("Couldn't write %s. Is the flash full?"), '/etc/config/dawnline'));
return apply.apply(); return apply.apply();
}; };
@@ -4,9 +4,10 @@
import { cursor } from 'uci'; import { cursor } from 'uci';
import { import {
valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int, valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util'; } from 'dawnline.util';
import { _, N_ } from 'dawnline.i18n';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
import * as schema from 'dawnline.schema'; import * as schema from 'dawnline.schema';
import { policy as updates_policy } from 'dawnline.updates'; import { policy as updates_policy } from 'dawnline.updates';
@@ -81,7 +82,6 @@ export function load(c) {
portal_alt: g('portal_alt'), portal_alt: g('portal_alt'),
portal_cert: g('portal_cert'), portal_cert: g('portal_cert'),
portal_key: g('portal_key'), portal_key: g('portal_key'),
portal_title: g('portal_title'),
// Where unknown portal links go instead of a bare 404 (empty = 404). // Where unknown portal links go instead of a bare 404 (empty = 404).
portal_redirect: g('portal_redirect'), portal_redirect: g('portal_redirect'),
default_device_limit: g('default_device_limit'), default_device_limit: g('default_device_limit'),
@@ -482,35 +482,35 @@ export function new_code() {
export function create_person(c, m, a) { export function create_person(c, m, a) {
if (!valid_name(a.name)) if (!valid_name(a.name))
fail('Enter a name (up to 48 characters).'); fail(name_rule());
// The id is a UCI section name: letters, digits and underscores only (a dash // The id is a UCI section name: letters, digits and underscores only (a dash
// makes uci drop the section). Repeated names get _2, _3, … // makes uci drop the section). Repeated names get _2, _3, …
let base = replace(a.slug ?? slugify(a.name), /-/g, '_'); let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
if (!match(base, /^[a-z0-9_]{1,32}$/)) if (!match(base, /^[a-z0-9_]{1,32}$/))
fail('The id may use lowercase letters, digits and underscores.'); fail(_('The id may use lowercase letters, digits and underscores.'));
// Any kind of section (store.id_taken, which imports this module). // Any kind of section (store.id_taken, which imports this module).
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] || let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] ||
index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0; index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0;
let slug = base; let slug = base;
for (let n = 2; taken(slug); n++) { for (let n = 2; taken(slug); n++) {
if (n > 99) if (n > 99)
fail(`"${base}" is already taken.`); fail(sprintf(_('"%s" is already taken.'), base));
slug = `${substr(base, 0, 28)}_${n}`; slug = `${substr(base, 0, 28)}_${n}`;
} }
let srv_id = a.server ?? keys(m.servers)[0]; let srv_id = a.server ?? keys(m.servers)[0];
if (!m.servers[srv_id]) if (!m.servers[srv_id])
fail('Set up a server first.'); fail(_('Set up a server first.'));
let access = a.access ?? 'internet'; let access = a.access ?? 'internet';
if (index(ACCESS, access) < 0) if (index(ACCESS, access) < 0)
fail('Access must be lan, internet or both.'); fail(_('Access must be lan, internet or both.'));
let limit = toint(a.device_limit, m.settings.default_device_limit); let limit = toint(a.device_limit, m.settings.default_device_limit);
if (limit < 1 || limit > 32) if (limit < 1 || limit > 32)
fail('Device limit must be between 1 and 32.'); fail(_('Device limit must be between 1 and 32.'));
if (a.expires && !valid_date(a.expires)) if (a.expires && !valid_date(a.expires))
fail('End date must be YYYY-MM-DD.'); fail(_('End date must be YYYY-MM-DD.'));
let quota = num(a.quota_gb, 0); let quota = num(a.quota_gb, 0);
if (quota < 0 || quota > 100000) if (quota < 0 || quota > 100000)
fail('Monthly data must be a positive number of GB.'); fail(_('Monthly data must be a positive number of GB.'));
c.set(CONFIG, slug, 'person'); c.set(CONFIG, slug, 'person');
c.set(CONFIG, slug, 'server', srv_id); c.set(CONFIG, slug, 'server', srv_id);
@@ -536,52 +536,53 @@ export function create_person(c, m, a) {
export function update_person(c, m, id, a) { export function update_person(c, m, id, a) {
let p = m.people[id]; let p = m.people[id];
if (!p) if (!p)
fail('Unknown person.'); fail(_('Unknown person.'));
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`); let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
if (a.name != null) { if (a.name != null) {
if (!valid_name(a.name)) if (!valid_name(a.name))
fail('Enter a name (up to 48 characters).'); fail(name_rule());
set('name', trim(a.name)); set('name', trim(a.name));
} }
if (a.access != null) { if (a.access != null) {
if (index(ACCESS, a.access) < 0) if (index(ACCESS, a.access) < 0)
fail('Access must be lan, internet or both.'); fail(_('Access must be lan, internet or both.'));
set('access', a.access); set('access', a.access);
} }
if (a.device_limit != null) { if (a.device_limit != null) {
let n = toint(a.device_limit, 0); let n = toint(a.device_limit, 0);
if (n < 1 || n > 32) if (n < 1 || n > 32)
fail('Device limit must be between 1 and 32.'); fail(_('Device limit must be between 1 and 32.'));
let have = length(p.devices); let have = length(p.devices);
if (n < have) if (n < have)
fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`); fail(sprintf(N_(have, '%s already has %d device. Remove one first to lower the limit to %d.',
'%s already has %d devices. Remove one first to lower the limit to %d.'), p.name, have, n));
set('device_limit', n); set('device_limit', n);
} }
if (a.expires != null) { if (a.expires != null) {
if (a.expires != '' && !valid_date(a.expires)) if (a.expires != '' && !valid_date(a.expires))
fail('End date must be YYYY-MM-DD.'); fail(_('End date must be YYYY-MM-DD.'));
set('expires', a.expires); set('expires', a.expires);
} }
if (a.expire_action != null) { if (a.expire_action != null) {
if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0) if (index([ 'pause', 'notify', 'remove' ], a.expire_action) < 0)
fail('Unknown end action.'); fail(_('Unknown end action.'));
set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action); set('expire_action', a.expire_action == 'pause' ? '' : a.expire_action);
} }
if (a.dns_mode != null) { if (a.dns_mode != null) {
if (index([ 'device', 'home' ], a.dns_mode) < 0) if (index([ 'device', 'home' ], a.dns_mode) < 0)
fail('Unknown DNS choice.'); fail(_('Unknown DNS choice.'));
set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode); set('dns_mode', a.dns_mode == 'device' ? '' : a.dns_mode);
} }
if (a.expire_warn != null) { if (a.expire_warn != null) {
let n = toint(a.expire_warn, -1); let n = toint(a.expire_warn, -1);
if (n < 0 || n > 60) if (n < 0 || n > 60)
fail('Warning must be 0-60 days.'); fail(_('Warning must be 0-60 days.'));
set('expire_warn', n == 3 ? '' : n); set('expire_warn', n == 3 ? '' : n);
} }
if (a.quota_gb != null) { if (a.quota_gb != null) {
let q = num(a.quota_gb, -1); let q = num(a.quota_gb, -1);
if (a.quota_gb != '' && (q < 0 || q > 100000)) if (a.quota_gb != '' && (q < 0 || q > 100000))
fail('Data limit must be a positive number of GB.'); fail(_('Data limit must be a positive number of GB.'));
set('quota_gb', q > 0 ? q : ''); set('quota_gb', q > 0 ? q : '');
} }
if (a.quota_period != null) if (a.quota_period != null)
@@ -589,21 +590,21 @@ export function update_person(c, m, id, a) {
if (a.bonus_gb != null) { if (a.bonus_gb != null) {
let b = num(a.bonus_gb, -1); let b = num(a.bonus_gb, -1);
if (b < 0 || b > 100000) if (b < 0 || b > 100000)
fail('Extra data must be a positive number of GB.'); fail(_('Extra data must be a positive number of GB.'));
set('bonus_gb', b > 0 ? b : ''); set('bonus_gb', b > 0 ? b : '');
set('bonus_month', b > 0 ? month_key() : ''); set('bonus_month', b > 0 ? month_key() : '');
} }
if (a.hours != null) { if (a.hours != null) {
if (a.hours != '' && !parse_hours(a.hours)) if (a.hours != '' && !parse_hours(a.hours))
fail('Hours must look like 07:00-23:00.'); fail(_('Hours must look like 07:00-23:00.'));
set('hours', a.hours); set('hours', a.hours);
} }
if (a.note != null) if (a.note != null)
set('note', substr(trim(a.note), 0, 500)); set('note', ucut(trim(a.note), 500));
if (type(a.services) == 'array') { if (type(a.services) == 'array') {
for (let sid in a.services) for (let sid in a.services)
if (!m.services[sid]) if (!m.services[sid])
fail(`Unknown service ${sid}.`); fail(sprintf(_('Unknown service %s.'), sid));
if (length(a.services)) if (length(a.services))
c.set(CONFIG, id, 'service', a.services); c.set(CONFIG, id, 'service', a.services);
else else
@@ -612,9 +613,27 @@ export function update_person(c, m, id, a) {
if (a.circle != null) { if (a.circle != null) {
let ci = m.circles[a.circle]; let ci = m.circles[a.circle];
if (a.circle != '' && (!ci || ci.server != p.server)) if (a.circle != '' && (!ci || ci.server != p.server))
fail('Unknown circle.'); fail(_('Unknown circle.'));
set('circle', a.circle); set('circle', a.circle);
} }
// Another server: every device gets an address in its tunnel (so each
// needs its configuration again); circles and home networks are the old
// server's and go.
if (a.server != null && a.server != '' && a.server != p.server) {
if (!m.servers[a.server])
fail(_('Unknown server.'));
set('server', a.server);
p.server = a.server;
for (let did in p.devices) {
let addr = alloc_address(m, m.servers[a.server]);
if (!addr)
fail(sprintf(_('No free address left on %s.'), m.servers[a.server].name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.delete(CONFIG, id, 'circle');
c.delete(CONFIG, id, 'home_net');
}
if (type(a.home_nets) == 'array') { if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/))); let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
if (length(nets)) if (length(nets))
@@ -635,29 +654,29 @@ export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {}; opts ??= {};
let p = m.people[person_id]; let p = m.people[person_id];
if (!p) if (!p)
fail('Unknown person.'); fail(_('Unknown person.'));
let srv = m.servers[p.server]; let srv = m.servers[p.server];
if (!srv) if (!srv)
fail('The person has no server.'); fail(_('The person has no server.'));
name = trim(name ?? ''); name = trim(name ?? '');
if (!valid_name(name)) if (!valid_name(name))
fail('Enter a device name (up to 48 characters).'); fail(_('Enter a device name (up to 48 characters).'));
if (index(KINDS, kind) < 0) if (index(KINDS, kind) < 0)
kind = 'other'; kind = 'other';
if (opts.by == 'portal' && length(p.devices) >= p.device_limit) if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
fail(`Device limit reached (${p.device_limit}).`); fail(sprintf(_('Device limit reached (%d).'), p.device_limit));
for (let id in p.devices) for (let id in p.devices)
if (lc(m.devices[id].name) == lc(name)) if (lc(m.devices[id].name) == lc(name))
fail(`"${name}" already exists.`); fail(sprintf(_('"%s" already exists.'), name));
let addr = alloc_address(m, srv); let addr = alloc_address(m, srv);
if (!addr) if (!addr)
fail('No free addresses left in the server subnet.'); fail(_('No free addresses left in the server subnet.'));
let k = opts.keys ?? {}; let k = opts.keys ?? {};
if (!valid_key(k.public_key)) if (!valid_key(k.public_key))
fail('Key generation failed (is amneziawg-tools installed?).'); fail(_('Key generation failed (is amneziawg-tools installed?).'));
for (let o, d in m.devices) for (let o, d in m.devices)
if (d.public_key == k.public_key) if (d.public_key == k.public_key)
fail('This key is already in use.'); fail(_('This key is already in use.'));
let id = `d_${rand_hex(4)}`; let id = `d_${rand_hex(4)}`;
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '', let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
@@ -682,13 +701,13 @@ export function create_device(c, m, person_id, name, kind, opts) {
export function rename_device(c, m, id, name) { export function rename_device(c, m, id, name) {
let d = m.devices[id]; let d = m.devices[id];
if (!d) if (!d)
fail('Unknown device.'); fail(_('Unknown device.'));
name = trim(name ?? ''); name = trim(name ?? '');
if (!valid_name(name)) if (!valid_name(name))
fail('Enter a device name (up to 48 characters).'); fail(_('Enter a device name (up to 48 characters).'));
for (let o in m.people[d.person]?.devices ?? []) for (let o in m.people[d.person]?.devices ?? [])
if (o != id && lc(m.devices[o].name) == lc(name)) if (o != id && lc(m.devices[o].name) == lc(name))
fail(`"${name}" already exists.`); fail(sprintf(_('"%s" already exists.'), name));
c.set(CONFIG, id, 'name', name); c.set(CONFIG, id, 'name', name);
d.name = name; d.name = name;
}; };
@@ -696,7 +715,7 @@ export function rename_device(c, m, id, name) {
export function delete_device(c, m, id) { export function delete_device(c, m, id) {
let d = m.devices[id]; let d = m.devices[id];
if (!d) if (!d)
fail('Unknown device.'); fail(_('Unknown device.'));
c.delete(CONFIG, id); c.delete(CONFIG, id);
let p = m.people[d.person]; let p = m.people[d.person];
if (p) if (p)
@@ -708,9 +727,9 @@ export function delete_device(c, m, id) {
export function rotate_device(c, m, id, keys) { export function rotate_device(c, m, id, keys) {
let d = m.devices[id]; let d = m.devices[id];
if (!d) if (!d)
fail('Unknown device.'); fail(_('Unknown device.'));
if (!valid_key(keys?.public_key) || !keys?.private_key) if (!valid_key(keys?.public_key) || !keys?.private_key)
fail('Key generation failed.'); fail(_('Key generation failed.'));
c.set(CONFIG, id, 'private_key', keys.private_key); c.set(CONFIG, id, 'private_key', keys.private_key);
c.set(CONFIG, id, 'public_key', keys.public_key); c.set(CONFIG, id, 'public_key', keys.public_key);
if (keys.preshared_key) if (keys.preshared_key)
@@ -720,7 +739,7 @@ export function rotate_device(c, m, id, keys) {
export function delete_person(c, m, id) { export function delete_person(c, m, id) {
let p = m.people[id]; let p = m.people[id];
if (!p) if (!p)
fail('Unknown person.'); fail(_('Unknown person.'));
for (let d in p.devices) for (let d in p.devices)
c.delete(CONFIG, d); c.delete(CONFIG, d);
c.delete(CONFIG, id); c.delete(CONFIG, id);
@@ -740,20 +759,20 @@ export function private_cidr(c) {
export function server_errors(m, srv, others_subnets) { export function server_errors(m, srv, others_subnets) {
let errs = []; let errs = [];
if (!valid_ifname(srv.ifname)) if (!valid_ifname(srv.ifname))
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.'); push(errs, _('Interface name: 1-12 lowercase letters, digits or _.'));
if (srv.port < 1 || srv.port > 65535) if (srv.port < 1 || srv.port > 65535)
push(errs, 'Port must be 1-65535.'); push(errs, _('Port must be 1-65535.'));
let c = parse_cidr(srv.subnet); let c = parse_cidr(srv.subnet);
if (!c) if (!c)
push(errs, 'Subnet must look like 10.77.0.0/24.'); push(errs, _('Subnet must look like 10.77.0.0/24.'));
else else
for (let o in others_subnets ?? []) { for (let o in others_subnets ?? []) {
let oc = parse_cidr(o); let oc = parse_cidr(o);
if (oc && cidr_overlaps(c, oc)) if (oc && cidr_overlaps(c, oc))
push(errs, `Subnet overlaps ${o}.`); push(errs, sprintf(_('Subnet overlaps %s.'), o));
} }
if (srv.endpoint != '' && !valid_host(srv.endpoint)) if (srv.endpoint != '' && !valid_host(srv.endpoint))
push(errs, 'Endpoint must be a hostname or IP address.'); push(errs, _('Endpoint must be a hostname or IP address.'));
return errs; return errs;
}; };
@@ -771,55 +790,102 @@ export function model_errors(m) {
let errs = []; let errs = [];
let codes = {}, addrs = {}; let codes = {}, addrs = {};
for (let id, p in m.people) { for (let id, p in m.people) {
let who = `Person ${p.name}`;
if (p.server != '' && !m.servers[p.server]) if (p.server != '' && !m.servers[p.server])
push(errs, `${who}: server ${p.server} does not exist.`); push(errs, sprintf(_('Person %s: server %s does not exist.'), p.name, p.server));
if (p.circle != '' && !m.circles[p.circle]) if (p.circle != '' && !m.circles[p.circle])
push(errs, `${who}: circle ${p.circle} does not exist.`); push(errs, sprintf(_('Person %s: circle %s does not exist.'), p.name, p.circle));
for (let sid in p.services) for (let sid in p.services)
if (!m.services[sid]) if (!m.services[sid])
push(errs, `${who}: home service ${sid} does not exist.`); push(errs, sprintf(_('Person %s: home service %s does not exist.'), p.name, sid));
if (p.code != '') { if (p.code != '') {
if (codes[p.code]) if (codes[p.code])
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`); push(errs, sprintf(_('Person %s: has the same personal link as %s.'), p.name, codes[p.code]));
codes[p.code] = p.name; codes[p.code] = p.name;
} }
} }
for (let id, d in m.devices) { for (let id, d in m.devices) {
let p = m.people[d.person]; let p = m.people[d.person];
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
if (!p) { if (!p) {
push(errs, `${who}: person ${d.person} does not exist.`); push(errs, sprintf(_('Device %s: person %s does not exist.'), d.name, d.person));
continue; continue;
} }
let say = (msg, ...args) => push(errs, sprintf(msg, d.name, p.name, ...args));
if (!valid_key(d.public_key)) if (!valid_key(d.public_key))
push(errs, `${who}: the public key is not a key.`); say(_('Device %s of %s: the public key is not a key.'));
if (d.private_key != '' && !valid_key(d.private_key)) if (d.private_key != '' && !valid_key(d.private_key))
push(errs, `${who}: the private key is not a key.`); say(_('Device %s of %s: the private key is not a key.'));
if (d.preshared_key != '' && !valid_key(d.preshared_key)) if (d.preshared_key != '' && !valid_key(d.preshared_key))
push(errs, `${who}: the preshared key is not a key.`); say(_('Device %s of %s: the preshared key is not a key.'));
let n = ip2int(d.address); let n = ip2int(d.address);
if (n == null) { if (n == null) {
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`); if (d.address)
say(_('Device %s of %s: address %s is not a plain IPv4 address.'), d.address);
else
say(_('Device %s of %s: address (none) is not a plain IPv4 address.'));
continue; continue;
} }
let srv = m.servers[p.server]; let srv = m.servers[p.server];
let t = srv ? parse_cidr(srv.subnet) : null; let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last)) if (t && (n < t.first || n > t.last))
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`); say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
else if (t && n == t.first) else if (t && n == t.first)
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`); say(_("Device %s of %s: address %s is the router's own address on %s."), d.address, srv.name);
let key = `${p.server} ${d.address}`; let key = `${p.server} ${d.address}`;
if (addrs[key]) let o = addrs[key];
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`); if (o)
addrs[key] = who; say(_('Device %s of %s: address %s is also used by device %s of %s.'), d.address, o.device, o.person);
addrs[key] = { device: d.name, person: p.name };
} }
for (let id, ci in m.circles) for (let id, ci in m.circles)
if (!m.servers[ci.server]) if (!m.servers[ci.server])
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`); push(errs, sprintf(_('Circle %s: server %s does not exist.'), ci.name, ci.server));
return errs; return errs;
}; };
/**
* Give every device on a server an address in `subnet` (the server's new
* tunnel network), lowest first: used by server_update when the network
* changes. Each device then needs its configuration again (the address is
* in it). Fails when the subnet cannot hold them.
*/
export function renumber_server(c, m, srv, subnet) {
srv.subnet = subnet;
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices)
m.devices[did].address = '';
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices) {
let addr = alloc_address(m, srv);
if (!addr)
fail(sprintf(_('%s has no room for every device on %s.'), subnet, srv.name));
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.set(CONFIG, srv.id, 'subnet', subnet);
};
/**
* The DNS labels of a person's devices, { device id: label }, unique within
* the person: two devices whose names give one label ("iPhone" and
* "iPhone!", or two Cyrillic names) get -2, -3 by age. Hostnames in
* /tmp/hosts (dawnline.apply) and the ones the UI shows (dawnline.view) both
* come from here, so what is shown resolves.
*/
export function device_labels(m, p) {
let out = {}, used = {};
let devs = sort(map(p.devices, (id) => m.devices[id]), (a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
for (let d in devs) {
let base = host_label(d.name), l = base;
for (let n = 2; used[l]; n++)
l = `${substr(base, 0, 37)}-${n}`;
used[l] = true;
out[d.id] = l;
}
return out;
};
/** /**
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }]. * Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
* A forwarded port never reaches the router itself, so nothing here can listen on it. * A forwarded port never reaches the router itself, so nothing here can listen on it.
@@ -883,7 +949,9 @@ export function portal_link(m, p, host) {
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`; return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
} }
let pp = portal_public_port(m); let pp = portal_public_port(m);
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`; // An IPv6 address needs its brackets in a URL.
let h = index(host, ':') >= 0 && !match(host, /^\[/) ? `[${host}]` : host;
return `https://${h}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
}; };
/** The main link (QR, invite card, Copy link). */ /** The main link (QR, invite card, Copy link). */
@@ -13,6 +13,7 @@ import * as awg from 'dawnline.awg';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import { _ } from 'dawnline.i18n';
/** AmneziaWG is on the router, so device keys can be made and loaded. */ /** AmneziaWG is on the router, so device keys can be made and loaded. */
export function ready() { export function ready() {
@@ -23,7 +24,8 @@ export function ready() {
export function need_awg() { export function need_awg() {
if (!awg.installed()) { if (!awg.installed()) {
let miss = awg.state().missing ?? []; let miss = awg.state().missing ?? [];
die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`); die(length(miss) ? sprintf(_('AmneziaWG is not installed (%s): install it in Dawnline → Components.'), join(', ', miss))
: _('AmneziaWG is not installed: install it in Dawnline → Components.'));
} }
}; };
@@ -31,9 +33,9 @@ export function need_awg() {
function own(m, id, opts) { function own(m, id, opts) {
let d = m.devices[id]; let d = m.devices[id];
if (!d || (opts.person != null && d.person != opts.person)) if (!d || (opts.person != null && d.person != opts.person))
die(opts.person != null ? 'Device not found.' : 'Unknown device.'); die(opts.person != null ? _('Device not found.') : _('Unknown device.'));
if (opts.by == 'portal' && d.disabled) if (opts.by == 'portal' && d.disabled)
die('The admin has turned this device off.'); die(_('The admin has turned this device off.'));
return d; return d;
} }
@@ -57,7 +59,7 @@ export function update(id, ch, opts) {
opts ??= {}; opts ??= {};
let by = opts.by ?? 'admin'; let by = opts.by ?? 'admin';
if (ch.disabled != null && by != 'admin') if (ch.disabled != null && by != 'admin')
die('Only the admin can turn devices off.'); die(_('Only the admin can turn devices off.'));
let d0 = store.transact((c, m) => { let d0 = store.transact((c, m) => {
let d = own(m, id, opts); let d = own(m, id, opts);
let was = { ...d }; let was = { ...d };
@@ -104,6 +106,21 @@ export function rotate(id, opts) {
return cfg; return cfg;
}; };
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings
* the admin changed): new keys, so the configuration it holds stops working
* with the sync, and it counts as not set up until it connects with the new
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
* it. Returns the new configuration, as rotate.
*/
export function reconnect(id, opts) {
opts ??= {};
let cfg = rotate(id, opts);
// A deferred sync (the page came through this device) lets the old keys live a few seconds more.
awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0));
return cfg;
};
/** Remove a device. Returns the runtime sync. */ /** Remove a device. Returns the runtime sync. */
export function remove(id, opts) { export function remove(id, opts) {
opts ??= {}; opts ??= {};
@@ -3,8 +3,9 @@
// Client addresses are looked up once with a third-party service (ipwho.is, // Client addresses are looked up once with a third-party service (ipwho.is,
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on // ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage // flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
// counters. Only the agent performs lookups, on its minute tick and within a // counters. Only the agent performs lookups, in a child process (the network
// time budget, never on the 1-second watcher; the UI reads the cache. // may take seconds; neither its watcher nor its tick waits for them) and
// merges them into the cache itself; the UI reads the cache.
import { stat } from 'fs'; import { stat } from 'fs';
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util'; import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
@@ -13,7 +14,7 @@ const CACHE = `${RUN_DIR}/geo.json`;
const SAVED = `${DATA_DIR}/geo.json`; const SAVED = `${DATA_DIR}/geo.json`;
const TTL = 30 * 86400; const TTL = 30 * 86400;
const RETRY = 86400; const RETRY = 86400;
// Entries kept at least; addresses still shown are never pushed out (resolve). // Entries kept at least; addresses still shown are never pushed out (merge).
const CAP = 500; const CAP = 500;
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …). // [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
@@ -99,40 +100,64 @@ export function lookup(provider, ip) {
}; };
/** /**
* Resolve up to `max` of `ips` that are missing or stale, within `budget` * The public addresses of `ips` the cache does not know or knows from too
* seconds (each lookup may wait on the network). Returns true when the cache * long ago (a failed lookup is retried after a day), once each and in order.
* changed (the caller saves it). `ips` is also what is still shown: the cache * Returns an empty array when there is nothing to look up.
* is kept bounded by dropping other entries only, oldest first, so a lookup
* is never repeated for an address that is still on the map.
*/ */
export function resolve(settings, cache, ips, max, budget) { export function stale(cache, ips, ts) {
let now = time(), changed = false, done = 0; let now = ts ?? time(), out = [], seen = {};
let started = now;
for (let ip in ips) { for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget)) if (seen[ip] || !is_public(ip))
break;
if (!is_public(ip))
continue; continue;
seen[ip] = true;
let c = cache.ips[ip]; let c = cache.ips[ip];
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL))) if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
continue; continue;
let r = lookup(settings.geo_provider, ip); push(out, ip);
}
return out;
};
/**
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
* wait on the network). Returns { ip: place, or false when the services had
* nothing } for the ones tried. Network only, no cache: the agent runs it in
* a child process and merges the result itself.
*/
export function lookup_all(provider, ips, max, budget) {
let started = time(), out = {}, done = 0;
for (let ip in ips) {
if (done >= max || (budget != null && time() - started >= budget))
break;
let r = lookup(provider, ip);
done++; done++;
changed = true; if (r)
if (r) {
delete r.ip; delete r.ip;
r.ts = now; out[ip] = r ?? false;
cache.ips[ip] = r;
} }
else return out;
cache.ips[ip] = { fail: now }; };
/**
* Put lookup_all() results into the cache. Returns true when the cache
* changed (the caller saves it). `shown` is what is still on the map: the
* cache is kept bounded by dropping other entries only, oldest first, so a
* lookup is never repeated for an address that is still on the map.
*/
export function merge(cache, found, shown, ts) {
let now = ts ?? time(), changed = false;
for (let ip, r in found) {
if (!is_public(ip))
continue;
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
changed = true;
} }
let shown = {}; let keep = {};
for (let ip in ips) for (let ip in shown)
shown[ip] = true; keep[ip] = true;
let all = keys(cache.ips); let all = keys(cache.ips);
if (length(all) > CAP) { if (length(all) > CAP) {
let other = sort(filter(all, (ip) => !shown[ip]), let other = sort(filter(all, (ip) => !keep[ip]),
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0)); (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
for (let i = 0; i < length(all) - CAP && i < length(other); i++) { for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
delete cache.ips[other[i]]; delete cache.ips[other[i]];
@@ -159,6 +184,11 @@ export function place(cache, ip) {
return (c && !c.fail) ? c : null; return (c && !c.fail) ? c : null;
}; };
/** "City · ISP" for the activity log; null for no place. */
export function label(pl) {
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
};
export function clear() { export function clear() {
save({ ips: {}, home: null }); save({ ips: {}, home: null });
ensure_dir(DATA_DIR, 0o700); ensure_dir(DATA_DIR, 0o700);
@@ -8,6 +8,7 @@
import { stat, popen, access } from 'fs'; import { stat, popen, access } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util'; import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
/** Prefixes that fetch github.com files when GitHub itself is unreachable. */ /** Prefixes that fetch github.com files when GitHub itself is unreachable. */
export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ]; export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ];
@@ -54,11 +55,11 @@ function api_json(url) {
return null; return null;
} }
if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i))) if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i)))
die('GitHub API rate limit reached: try again in an hour.'); die(_('GitHub API rate limit reached: try again in an hour.'));
if (r.status == 404) if (r.status == 404)
return null; return null;
if (r.status >= 400) if (r.status >= 400)
die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`); die(sprintf(_('GitHub: %s'), j?.message ?? `HTTP ${r.status}`));
return j; return j;
} }
@@ -209,18 +210,18 @@ export function download(url, dest, o) {
for (let i, u in tries) { for (let i, u in tries) {
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1'); let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (i > 0) if (i > 0)
o.log?.(`Trying mirror ${host}`); o.log?.(sprintf(_('Trying mirror %s'), host));
let r = have_curl() let r = have_curl()
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`) ? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`); : run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) { if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
if (!want || sha256(dest) == want) if (!want || sha256(dest) == want)
return u; return u;
o.log?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`); o.log?.(sprintf(_("Warning: %s sent a file that does not match GitHub's sha256, discarded"), host));
} }
system(`rm -f ${q(dest)}`); system(`rm -f ${q(dest)}`);
if (i == 0 && length(tries) > 1) if (i == 0 && length(tries) > 1)
o.log?.('GitHub did not answer, trying mirrors'); o.log?.(_('GitHub did not answer, trying mirrors'));
} }
return null; return null;
}; };
@@ -1,8 +1,10 @@
// Dawnline — Health: what the router has and lacks (packages, listeners, // Dawnline — Health: what the router has and lacks (packages, listeners,
// networks), the checks shown on Diagnostics → Health, and their fixes. // networks), the checks shown on Diagnostics → Health, and their fixes.
// The checks' texts are in the language of the call (dawnline.i18n).
import { readfile, stat, lsdir } from 'fs'; import { readfile, stat, lsdir } from 'fs';
import { cursor } from 'uci'; import { cursor } from 'uci';
import { _, N_ } from 'dawnline.i18n';
import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util'; import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
@@ -174,43 +176,12 @@ export function foreign_subnets() {
/* /*
* Checks are named for the healthy state ("Clock is set"); a failed one also * Checks are named for the healthy state ("Clock is set"); a failed one also
* gets the problem in words for notices ("Clock isn't set"). Longest names * gets the problem in words for notices ("Clock isn't set"), passed with it.
* first; a server's name after the check name is kept. * A server's checks carry its name after both (` (Home)`, with several servers).
*/ */
const PROBLEM = [
[ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ],
[ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ],
[ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ],
[ 'AmneziaWG port is free', 'AmneziaWG port is taken' ],
[ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ],
[ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ],
[ 'AmneziaWG running', 'AmneziaWG is down' ],
[ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ],
[ 'Portal address points here', 'Portal address doesn’t point here' ],
[ 'Portal address', 'Portal address isn’t set' ],
[ 'Portal certificate', 'Portal certificate needs attention' ],
[ 'Personal portal', 'Personal portal isn’t working' ],
[ 'Plain HTTP links', 'Portal links use plain HTTP' ],
[ 'Internet like a home device', 'Internet like a home device isn’t working' ],
[ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ],
[ 'Background agent running', 'Background agent isn’t running' ],
[ 'Access rules loaded', 'Access rules aren’t loaded' ],
[ 'Server configured', 'No server yet' ],
[ 'Public address', 'Public address needs attention' ],
[ 'Clock is set', 'Clock isn’t set' ],
];
function problem_of(title) {
for (let p in PROBLEM)
if (substr(title, 0, length(p[0])) == p[0])
return p[1] + substr(title, length(p[0]));
return title;
}
/** problem: the failed check in words, when the table's wording does not fit the case. */
function check(id, title, status, detail, fix, problem) { function check(id, title, status, detail, fix, problem) {
let bad = status == 'warn' || status == 'error'; let bad = status == 'warn' || status == 'error';
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null }; return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? title) : null };
} }
/** /**
@@ -222,37 +193,101 @@ function replies(m) {
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) }; return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
} }
function reply_check(id, title, proto, port, r) { function reply_check(id, title, problem, proto, port, r) {
let via = join(', ', r.diverts); let via = join(', ', r.diverts);
let from = `${uc(proto)} ${port}`;
return check(id, title, r.ok ? 'ok' : 'error', return check(id, title, r.ok ? 'ok' : 'error',
!r.ok ? `Answers from ${uc(proto)} ${port} are swallowed by a proxy on the router (${via}): clients get no reply.` !r.ok ? sprintf(_('Answers from %s are swallowed by a proxy on the router (%s): clients get no reply.'), from, via)
: length(r.diverts) ? `Answers from ${uc(proto)} ${port} go straight out. A proxy on the router diverts its own traffic (${via}); these answers skip it.` : length(r.diverts) ? sprintf(_('Answers from %s go straight out. A proxy on the router diverts its own traffic (%s); these answers skip it.'), from, via)
: `Answers from ${uc(proto)} ${port} go straight out.`, : sprintf(_('Answers from %s go straight out.'), from),
r.ok ? null : 'apply'); r.ok ? null : 'apply', problem);
} }
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr); const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */ /** What kind of IPv4 the WAN has: public, cgnat (100.64/10), private (behind another router), or none. */
function endpoint_check(id, title, srv, host, proto_note) { export function wan_kind(wan) {
if (!host)
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
let ips = lookup.resolve(host);
let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
let wc = wan ? ip2int(wan) : null; let wc = wan ? ip2int(wan) : null;
let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0; if (wc == null)
if (!length(ips)) return 'none';
return check(id, title, 'error', `${host} does not resolve.`); if (in_cidr(wc, PRIVATE[0]))
if (cgnat) return 'cgnat';
return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`); return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
if (length(filter(ips, (a) => cloudflare_ip(a)))) };
return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`);
if (wan && index(ips, wan) < 0) /**
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`); * What a public address points at, for Health and the "as you type" check on
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`); * the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
* here (an IPv4 of it is this router's WAN), v6_only }.
*/
export function endpoint_facts(srv, host) {
let ips = host ? lookup.resolve(host) : [];
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
return {
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
here: wan != null && index(ips4, wan) >= 0,
v6_only: !length(ips4) && length(ips6) > 0,
};
};
/**
* The facts in words, in the language of the call: { status: ok|warn|error, text }
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
*/
export function endpoint_words(f, proto_note) {
if (!f.host)
return { status: 'error', text: _('No public address: devices will not know where to connect.') };
if (!length(f.ips))
return { status: 'error', text: sprintf(_('%s does not resolve.'), f.host) };
if (f.cloudflare)
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
f.host, join(', ', f.ips), proto_note) };
if (f.v6_only)
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
if (f.kind == 'cgnat' || f.kind == 'private')
return { status: 'warn', text: f.kind == 'cgnat'
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note) };
if (f.wan && !f.here)
return { status: 'warn', text: sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan) };
// Without the router's WAN address only the facts: names and addresses, no words.
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, f.wan) : `${f.host} → ${join(', ', f.ips)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
function endpoint_check(id, title, problem, srv, host, proto_note) {
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
return check(id, title, w.status, w.text, null, problem);
} }
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it)."; /**
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
* Dawnline's (pref < 5205) whose table has a default route of its own sends
* marked tunnel traffic straight out, past "like a home device". Reported,
* since those marks belong to that package. [] when none.
*/
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
if (!mm || +mm[1] >= 5205)
continue;
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
let def = match(routes, /(^|\n)default [^\n]*/)?.[0] ?? '';
if (def == '' || match(def, /local default/) || index(def, `dev ${net.INTERNAL.transit}`) >= 0)
continue;
push(out, `pref ${mm[1]} fwmark 0x${mm[2]} → table ${mm[4]}`);
}
return out;
}
function no_proto() {
return _("netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).");
}
/** Free space on the overlay in KB (null when unknown). */ /** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() { function overlay_free_kb() {
@@ -264,27 +299,29 @@ function overlay_free_kb() {
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */ /** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() { function awg_check() {
let st = awg.load(); let st = awg.load();
let title = 'AmneziaWG installed'; let title = _('AmneziaWG installed');
if (length(st.missing ?? [])) { let missing = st.missing ?? [];
if (length(missing)) {
// The module was built for the kernel of the firmware it was installed on. // The module was built for the kernel of the firmware it was installed on.
let kc = builds.kernel_changed(); let kc = builds.kernel_changed();
if (kc && index(st.missing, 'kmod-amneziawg') >= 0) if (kc && index(missing, 'kmod-amneziawg') >= 0)
return check('awg', title, 'error', return check('awg', title, 'error',
`The firmware changed (kernel ${kc.was} → ${kc.now}): the AmneziaWG build installed for it is gone. Install the build for this firmware.`, sprintf(_('The firmware changed (kernel %s → %s): the AmneziaWG build installed for it is gone. Install the build for this firmware.'), kc.was, kc.now),
'install:awg', 'AmneziaWG needs a build for the new firmware'); 'install:awg', _('AmneziaWG needs a build for the new firmware'));
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg', return check('awg', title, 'error', sprintf(N_(length(missing), '%s is missing.', '%s are missing.'), join(', ', missing)), 'install:awg',
'AmneziaWG isn’t installed'); _('AmneziaWG isn’t installed'));
} }
if (!st.loaded) { if (!st.loaded) {
// load() tried it: the second modprobe only repeats why. // load() tried it: the second modprobe only repeats why.
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out); let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
return check('awg', title, 'error', return check('awg', title, 'error',
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates', why ? sprintf(_("The kernel module doesn't load: %s Reinstall a build for this kernel in Components."), why)
'AmneziaWG’s kernel module doesn’t load'); : _("The kernel module doesn't load. Reinstall a build for this kernel in Components."),
'updates', _('AmneziaWG’s kernel module doesn’t load'));
} }
if (!st.handler) if (!st.handler)
return check('awg', title, 'error', NO_PROTO, 'netrestart', 'The network doesn’t know AmneziaWG yet'); return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.'); return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
} }
/** Checks of a server's AmneziaWG tunnel. */ /** Checks of a server's AmneziaWG tunnel. */
@@ -293,34 +330,50 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let st = live.iface_status(srv.ifname); let st = live.iface_status(srv.ifname);
let up = !!st?.up; let up = !!st?.up;
let codes = map(st?.errors ?? [], (e) => e.code); let codes = map(st?.errors ?? [], (e) => e.code);
let running = _('AmneziaWG running') + label, down = _('AmneziaWG is down') + label;
if (!up && index(codes, 'INVALID_PROTO') >= 0) if (!up && index(codes, 'INVALID_PROTO') >= 0)
push(out, check(`up_${id}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart')); push(out, check(`up_${id}`, running, 'error', no_proto(), 'netrestart', down));
else else
push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error', push(out, check(`up_${id}`, running, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` : up ? sprintf(_('%s is up, listening on UDP %d.'), srv.ifname, srv.port) :
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`), !st ? sprintf(_('%s does not exist.'), srv.ifname) :
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'))); length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
if (up) { if (up) {
let expected = 0; // By key, not by count: a stale peer standing in for a missing one would
// make the numbers match.
let states = apply.states_for(m, core.load_usage()); let states = apply.states_for(m, core.load_usage());
let wanted = {}, expected = 0;
for (let did, d in m.devices) { for (let did, d in m.devices) {
let p = m.people[d.person]; let p = m.people[d.person];
if (p?.server == id && !d.disabled && states[d.person] == 'active') if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
wanted[d.public_key] = true;
expected++; expected++;
} }
let actual = 0; }
let loaded = {}, actual = 0;
for (let k, p in dmp.peers) for (let k, p in dmp.peers)
if (p.ifname == srv.ifname) if (p.ifname == srv.ifname) {
loaded[k] = true;
actual++; actual++;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn', }
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync')); let missing = length(filter(keys(wanted), (k) => !loaded[k]));
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
let same = !missing && !extra;
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
extra ? sprintf(N_(expected, '%d of %d device missing, %d loaded that should not be.', '%d of %d devices missing, %d loaded that should not be.'),
missing, expected, extra)
: sprintf(N_(expected, '%d of %d device missing.', '%d of %d devices missing.'), missing, expected),
same ? null : 'sync', _('Not every device is loaded into AmneziaWG') + label));
} }
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule'; let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone'; let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error', push(out, check(`fw_${id}`, _('AmneziaWG firewall') + label, rule && zone ? 'ok' : 'error',
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.', rule && zone ? sprintf(_('Zone %s and the WAN rule for UDP %d exist.'), srv.ifname, srv.port) : _('Firewall zone or WAN rule is missing.'),
rule && zone ? null : 'apply')); rule && zone ? null : 'apply', _('AmneziaWG firewall rules are missing') + label));
push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, rep)); push(out, reply_check(`reply_${id}`, _('AmneziaWG answers reach devices') + label, _('AmneziaWG answers may not reach devices') + label,
'udp', srv.port, rep));
// Port collisions with other tunnels. // Port collisions with other tunnels.
let clash = []; let clash = [];
let nc = cursor(); let nc = cursor();
@@ -330,7 +383,8 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
push(clash, s['.name']); push(clash, s['.name']);
}); });
if (length(clash)) if (length(clash))
push(out, check(`port_${id}`, `AmneziaWG port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`)); push(out, check(`port_${id}`, _('AmneziaWG port is free') + label, 'error', sprintf(_('UDP %d is also used by %s.'), srv.port, join(', ', clash)),
null, _('AmneziaWG port is taken') + label));
let overlaps = []; let overlaps = [];
let sc = parse_cidr(srv.subnet); let sc = parse_cidr(srv.subnet);
for (let o in other_subnets(id)) { for (let o in other_subnets(id)) {
@@ -338,8 +392,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
if (sc && oc && cidr_overlaps(sc, oc)) if (sc && oc && cidr_overlaps(sc, oc))
push(overlaps, `${o.iface} (${o.cidr})`); push(overlaps, `${o.iface} (${o.cidr})`);
} }
push(out, check(`subnet_${id}`, `AmneziaWG subnet is unique${label}`, length(overlaps) ? 'error' : 'ok', push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`)); length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet),
null, _('AmneziaWG subnet overlaps another network') + label));
return out; return out;
} }
@@ -347,50 +402,59 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
function portal_checks(m, need, rep) { function portal_checks(m, need, rep) {
let out = []; let out = [];
let s = m.settings; let s = m.settings;
let portal = _('Personal portal'), portal_bad = _('Personal portal isn’t working');
if (length(need.https)) if (length(need.https))
return [ check('portal', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https') ]; return [ check('portal', portal, 'error', sprintf(_("HTTPS isn't available on this router: install %s."), join(', ', need.https)), 'install:https', portal_bad) ];
let owners = tcp_port_owners(s.portal_port); let owners = tcp_port_owners(s.portal_port);
let listening = tcp_listening(s.portal_port); let listening = tcp_listening(s.portal_port);
if (length(owners)) if (length(owners))
push(out, check('portal', 'Personal portal', 'error', push(out, check('portal', portal, 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`)); sprintf(_('TCP %d is already used by %s. Choose another port in Settings.'), s.portal_port, join(', ', owners)), null, portal_bad));
else else
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error', push(out, check('portal', portal, listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart')); listening ? sprintf(_('Listening on TCP %d.'), s.portal_port) : sprintf(_('Nothing listens on TCP %d.'), s.portal_port),
listening ? null : 'restart', portal_bad));
if (!s.portal_host) if (!s.portal_host)
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.')); push(out, check('portal_host', _('Portal address'), 'error', _('Set the public hostname in Settings so links can be generated.'),
null, _('Portal address isn’t set')));
else { else {
let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m); let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m);
let cf = filter(ips, (x) => cloudflare_ip(x)); let cf = filter(ips, (x) => cloudflare_ip(x));
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok', let h = s.portal_host;
!length(ips) ? `${s.portal_host} does not resolve.` : push(out, check('portal_dns', _('Portal address points here'), !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` : !length(ips) ? sprintf(_('%s does not resolve.'), h) :
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` : length(cf) ? sprintf(_('%s goes through Cloudflare; in Russia such connections often stall after ~16 KB.'), h) :
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`)); wan && index(ips, wan) < 0 ? sprintf(_('%s points at %s, not this router (%s).'), h, join(', ', ips), wan) :
wan ? sprintf(_('%s → %s (this router).'), h, join(', ', ips)) : `${h} → ${join(', ', ips)}.`,
null, _('Portal address doesn’t point here')));
} }
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, rep)); push(out, reply_check('portal_reply', _('Portal answers reach visitors'), _('Portal answers may not reach visitors'), 'tcp', s.portal_port, rep));
if (core.portal_http(m)) { if (core.portal_http(m)) {
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null); let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
push(out, check('portal_http', 'Plain HTTP links', 'warn', push(out, check('portal_http', _('Plain HTTP links'), 'warn',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`)); sprintf(_('Links on %s use plain HTTP: the link and the VPN keys in configurations travel unencrypted.'), join(', ', ipl)),
null, _('Portal links use plain HTTP')));
} }
if (ip2int(s.portal_host) != null) { if (ip2int(s.portal_host) != null) {
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.')); push(out, check('cert', _('Portal certificate'), 'skip', _('The main address is an IP: its links use plain HTTP.')));
return out; return out;
} }
let cert = pc.portal_cert(s); let cert = pc.portal_cert(s);
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0; let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
let sans = cert.self_signed ? [] : pc.cert_names(cert.cert); let sans = cert.self_signed ? [] : pc.cert_names(cert.cert);
let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0; let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0;
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok', push(out, check('cert', _('Portal certificate'), cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` : cert.self_signed ? (length(need.acme) ? _('Using a self-signed certificate: browsers will show a warning. ACME can get a free Let’s Encrypt one.')
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` : : _('Using a self-signed certificate: browsers will show a warning.')) :
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`)); !covers ? sprintf(_('%s does not cover %s (it has %s): browsers will warn.'), cert.cert, s.portal_host, join(', ', sans)) :
ok ? sprintf(_('%s covers %s and is valid for more than 14 days.'), cert.cert, s.portal_host) : sprintf(_('%s expires within 14 days.'), cert.cert),
null, _('Portal certificate needs attention')));
return out; return out;
} }
/** /**
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }. * Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix,
* problem (a failed check in words, else null) }, the texts in the language of the call.
* `fix` names an action accepted by fix(), or one the UI handles itself * `fix` names an action accepted by fix(), or one the UI handles itself
* (install:<feature>, updates). * (install:<feature>, updates).
*/ */
@@ -404,38 +468,50 @@ export function health(m) {
if (length(m.servers)) if (length(m.servers))
push(out, awg_check()); push(out, awg_check());
let y = localtime().year; let y = localtime().year;
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error', push(out, check('clock', _('Clock is set'), y >= 2025 ? 'ok' : 'error',
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.')); y >= 2025 ? _('End dates and quotas use the router clock.') : _('The router clock looks wrong; end dates will misbehave. Check NTP.'),
null, _('Clock isn’t set')));
let agent = service_running('dawnline', 'agent'); let agent = service_running('dawnline', 'agent');
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error', push(out, check('agent', _('Background agent running'), agent ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart')); _('Counts traffic and enforces end dates and quotas.'), agent ? null : 'restart', _('Background agent isn’t running')));
// A full overlay fails every config write on the router, Dawnline's and // A full overlay fails every config write on the router, Dawnline's and
// OpenWrt's own; backups and history are what Dawnline adds to it. // OpenWrt's own; backups and history are what Dawnline adds to it.
let free = overlay_free_kb(); let free = overlay_free_kb();
if (free != null) if (free != null)
push(out, check('flash', 'Free space on the router', free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok', push(out, check('flash', _('Free space on the router'), free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
free < 2048 ? `${int(free / 1024 * 10) / 10} MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.` free < 2048 ? sprintf(_('%s MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.'), int(free / 1024 * 10) / 10)
: `${int(free / 1024)} MB free on the overlay.`, : sprintf(_('%d MB free on the overlay.'), int(free / 1024)),
null, 'The router is running out of flash')); null, _('The router is running out of flash')));
if (!length(m.servers)) { if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.')); push(out, check('server', _('Server configured'), 'warn', _('Run the setup wizard on the Server tab.'), null, _('No server yet')));
return out; return out;
} }
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0; let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error', push(out, check('nft', _('Access rules loaded'), nft_ok ? 'ok' : 'error',
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' nft_ok ? _('Table inet dawnline enforces who may reach LAN and the internet.')
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.', : _('Table inet dawnline is missing: no device is loaded into the tunnels until it is back.'),
nft_ok ? null : 'apply')); nft_ok ? null : 'apply', _('Access rules aren’t loaded')));
if (length(filter(values(m.servers), (s) => s.lan_like && s.enabled))) {
let pr = policy_routing();
push(out, check('policy', _('Internet like a home device not bypassed'), length(pr) ? 'warn' : 'ok',
length(pr) ? sprintf(_("Policy routing on the router (%s) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters."), join('; ', pr))
: _('No other policy routing ahead of the tunnel rules.'),
null, _('Other policy routing bypasses the home-device path')));
}
// A device the sync has to leave out (a merged import, a hand-edited config). // A device the sync has to leave out (a merged import, a hand-edited config).
// Its sentences (core.model_errors), how many more, then what it means.
let data = core.model_errors(m); let data = core.model_errors(m);
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok', push(out, check('data', _('People and devices consistent'), length(data) ? 'error' : 'ok',
length(data) ? `${join(' ', slice(data, 0, 4))}${length(data) > 4 ? ` (${length(data) - 4} more)` : ''} Such devices are left out of the tunnels: fix or remove them.` length(data) ? join(' ', filter([ join(' ', slice(data, 0, 4)), length(data) > 4 ? sprintf(_('(%d more)'), length(data) - 4) : null,
: 'Every device has a key and an address of its own inside its server.')); _('Such devices are left out of the tunnels: fix or remove them.') ], (x) => x))
: _('Every device has a key and an address of its own inside its server.'),
null, _('People and devices are inconsistent')));
let fwc = cursor(); let fwc = cursor();
fwc.load('firewall'); fwc.load('firewall');
@@ -443,21 +519,23 @@ export function health(m) {
for (let id, srv in m.servers) { for (let id, srv in m.servers) {
let label = length(m.servers) > 1 ? ` (${srv.name})` : ''; let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
if (!srv.enabled) { if (!srv.enabled) {
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.')); push(out, check(`srv_${id}`, _('Server') + label, 'skip', _('Server is disabled.')));
continue; continue;
} }
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep)); push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep));
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`)); push(out, endpoint_check(`ep_${id}`, _('Public address') + label, _('Public address needs attention') + label,
srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
if (srv.lan_like) { if (srv.lan_like) {
let ls = loop.status(); let ls = loop.status();
let nh = need.home; let nh = need.home;
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn', push(out, check(`home_${id}`, _('Internet like a home device') + label, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` : ls.active && ls.bridged ? sprintf(_('Traffic enters %s as %s, so it is handled like any device on your LAN.'), ls.dev, ls.address) :
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` : length(nh) ? sprintf(_('Needs %s. Internet traffic leaves through WAN directly until then.'), join(', ', nh)) :
ls.active ? `The link is up but not attached to ${ls.dev}.` : ls.active ? sprintf(_('The link is up but not attached to %s.'), ls.dev) :
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`, // loop.status()'s own sentence, then what it means.
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply')); `${ls.error ?? _('Not set up.')} ${_('Internet traffic leaves through WAN directly.')}`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply', _('Internet like a home device isn’t working') + label));
} }
} }
@@ -469,10 +547,11 @@ export function health(m) {
// A new config (a server turned on, the home link up) restarts it: give it a few seconds. // A new config (a server turned on, the home link up) restarts it: give it a few seconds.
let restarting = !running && conf != null && time() - conf.mtime < 10; let restarting = !running && conf != null && time() - conf.mtime < 10;
let ok = running || restarting; let ok = running || restarting;
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn', push(out, check('resolver', _('DNS for Home-only devices'), ok ? 'ok' : 'warn',
restarting ? 'Restarting with the new settings.' : restarting ? _('Restarting with the new settings.') :
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`) ok ? (rt.mode == 'ns' ? sprintf(_('Plain resolver running next to the LAN (%s).'), rt.address) : sprintf(_('Plain resolver on port %d.'), rt.port))
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply')); : _('The resolver is not running; Home-only devices cannot resolve names.'),
ok ? null : 'apply', _('DNS for Home-only devices isn’t working')));
} }
if (m.settings.portal_enabled) if (m.settings.portal_enabled)
@@ -499,9 +578,9 @@ export function fix(id) {
// Only Dawnline's own tunnels: never another interface of the router. // Only Dawnline's own tunnels: never another interface of the router.
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key); let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
if (!length(mine)) if (!length(mine))
die(`${m[1]} is not one of Dawnline's tunnels.`); die(sprintf(_("%s is not one of Dawnline's tunnels."), m[1]));
system(`ifup ${q(m[1])}`); system(`ifup ${q(m[1])}`);
return { ok: true }; return { ok: true };
} }
die('Unknown fix.'); die(_('Unknown fix.'));
}; };
@@ -0,0 +1,71 @@
// Dawnline — the backend's messages in the admin's language: what die()
// reports, the health checks, the updater's phases. Text is English in the
// code, wrapped in _() and N_() (web/i18n/extract.ts collects them into the
// luci-i18n-dawnline-<lang> catalog with the admin UI's strings), with
// placeholders filled by sprintf() after the lookup:
//
// die(sprintf(_('Download failed: %s'), asset));
//
// Translated through LuCI's own catalog reader (luci.core, as LuCI's pages
// are) in the language use() set: the admin page's, sent with every RPC call
// (rpcd/ucode/luci.dawnline) and handed to the updater. With no language,
// no Dawnline translation installed for it, or no luci-base (the unit tests'
// rootfs), the English as written. The portal sets none: its page translates
// the messages it gets with its own catalog.
import { stat } from 'fs';
const DIR = '/usr/lib/lua/luci/i18n';
// A C module, loaded at run time: luci-base may be missing, and a static import would not compile then.
let lmo = null;
try {
lmo = require('luci.core');
}
catch (e) {
lmo = null;
}
let active = null;
/**
* Speak `lang` from now on ("ru"; null or "en" for English). Only a language
* with a Dawnline catalog: LuCI's others alone would translate a few words.
*/
export function use(lang) {
active = null;
if (!lmo || type(lang) != 'string' || lang == 'en' || !match(lang, /^[a-z][a-z][a-z]?([_-][A-Za-z][A-Za-z][A-Za-z]?[A-Za-z]?)?$/))
return;
lang = lc(replace(lang, '_', '-'));
if (!stat(`${DIR}/dawnline.${lang}.lmo`))
return;
if (lmo.load_catalog(lang, DIR) && lmo.change_catalog(lang))
active = lang;
};
/** The language use() set, when its catalog is in use; null for English. */
export function current() {
return active;
};
/** `msg` in the language use() set (the English when the catalog has no translation). */
export function _(msg) {
return (active ? lmo.translate(msg) : null) ?? msg;
};
/** `one` or `many` for n, by the language's plural rules (Russian has three forms). */
export function N_(n, one, many) {
return (active ? lmo.ntranslate(n, one, many) : null) ?? (n == 1 ? one : many);
};
/**
* A service log line's words, as written: the log is kept in English (the
* agent that writes most of it has no language) and read later in any.
* Marking them collects them into the catalog and into the admin page's list
* of log templates, which puts each line into the reader's language when it
* is shown (web/src/admin/events/logwords.ts): sprintf(L_('updated · %s → %s'), a, b).
* Keep a line's English as it was: old lines match it too.
*/
export function L_(s) {
return s;
};
@@ -29,7 +29,7 @@ export const CATEGORY = {
device_added: 'people', device_removed: 'people', devices_removed: 'people', device_added: 'people', device_removed: 'people', devices_removed: 'people',
device_changed: 'people', device_keys: 'people', link_changed: 'people', device_changed: 'people', device_keys: 'people', link_changed: 'people',
person_added: 'people', person_removed: 'people', person_changed: 'people', person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people', paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems', server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
}; };
export const CATEGORIES = [ 'connections', 'people', 'problems' ]; export const CATEGORIES = [ 'connections', 'people', 'problems' ];
@@ -395,6 +395,35 @@ export function add_event_merged(e, window) {
unlock(l); unlock(l);
}; };
/**
* Places for connections logged before their address was located (the
* lookup finishes after the event): connect events since `since` from an
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
* Returns true when `ev` changed.
*/
export function fill_places(ev, where, since) {
let changed = false;
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
let e = ev[i];
if (e.type == 'connect' && !e.where && where[e.detail]) {
e.where = where[e.detail];
changed = true;
}
}
return changed;
};
/** fill_places() on the live log, written only when something changed. */
export function set_places(where, since) {
let l = lock('events');
let ev = load_events();
if (fill_places(ev, where, since)) {
ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
}
unlock(l);
};
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */ /** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
export function persist_events(pol) { export function persist_events(pol) {
pol ??= policy(); pol ??= policy();
@@ -4,7 +4,7 @@
// time, so a slow DNS server must not hold up the whole admin UI. // time, so a slow DNS server must not hold up the whole admin UI.
import { readfile } from 'fs'; import { readfile } from 'fs';
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util'; import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
@@ -23,9 +23,10 @@ function valid_name(h) {
} }
/** /**
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not * Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
* resolve). IP addresses map to themselves. Every uncached name is asked of * does not resolve). IP addresses map to themselves. Every uncached name is
* every server at once; the first server (in SERVERS order) that answers wins. * asked of every server at once, A and AAAA; the first server (in SERVERS
* order) that answers wins.
*/ */
export function resolve_all(hosts) { export function resolve_all(hosts) {
let out = {}, now = time(), todo = []; let out = {}, now = time(), todo = [];
@@ -33,7 +34,7 @@ export function resolve_all(hosts) {
for (let h in hosts) { for (let h in hosts) {
if (h == null || out[h] != null) if (h == null || out[h] != null)
continue; continue;
if (ip2int(h) != null) { if (ip2int(h) != null || is_ip6(h)) {
out[h] = [ h ]; out[h] = [ h ];
continue; continue;
} }
@@ -55,14 +56,16 @@ export function resolve_all(hosts) {
let cmds = []; let cmds = [];
for (let i = 0; i < length(todo); i++) for (let i = 0; i < length(todo); i++)
for (let j = 0; j < length(SERVERS); j++) for (let j = 0; j < length(SERVERS); j++)
for (let t in [ 'a', 'aaaa' ])
// nslookup's own timeout: some firmware builds BusyBox without `timeout`. // nslookup's own timeout: some firmware builds BusyBox without `timeout`.
push(cmds, `( nslookup -type=a -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`); push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`); sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
for (let i = 0; i < length(todo); i++) { for (let i = 0; i < length(todo); i++) {
let ips = []; let ips = [];
for (let j = 0; j < length(SERVERS) && !length(ips); j++) { for (let j = 0; j < length(SERVERS) && !length(ips); j++)
let r = readfile(`${dir}/${i}.${j}`) ?? ''; for (let t in [ 'a', 'aaaa' ]) {
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null); let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
} }
out[todo[i]] = ips; out[todo[i]] = ips;
cache[todo[i]] = { ts: now, ips }; cache[todo[i]] = { ts: now, ips };
@@ -22,7 +22,8 @@
// //
// Everything is derived from the router at run time; nothing assumes a // Everything is derived from the router at run time; nothing assumes a
// particular subnet or tool. If the LAN is not a bridge or setup fails, the // particular subnet or tool. If the LAN is not a bridge or setup fails, the
// direct path stays and status() says why. // direct path stays and status() says why (kept as a code in loop.json, which
// apply and the agent write with no language; error_text() makes the words).
import { readfile, writefile, readlink, stat, unlink } from 'fs'; import { readfile, writefile, readlink, stat, unlink } from 'fs';
import { cursor } from 'uci'; import { cursor } from 'uci';
@@ -33,6 +34,7 @@ import * as net from 'dawnline.net';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import * as resolver from 'dawnline.resolver'; import * as resolver from 'dawnline.resolver';
import { _, L_ } from 'dawnline.i18n';
export const NS = 'dawnline'; export const NS = 'dawnline';
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1'; const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
@@ -40,7 +42,7 @@ const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
export const RESOLVER_CONF = resolver.CONF; export const RESOLVER_CONF = resolver.CONF;
const STATE = `${RUN_DIR}/loop.json`; const STATE = `${RUN_DIR}/loop.json`;
const WHO = 'Internet like a home device'; const WHO = L_('Internet like a home device');
function log(msg, level, detail) { function log(msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, WHO); slog('dawnline', level ?? 'info', msg, detail, WHO);
@@ -180,6 +182,57 @@ function pick_table(saved) {
return null; return null;
} }
/* ---------- why it is off ---------- */
/*
* The reasons plan() and ensure() give, kept in loop.json:
* { code: 'no_lan' } no LAN detected
* { code: 'not_bridge', dev } the LAN is not a bridge
* { code: 'no_ipv4', dev } the LAN has no IPv4 address
* { code: 'no_address', net } no free address on the LAN's network
* { code: 'no_transit' } no free link-local range for the internal link
* { code: 'no_table' } no free routing table
* { code: 'setup', detail } a command failed (detail: it and what it said)
*/
/** A reason from plan() for the service log: English, like every log line. */
function error_note(e) {
if (e.code == 'no_lan')
return L_('No LAN detected.');
if (e.code == 'not_bridge')
return sprintf(L_('%s is not a bridge, so Dawnline cannot join the LAN as a device.'), e.dev);
if (e.code == 'no_ipv4')
return sprintf(L_('%s has no IPv4 address.'), e.dev);
if (e.code == 'no_address')
return sprintf(L_('No free address on %s.'), e.net);
if (e.code == 'no_transit')
return L_('No free link-local range for the internal link.');
return L_('No free routing table.');
}
/**
* Why "like a home device" is off (a reason above), as a sentence in the
* reader's language. Null for none; the English of a loop.json written by an
* older version as it is.
*/
export function error_text(e) {
if (type(e) != 'object')
return e ?? null;
if (e.code == 'no_lan')
return _('No LAN detected.');
if (e.code == 'not_bridge')
return sprintf(_('%s is not a bridge, so Dawnline cannot join the LAN as a device.'), e.dev);
if (e.code == 'no_ipv4')
return sprintf(_('%s has no IPv4 address.'), e.dev);
if (e.code == 'no_address')
return sprintf(_('No free address on %s.'), e.net);
if (e.code == 'no_transit')
return _('No free link-local range for the internal link.');
if (e.code == 'no_table')
return _('No free routing table.');
return sprintf(_('Setup failed: %s'), e.detail);
};
/* ---------- plan ---------- */ /* ---------- plan ---------- */
function settings() { function settings() {
@@ -199,8 +252,8 @@ function all_ifnames(m) {
} }
/** /**
* What should exist, or { error } when it cannot. Pure apart from reading * What should exist, or { error } (a reason, see error_text) when it cannot.
* router state (and one ping per candidate address). * Pure apart from reading router state (and one ping per candidate address).
*/ */
export function plan(m) { export function plan(m) {
let srvs = wanted(m); let srvs = wanted(m);
@@ -210,24 +263,24 @@ export function plan(m) {
let dev = snap.lan; let dev = snap.lan;
let d = snap.devices[dev]; let d = snap.devices[dev];
if (!dev || !d) if (!dev || !d)
return { error: 'No LAN detected.' }; return { error: { code: 'no_lan' } };
if (d.kind != 'bridge') if (d.kind != 'bridge')
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` }; return { error: { code: 'not_bridge', dev } };
let lan = parse_cidr(d.addrs[0]); let lan = parse_cidr(d.addrs[0]);
if (!lan) if (!lan)
return { error: `${dev} has no IPv4 address.` }; return { error: { code: 'no_ipv4', dev } };
let facts = dhcp_facts(d.logical, lan); let facts = dhcp_facts(d.logical, lan);
let st = settings(); let st = settings();
let addr = pick_address(lan, facts, st.lan_address, dev); let addr = pick_address(lan, facts, st.lan_address, dev);
if (!addr) if (!addr)
return { error: `No free address on ${int2ip(lan.net)}/${lan.prefix}.` }; return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
let last = read_json(STATE, {}); let last = read_json(STATE, {});
let tx = pick_transit(last?.transit); let tx = pick_transit(last?.transit);
if (tx == null) if (tx == null)
return { error: 'No free link-local range for the internal link.' }; return { error: { code: 'no_transit' } };
let table = pick_table(last?.plan?.table); let table = pick_table(last?.plan?.table);
if (table == null) if (table == null)
return { error: 'No free routing table.' }; return { error: { code: 'no_table' } };
let servers = []; let servers = [];
for (let srv in srvs) { for (let srv in srvs) {
let sn = net.server_net(srv, snap); let sn = net.server_net(srv, snap);
@@ -362,8 +415,8 @@ export function ensure(m, force) {
remove(ifnames); remove(ifnames);
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
write_json(STATE, { error: p.error, off: !!p.off }, 0o644); write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
if (p.error && p.error != was.error) if (p.error && sprintf('%J', p.error) != sprintf('%J', was.error))
log('is off', 'error', p.error); log(L_('is off'), 'error', error_note(p.error));
return p; return p;
} }
let last = read_json(STATE, {}); let last = read_json(STATE, {});
@@ -411,18 +464,19 @@ export function ensure(m, force) {
push(errs, ...run(sync_rules(p, ifnames))); push(errs, ...run(sync_rules(p, ifnames)));
if (length(errs)) { if (length(errs)) {
if (read_json(STATE, {}).error != `Setup failed: ${errs[0]}`) let why = { code: 'setup', detail: errs[0] };
log('failed — internet goes out directly for now', 'error', errs[0]); if (sprintf('%J', read_json(STATE, {}).error) != sprintf('%J', why))
log(L_('failed - internet goes out directly for now'), 'error', errs[0]);
remove(ifnames); remove(ifnames);
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644); write_json(STATE, { error: why }, 0o644);
return { error: errs[0] }; return { error: why };
} }
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644); write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address) if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
log(`is on · traffic enters ${p.dev} as ${p.address}`, 'up'); log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
else if (!healthy) else if (!healthy)
log(`was broken — set up again (${p.dev} as ${p.address})`, 'repair'); log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
return p; return p;
}; };
@@ -440,7 +494,7 @@ export function remember(p) {
}); });
}; };
/** Last applied state for views and health checks. */ /** Last applied state for views and health checks; `error` says why it is off (error_text). */
export function status() { export function status() {
let s = read_json(STATE, {}); let s = read_json(STATE, {});
if (s.plan) if (s.plan)
@@ -449,7 +503,7 @@ export function status() {
dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns, dev: s.plan.dev, address: s.plan.address, dns: s.plan.dns, gateway: s.plan.gateway, transit: s.plan.tx_ns,
bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev, bridged: replace(readlink(`/sys/class/net/${LAN_ROOT}/master`) ?? '', /^.*\//, '') == s.plan.dev,
}; };
return { active: false, off: !!s.off, error: s.error }; return { active: false, off: !!s.off, error: error_text(s.error) };
}; };
/** The DNS address tunnel clients should use while the loop is up. */ /** The DNS address tunnel clients should use while the loop is up. */
@@ -8,6 +8,7 @@ import { stat, unlink } from 'fs';
import { q, slog } from 'dawnline.util'; import { q, slog } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import { L_ } from 'dawnline.i18n';
const LAN_CGI = '/www/cgi-bin/dawnline-portal'; const LAN_CGI = '/www/cgi-bin/dawnline-portal';
const LAN_CGI_URL = '/cgi-bin/dawnline-portal'; const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
@@ -32,7 +33,7 @@ function word_codes() {
} }
}); });
}); });
slog('dawnline', 'info', 'moved to word codes', null, 'Personal links'); slog('dawnline', 'info', L_('moved to word codes'), null, L_('Personal links'));
} }
/* /*
@@ -57,6 +58,14 @@ export function uhttpd() {
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443')); store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
}; };
/** The portal names itself after the server now (the breadcrumb, the tab): its own title setting is gone. */
function portal_title() {
let c = cursor();
c.load('dawnline');
if (c.get('dawnline', 'settings', 'portal_title') != null)
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_title'));
}
/* /*
* Steps that cannot tell from the config whether they ran are recorded in * Steps that cannot tell from the config whether they ran are recorded in
* `settings.migrated` (a list), so they run exactly once. * `settings.migrated` (a list), so they run exactly once.
@@ -93,7 +102,7 @@ function auto_mtu() {
mark_migrated(w, 'auto_mtu'); mark_migrated(w, 'auto_mtu');
}); });
if (any) if (any)
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers'); slog('dawnline', 'info', L_('MTU is now automatic'), null, L_('Servers'));
} }
/** All of them, in order. */ /** All of them, in order. */
@@ -101,4 +110,5 @@ export function run() {
word_codes(); word_codes();
uhttpd(); uhttpd();
auto_mtu(); auto_mtu();
portal_title();
}; };
@@ -2,13 +2,15 @@
// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created // ifname and marked `_dawnline` = server id. Only interfaces Dawnline created
// are changed or removed: a name already used by another interface (`lan`, a // are changed or removed: a name already used by another interface (`lan`, a
// tunnel of your own, one from an imported config) is left alone and the // tunnel of your own, one from an imported config) is left alone and the
// server is reported instead. // server is reported instead. Why a server is kept down is kept in
// core.BLOCKED as a code with its values (awg.blocked_text says it).
import { cursor } from 'uci'; import { cursor } from 'uci';
import { stat, unlink, writefile } from 'fs'; 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, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
import { L_ } from 'dawnline.i18n';
// Set while AmneziaWG is missing and that was logged (once until it is back). // Set while AmneziaWG is missing and that was logged (once until it is back).
const NO_AWG = `${RUN_DIR}/netifd-no-awg`; const NO_AWG = `${RUN_DIR}/netifd-no-awg`;
@@ -35,12 +37,12 @@ export function sync(m) {
let changed = false, touched = [], want = {}; let changed = false, touched = [], want = {};
// Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts. // Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts.
let was = read_json(core.BLOCKED, {}), blocked = {}; let was = read_json(core.BLOCKED, {}), blocked = {};
let block = (srv, msg, detail) => { let block = (srv, why, detail) => {
blocked[srv.id] = msg; blocked[srv.id] = why;
// The rest of this apply works from the same model: no tunnel for it there either. // The rest of this apply works from the same model: no tunnel for it there either.
srv.blocked = msg; srv.blocked = why;
if (was[srv.id] != msg) if (sprintf('%J', was[srv.id]) != sprintf('%J', why))
log(srv.name, msg, 'error', detail); log(srv.name, awg.blocked_note(why), 'error', detail);
}; };
// Without amneziawg-tools there is no protocol script: changing or bringing // Without amneziawg-tools there is no protocol script: changing or bringing
@@ -49,7 +51,7 @@ export function sync(m) {
if (tools && stat(NO_AWG)) if (tools && stat(NO_AWG))
unlink(NO_AWG); unlink(NO_AWG);
else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) { else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) {
log('AmneziaWG', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.'); log('AmneziaWG', L_("isn't installed: tunnels were left as they are"), 'error', L_('Install it in Dawnline → Components.'));
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
writefile(NO_AWG, `${time()}`); writefile(NO_AWG, `${time()}`);
} }
@@ -59,12 +61,12 @@ export function sync(m) {
continue; continue;
let ifn = srv.ifname; let ifn = srv.ifname;
if (!core.valid_ifname(ifn)) { if (!core.valid_ifname(ifn)) {
block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.'); block(srv, { code: 'ifname', ifname: ifn }, 'Interface name: 1-12 lowercase letters, digits or _.');
continue; continue;
} }
let own = owner(ifn, c); let own = owner(ifn, c);
if (own != null && own != id) { if (own != null && own != id) {
block(srv, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`, block(srv, { code: 'taken', ifname: ifn },
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.'); 'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue; continue;
} }
@@ -74,7 +76,7 @@ export function sync(m) {
// disguise is changed. // disguise is changed.
let why = tools ? awg.obf_unsupported(srv.obf) : null; let why = tools ? awg.obf_unsupported(srv.obf) : null;
if (why) { if (why) {
block(srv, `is kept down: ${why}`, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.'); block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
continue; continue;
} }
delete srv.blocked; delete srv.blocked;
@@ -4,6 +4,7 @@
import { access, popen, stat } from 'fs'; import { access, popen, stat } from 'fs';
import { q } from 'dawnline.util'; import { q } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
function run(cmd) { function run(cmd) {
let p = popen(cmd + ' 2>&1', 'r'); let p = popen(cmd + ' 2>&1', 'r');
@@ -99,8 +100,9 @@ function preflight(files, need_kb, log) {
for (let f in files ?? []) for (let f in files ?? [])
need += int(((stat(f)?.size ?? 0) * 3) / 1024); need += int(((stat(f)?.size ?? 0) * 3) / 1024);
if (free < need) if (free < need)
die(`Not enough free space on the router: ${int(free / 1024)} MB free, about ${int(need / 1024) + 1} MB needed. Remove old backups or packages first`); die(sprintf(_('Not enough free space on the router: %d MB free, about %d MB needed. Remove old backups or packages first'),
log?.(` ${int(free / 1024)} MB free on the overlay`); int(free / 1024), int(need / 1024) + 1));
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
} }
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */ /** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
@@ -115,8 +117,8 @@ export function install_files(files, force, log) {
let before = force ? stat(marker)?.mtime : null; let before = force ? stat(marker)?.mtime : null;
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0; let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
if (ok && force && before != null && stat(marker)?.mtime == before) { if (ok && force && before != null && stat(marker)?.mtime == before) {
log?.(' apk did not reinstall the version that is already installed'); log?.(' ' + _('apk did not reinstall the version that is already installed'));
die("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"); die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
} }
return ok; return ok;
}; };
@@ -24,6 +24,10 @@
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings) // disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
// shows the page, but gets them from its HTTPS twin. // shows the page, but gets them from its HTTPS twin.
// //
// Messages go out in the page's language (Accept-Language: the portal's
// fetch sends the visitor's choice) when a Dawnline translation for it is
// installed; else in English, and the page translates the ones it knows.
//
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the // handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal // CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
// that answers anything not shaped like a link (its not_found() twin). // that answers anything not shaped like a link (its not_found() twin).
@@ -36,6 +40,8 @@ import * as live from 'dawnline.live';
import * as view from 'dawnline.view'; import * as view from 'dawnline.view';
import * as schema from 'dawnline.schema'; import * as schema from 'dawnline.schema';
import * as devices from 'dawnline.devices'; import * as devices from 'dawnline.devices';
import * as i18n from 'dawnline.i18n';
import { _ } from 'dawnline.i18n';
const RATE = `${RUN_DIR}/portal-rate.json`; const RATE = `${RUN_DIR}/portal-rate.json`;
const ASSETS = '/usr/share/dawnline/portal/assets'; const ASSETS = '/usr/share/dawnline/portal/assets';
@@ -60,13 +66,22 @@ const SECURITY_HEADERS = {
'Cache-Control': 'no-store', 'Cache-Control': 'no-store',
}; };
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
// States the admin stopped the person in: the portal only shows, it changes nothing. // States the admin stopped the person in: the portal only shows, it changes nothing.
const LOCKED = { const LOCKED = [ 'paused', 'expired' ];
paused: 'Your access is paused by the admin.',
expired: 'Your access has ended. Ask the admin to extend it.', /** Why a stopped person (a LOCKED state) can't change anything, in the visitor's language; null for other states. */
}; function locked_reason(st) {
if (st == 'paused')
return _('Your access is paused.');
if (st == 'expired')
return _('Your access has ended.');
return null;
}
/** Why a new device or a new set-up is refused while the router has no AmneziaWG. */
function not_ready() {
return _("Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.");
}
function html_escape(s) { function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]); return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
@@ -124,7 +139,7 @@ function body(r) {
if (len <= 0) if (len <= 0)
return {}; return {};
if (len > BODY_MAX) if (len > BODY_MAX)
fail(r, '413 Payload Too Large', 'Request too large.'); fail(r, '413 Payload Too Large', _('Request too large.'));
let raw = ''; let raw = '';
while (length(raw) < len) { while (length(raw) < len) {
let chunk = r.io.read(len - length(raw)); let chunk = r.io.read(len - length(raw));
@@ -137,7 +152,7 @@ function body(r) {
return type(j) == 'object' ? j : {}; return type(j) == 'object' ? j : {};
} }
catch (e) { catch (e) {
fail(r, '400 Bad Request', 'Invalid JSON.'); fail(r, '400 Bad Request', _('Invalid JSON.'));
} }
} }
@@ -236,16 +251,21 @@ function rate_action(r) {
write_json(RATE, st, 0o600); write_json(RATE, st, 0o600);
unlock(l); unlock(l);
if (v.count > ACTION_LIMIT) if (v.count > ACTION_LIMIT)
fail(r, '429 Too Many Requests', 'Too many changes in a short time. Try again in a few minutes.'); fail(r, '429 Too Many Requests', _('Too many changes in a short time. Try again in a few minutes.'));
} }
/* ---------- pages ---------- */ /* ---------- pages ---------- */
/** What the page is called (the tab, the first crumb): the person's server, or Dawnline. */
function place(r) {
return r.person ? r.m.servers[r.person.server]?.name || 'Dawnline' : 'Dawnline';
}
/** The app shell; it reads the code from its own URL and sends it along. */ /** The app shell; it reads the code from its own URL and sends it along. */
function shell(r) { function shell(r) {
// The build's time joins the version so every update busts the hour-long asset cache. // The build's time joins the version so every update busts the hour-long asset cache.
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`; let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
let base = r.base, title = r.title; let base = r.base, title = place(r);
headers(r, '200 OK', { headers(r, '200 OK', {
'Content-Type': 'text/html; charset=utf-8', 'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " + 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
@@ -300,7 +320,7 @@ function person_state(m, p, usage) {
let st = core.person_state(m, p, usage); let st = core.person_state(m, p, usage);
if (st == 'server_off') { if (st == 'server_off') {
let own = core.own_state(m, p, usage); let own = core.own_state(m, p, usage);
if (LOCKED[own]) if (index(LOCKED, own) >= 0)
return own; return own;
} }
return st; return st;
@@ -308,7 +328,7 @@ function person_state(m, p, usage) {
/** Why the person can't change anything right now, or null. */ /** Why the person can't change anything right now, or null. */
function locked(r) { function locked(r) {
return LOCKED[person_state(r.m, r.person, core.load_usage())] ?? null; return locked_reason(person_state(r.m, r.person, core.load_usage()));
} }
/** Refuses a change (or a config) while the person is stopped. */ /** Refuses a change (or a config) while the person is stopped. */
@@ -335,7 +355,13 @@ function https_url(r) {
function need_https(r) { function need_https(r) {
let u = https_url(r); let u = https_url(r);
if (u) if (u)
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u }); send_json(r, '403 Forbidden', { error: _('Open this link over HTTPS to get the connection settings.'), https_url: u });
}
/** The router's offset from UTC in minutes: the admin sets hours in its time, the page shows the visitor's. */
function tz_offset() {
let t = time();
return int((timegm(localtime(t)) - t) / 60);
} }
/** Everything the page shows. */ /** Everything the page shows. */
@@ -344,28 +370,32 @@ function state(r) {
let usage = core.load_usage(); let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage)); let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
v.state = person_state(m, person, usage); v.state = person_state(m, person, usage);
// Day by day this month, for the page's chart (the admin's views have no use for it).
v.month_days = view.month_days(usage.people?.[person.id]);
let srv = m.servers[person.server]; let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel. // The device this page was opened from, through the tunnel or beside it.
let here = null; let here = view.device_here(v.devices, r.peer);
for (let id, d in m.devices)
if (d.person == person.id && d.address == r.peer)
here = id;
return { return {
title: r.title,
person: v, person: v,
here, here,
server: { server: {
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh, name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app). // AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false, awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
}, },
can_add: length(person.devices) < person.device_limit, can_add: length(person.devices) < person.device_limit,
locked: LOCKED[v.state] != null, locked: index(LOCKED, v.state) >= 0,
// Over plain HTTP: where the configurations are (keys only travel encrypted). // Over plain HTTP: where the configurations are (keys only travel encrypted).
https_url: https_url(r), https_url: https_url(r),
kinds: core.KINDS, kinds: core.KINDS,
// The router's day: access ends and usage days follow its clock, not the browser's. // The router's day: access ends and usage days follow its clock, not the browser's.
today: today(), today: today(),
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
now: time(),
// And its time zone: hours are set in the router's time, shown in the visitor's.
tz_offset: tz_offset(),
version: VERSION, version: VERSION,
}; };
} }
@@ -374,7 +404,7 @@ function state(r) {
function own_device(r, id) { function own_device(r, id) {
let d = r.m.devices[id]; let d = r.m.devices[id];
if (!d || d.person != r.person.id) if (!d || d.person != r.person.id)
fail(r, '404 Not Found', 'Device not found.'); fail(r, '404 Not Found', _('Device not found.'));
return d; return d;
} }
@@ -387,7 +417,7 @@ function api_add(r) {
need_https(r); need_https(r);
let b = body(r); let b = body(r);
if (!devices.ready()) if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY); fail(r, '503 Service Unavailable', not_ready());
rate_action(r); rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key })); let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
reload(r); reload(r);
@@ -408,11 +438,12 @@ const ACTIONS = {
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id })); guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
return {}; return {};
}, },
rotate: (r, d, b) => { // Set up from scratch: new keys and the new configuration, which the set-up sheet takes in.
reconnect: (r, d, b) => {
need_https(r); need_https(r);
if (!devices.ready()) if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY); fail(r, '503 Service Unavailable', not_ready());
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer })); let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config }; return { config };
}, },
'delete': (r, d, b) => { 'delete': (r, d, b) => {
@@ -427,7 +458,7 @@ function api_device(r, id) {
let b = body(r); let b = body(r);
let act = ACTIONS[b.action]; let act = ACTIONS[b.action];
if (!act) if (!act)
fail(r, '400 Bad Request', 'Unknown action.'); fail(r, '400 Bad Request', _('Unknown action.'));
rate_action(r); rate_action(r);
let res = act(r, d, b); let res = act(r, d, b);
reload(r); reload(r);
@@ -479,7 +510,6 @@ export function handle(io) {
method: env.REQUEST_METHOD ?? 'GET', method: env.REQUEST_METHOD ?? 'GET',
peer: env.REMOTE_ADDR ?? '', peer: env.REMOTE_ADDR ?? '',
buckets: buckets(env), buckets: buckets(env),
title: m.settings.portal_title || 'Dawnline',
// The port in the visitor's address bar ([v6]:port, name:port, or the default). // The port in the visitor's address bar ([v6]:port, name:port, or the default).
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443', hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null, person: null,
@@ -527,21 +557,23 @@ export function handle(io) {
let origin = header('origin'); let origin = header('origin');
if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) || if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) ||
(origin != null && origin != `${https ? 'https' : 'http'}://${host}`)) (origin != null && origin != `${https ? 'https' : 'http'}://${host}`))
fail(r, '403 Forbidden', 'Cross-site request refused.'); fail(r, '403 Forbidden', _('Cross-site request refused.'));
} }
else if (r.method != 'GET') else if (r.method != 'GET')
fail(r, '405 Method Not Allowed', 'Method not allowed.'); fail(r, '405 Method Not Allowed', _('Method not allowed.'));
let rt = route(API, r.method, slice(rest, 1)); let rt = route(API, r.method, slice(rest, 1));
if (!rt) if (!rt)
fail(r, '404 Not Found', 'Not found.'); fail(r, '404 Not Found', _('Not found.'));
rt.run(r, rt.args[0]); rt.run(r, rt.args[0]);
fail(r, '404 Not Found', 'Not found.'); fail(r, '404 Not Found', _('Not found.'));
}; };
/** Run handle() and swallow its early end. */ /** Run handle() and swallow its early end. */
export function serve(io) { export function serve(io) {
try { try {
// "ru-RU,ru;q=0.9" → ru (i18n.use takes plain language codes only).
i18n.use((match(io.env.HTTP_ACCEPT_LANGUAGE ?? '', /^[ \t]*([A-Za-z][A-Za-z][A-Za-z]?)/) ?? [])[1]);
handle(io); handle(io);
} }
catch (e) { catch (e) {
@@ -6,6 +6,7 @@ import * as awg from 'dawnline.awg';
import * as health from 'dawnline.health'; import * as health from 'dawnline.health';
import * as schema from 'dawnline.schema'; import * as schema from 'dawnline.schema';
import { uniq } from 'dawnline.util'; import { uniq } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
/** /**
* An rpcd handler from fn(args): an object result is passed on, anything else * An rpcd handler from fn(args): an object result is passed on, anything else
@@ -34,21 +35,27 @@ export function clamp_days(v) {
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30; return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
}; };
export const METHODS = [ 'off', 'standard', 'strong', 'balanced', 'max' ]; export const METHODS = [ 'off', 'balanced', 'max' ];
/** The disguise a new server gets: the strongest this router can run. */
export function default_method() {
let c = awg.caps();
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
};
/** A disguise method the installed AmneziaWG can run. */ /** A disguise method the installed AmneziaWG can run. */
export function check_method(name) { export function check_method(name) {
if (index(METHODS, name) < 0) if (index(METHODS, name) < 0)
die('Unknown disguise method.'); die(_('Unknown disguise method.'));
let c = awg.caps(); let c = awg.caps();
if (name == 'max' && !c.v3) if (name == 'max' && !c.v3)
die(awg.installed() die(awg.installed()
? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.' ? _('Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.')
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.'); : _('AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.'));
if (name == 'balanced' && !c.v2) if (name == 'balanced' && !c.v2)
die(awg.installed() die(awg.installed()
? 'Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.' ? _('Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.')
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.'); : _('AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.'));
return name; return name;
}; };
@@ -69,6 +76,7 @@ function tcp_forwards(m) {
/** /**
* TCP ports the portal can't take, and who holds them: [{ from, to, who }]. * TCP ports the portal can't take, and who holds them: [{ from, to, who }].
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN. * The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
* `who` is shown in the admin's language ("Used by %s.").
*/ */
export function tcp_taken(m) { export function tcp_taken(m) {
let out = []; let out = [];
@@ -80,11 +88,11 @@ export function tcp_taken(m) {
} }
}; };
for (let p in schema.RESERVED_PORTS) for (let p in schema.RESERVED_PORTS)
hold(p, 'the router itself'); hold(p, _('the router itself'));
for (let p, name in health.tcp_port_programs()) for (let p, name in health.tcp_port_programs())
hold(+p, `${name} on this router`); hold(+p, sprintf(_('%s on this router'), name));
for (let f in tcp_forwards(m)) for (let f in tcp_forwards(m))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` }); push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out; return out;
}; };
@@ -94,12 +102,12 @@ export function check_portal(m, was) {
return; return;
let port = s.portal_port; let port = s.portal_port;
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0) if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'); die(_('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'));
let ports = [ port ]; let ports = [ port ];
if (core.portal_http(m)) { if (core.portal_http(m)) {
let hp = core.portal_http_port(m); let hp = core.portal_http_port(m);
if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0) if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0)
die(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`); die(sprintf(_('Links on IP addresses use plain HTTP on the next port (%d), which the portal cannot take. Choose another portal port.'), hp));
push(ports, hp); push(ports, hp);
} }
// Only ports the portal does not hold already: our own uhttpd is not an owner anyway. // Only ports the portal does not hold already: our own uhttpd is not an owner anyway.
@@ -114,11 +122,13 @@ export function check_portal(m, was) {
continue; continue;
let owners = health.tcp_port_owners(p); let owners = health.tcp_port_owners(p);
if (length(owners)) if (length(owners))
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`); die(sprintf(p != port
? _("TCP %d is already used by %s. Links on IP addresses use plain HTTP on the port after the portal's. Choose another portal port.")
: _('TCP %d is already used by %s. Choose another portal port.'), p, join(', ', owners)));
} }
// A forwarded port never reaches the router: the portal would be unreachable. // A forwarded port never reaches the router: the portal would be unreachable.
for (let p in ports) for (let p in ports)
for (let f in tcp_forwards(m)) for (let f in tcp_forwards(m))
if (f.from <= p && p <= f.to) if (f.from <= p && p <= f.to)
die(`TCP ${p} is sent on by port forward “${f.name}”. Choose another portal port.`); die(sprintf(_('TCP %d is sent on by port forward “%s”. Choose another portal port.'), p, f.name));
}; };
@@ -4,7 +4,7 @@
import { readfile } from 'fs'; import { readfile } from 'fs';
import { cursor } from 'uci'; import { cursor } from 'uci';
import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util'; import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
@@ -12,6 +12,7 @@ import * as access from 'dawnline.access';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema'; import * as schema from 'dawnline.schema';
import { wrap, str } from 'dawnline.rpc.common'; import { wrap, str } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
/* ---------- services ---------- */ /* ---------- services ---------- */
@@ -22,29 +23,29 @@ function new_id(m, make) {
if (!store.id_taken(m, id)) if (!store.id_taken(m, id))
return id; return id;
} }
die('Could not find a free id, try again.'); die(_('Could not find a free id, try again.'));
} }
function service_set(a) { function service_set(a) {
let name = str(a.name); let name = str(a.name);
if (name == '' || length(name) > 48) if (!valid_name(name))
die('Enter a service name.'); die(_('Service: Enter a name: up to 48 characters, without < > " or \\.'));
let address = str(a.address); let address = str(a.address);
if (!schema.ipv4(address)) if (!schema.ipv4(address))
die('Address must be an IPv4 address.'); die(_('Address must be an IPv4 address.'));
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != ''); let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != '');
for (let pt in ports) for (let pt in ports)
if (!schema.valid_port(pt)) if (!schema.valid_port(pt))
die(`Invalid port ${pt}.`); die(sprintf(_('Invalid port %s.'), pt));
let id = store.transact((c, m) => { let id = store.transact((c, m) => {
let id = str(a.id); let id = str(a.id);
if (id == '') if (id == '')
id = new_id(m, () => `svc_${rand_int(100000, 999999)}`); id = new_id(m, () => `svc_${rand_int(100000, 999999)}`);
else if (!match(id, /^[A-Za-z0-9_]{1,32}$/)) else if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
die('Invalid service id.'); die(_('Invalid service id.'));
// Never turn a person, device, server, circle or the settings into a service. // Never turn a person, device, server, circle or the settings into a service.
else if (!m.services[id] && store.id_taken(m, id)) else if (!m.services[id] && store.id_taken(m, id))
die('That id is taken.'); die(_('That id is taken.'));
c.set(core.CONFIG, id, 'service'); c.set(core.CONFIG, id, 'service');
c.set(core.CONFIG, id, 'name', name); c.set(core.CONFIG, id, 'name', name);
c.set(core.CONFIG, id, 'address', address); c.set(core.CONFIG, id, 'address', address);
@@ -61,7 +62,7 @@ function service_set(a) {
function service_delete(a) { function service_delete(a) {
store.transact((c, m) => { store.transact((c, m) => {
if (!m.services[a.id]) if (!m.services[a.id])
die('Unknown service.'); die(_('Unknown service.'));
c.delete(core.CONFIG, a.id); c.delete(core.CONFIG, a.id);
for (let pid, p in m.people) for (let pid, p in m.people)
if (index(p.services, a.id) >= 0) { if (index(p.services, a.id) >= 0) {
@@ -81,18 +82,18 @@ function service_delete(a) {
/** Create or edit a circle; `members` (person ids) replaces who is in it. */ /** Create or edit a circle; `members` (person ids) replaces who is in it. */
function circle_set(a) { function circle_set(a) {
let name = str(a.name); let name = str(a.name);
if (name == '' || length(name) > 32) if (!valid_name(name) || ulength(name) > 32)
die('Enter a circle name (up to 32 characters).'); die(_('Enter a circle name: up to 32 characters, without < > " or \\.'));
let res = store.transact((c, m) => { let res = store.transact((c, m) => {
let ci = a.id ? m.circles[a.id] : null; let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci) if (a.id && !ci)
die('Unknown circle.'); die(_('Unknown circle.'));
let server = ci?.server ?? a.server; let server = ci?.server ?? a.server;
if (!m.servers[server]) if (!m.servers[server])
die('Unknown server.'); die(_('Unknown server.'));
for (let id, o in m.circles) for (let id, o in m.circles)
if (id != a.id && o.server == server && lc(o.name) == lc(name)) if (id != a.id && o.server == server && lc(o.name) == lc(name))
die(`${name} already exists.`); die(sprintf(_('%s already exists.'), name));
let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`); let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`);
let n = core.CIRCLE_COLORS; let n = core.CIRCLE_COLORS;
c.set(core.CONFIG, id, 'circle'); c.set(core.CONFIG, id, 'circle');
@@ -121,7 +122,7 @@ function circle_delete(a) {
let res = store.transact((c, m) => { let res = store.transact((c, m) => {
let ci = m.circles[a.id]; let ci = m.circles[a.id];
if (!ci) if (!ci)
die('Unknown circle.'); die(_('Unknown circle.'));
c.delete(core.CONFIG, a.id); c.delete(core.CONFIG, a.id);
for (let pid, p in m.people) for (let pid, p in m.people)
if (p.circle == a.id) if (p.circle == a.id)
@@ -173,7 +174,7 @@ function home_hosts(a) {
let m = core.load(); let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0]; let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv) if (!srv)
die('No server yet.'); die(_('No server yet.'));
let nets = []; let nets = [];
for (let cidr in net.server_net(srv).nets) { for (let cidr in net.server_net(srv).nets) {
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/); let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
@@ -1,6 +1,7 @@
// Dawnline rpcd methods: Diagnostics (Health, the service log), backups, // Dawnline rpcd methods: Diagnostics (Health, the service log), backups,
// export / import, and removing Dawnline. // export / import, and removing Dawnline.
import { _ } from 'dawnline.i18n';
import { slog_clear, admin_log } from 'dawnline.util'; import { slog_clear, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
@@ -49,10 +50,10 @@ function import_all(a) {
/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */ /** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */
function uninstall(a) { function uninstall(a) {
if (a.confirm != 'remove') if (a.confirm != 'remove')
die('Type "remove" to confirm.'); die(_('Type "remove" to confirm.'));
// Not in the middle of an update (opkg/apk may be installing Dawnline itself). // Not in the middle of an update (opkg/apk may be installing Dawnline itself).
if (upd.busy()) if (upd.busy())
die('An update is running: wait for it to finish, then remove Dawnline.'); die(_('An update is running: wait for it to finish, then remove Dawnline.'));
backup.backup_create('pre-remove'); backup.backup_create('pre-remove');
// Stop first: the agent would put back what teardown removes, and could start an automatic update. // Stop first: the agent would put back what teardown removes, and could start an automatic update.
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1'); system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
@@ -9,9 +9,10 @@ import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store'; import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices'; import * as devices from 'dawnline.devices';
import { wrap, str, clamp_days } from 'dawnline.rpc.common'; import { wrap, str, clamp_days } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period', const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
'bonus_gb', 'hours', 'note', 'dns_mode' ]; 'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
/* ---------- people ---------- */ /* ---------- people ---------- */
@@ -39,12 +40,16 @@ function person_update(a) {
fields.circle = a.circle; fields.circle = a.circle;
if (type(a.home_nets) == 'array') if (type(a.home_nets) == 'array')
fields.home_nets = a.home_nets; fields.home_nets = a.home_nets;
let m0 = null;
let before = store.transact((c, m) => { let before = store.transact((c, m) => {
let p = m.people[a.id]; let p = m.people[a.id];
m0 = m;
core.update_person(c, m, a.id, fields); core.update_person(c, m, a.id, fields);
return p; return p;
}); });
let changes = join(', ', filter(keys(fields), (k) => k != 'note')); // "moved to Test" says more than "server".
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
if (changes) if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120); live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
// Access changes affect the nft sets and client AllowedIPs. // Access changes affect the nft sets and client AllowedIPs.
@@ -57,7 +62,7 @@ function person_update(a) {
function person_pause(a) { function person_pause(a) {
store.transact((c, m) => { store.transact((c, m) => {
if (!m.people[a.id]) if (!m.people[a.id])
die('Unknown person.'); die(_('Unknown person.'));
if (a.paused) if (a.paused)
c.set(core.CONFIG, a.id, 'paused', '1'); c.set(core.CONFIG, a.id, 'paused', '1');
else else
@@ -75,7 +80,7 @@ function person_pause(a) {
function person_regen(a) { function person_regen(a) {
let gone = store.transact((c, m) => { let gone = store.transact((c, m) => {
if (!m.people[a.id]) if (!m.people[a.id])
die('Unknown person.'); die(_('Unknown person.'));
c.set(core.CONFIG, a.id, 'code', core.new_code()); c.set(core.CONFIG, a.id, 'code', core.new_code());
c.set(core.CONFIG, a.id, 'code_set', `${time()}`); c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
let gone = []; let gone = [];
@@ -102,7 +107,7 @@ function person_links(a) {
let m = core.load(); let m = core.load();
let p = m.people[a.id]; let p = m.people[a.id];
if (!p) if (!p)
die('Unknown person.'); die(_('Unknown person.'));
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) }; return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
} }
@@ -121,7 +126,7 @@ function person_usage(a) {
let m = core.load(); let m = core.load();
let p = m.people[a.id]; let p = m.people[a.id];
if (!p) if (!p)
die('Unknown person.'); die(_('Unknown person.'));
let days = clamp_days(a.days); let days = clamp_days(a.days);
let devs = {}; let devs = {};
for (let d in p.devices) for (let d in p.devices)
@@ -140,7 +145,7 @@ function device_config(a) {
let m = core.load(); let m = core.load();
let d = m.devices[a.id]; let d = m.devices[a.id];
if (!d) if (!d)
die('Unknown device.'); die(_('Unknown device.'));
awg.mark_issued(m, d.id); awg.mark_issued(m, d.id);
return awg.client_config(m, d); return awg.client_config(m, d);
} }
@@ -156,7 +161,7 @@ export const methods = {
}, },
person_update: { person_update: {
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '', args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] }, quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
call: wrap(person_update), call: wrap(person_update),
}, },
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) }, person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
@@ -2,7 +2,7 @@
// Interfaces settings, its disguise, and removing it. // Interfaces settings, its disguise, and removing it.
import { cursor } from 'uci'; import { cursor } from 'uci';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util'; import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, rand_int, uniq, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
@@ -14,7 +14,8 @@ import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health'; import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup'; import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices'; import * as devices from 'dawnline.devices';
import { wrap, str, check_method, check_portal, tcp_taken } from 'dawnline.rpc.common'; import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
/** Server ids that would shadow a portal path. */ /** Server ids that would shadow a portal path. */
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ]; const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
@@ -27,6 +28,7 @@ const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other',
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }]. * UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
* Other servers, tunnel interfaces, programs on the router and port forwards * Other servers, tunnel interfaces, programs on the router and port forwards
* from its WAN zone. `srv` is the server being edited: its own port isn't counted. * from its WAN zone. `srv` is the server being edited: its own port isn't counted.
* `who` is shown in the admin's language ("Used by %s.").
*/ */
function udp_taken(m, srv, wan_zone) { function udp_taken(m, srv, wan_zone) {
let out = []; let out = [];
@@ -39,26 +41,26 @@ function udp_taken(m, srv, wan_zone) {
}; };
for (let id, o in m.servers) for (let id, o in m.servers)
if (id != srv?.id) if (id != srv?.id)
hold(o.port, `server “${o.name}”`); hold(o.port, sprintf(_('server “%s”'), o.name));
let nc = cursor(); let nc = cursor();
nc.load('network'); nc.load('network');
nc.foreach('network', 'interface', (s) => { nc.foreach('network', 'interface', (s) => {
if (s.listen_port && s['.name'] != srv?.ifname) if (s.listen_port && s['.name'] != srv?.ifname)
hold(+s.listen_port, `interface ${s['.name']}`); hold(+s.listen_port, sprintf(_('interface %s'), s['.name']));
}); });
let progs = health.udp_port_programs(); let progs = health.udp_port_programs();
for (let p in health.udp_bound()) for (let p in health.udp_bound())
if (p != srv?.port) if (p != srv?.port)
hold(p, progs[`${p}`] ? `${progs[`${p}`]} on this router` : 'another program on this router'); hold(p, progs[`${p}`] ? sprintf(_('%s on this router'), progs[`${p}`]) : _('another program on this router'));
for (let f in core.wan_forwards(wan_zone, 'udp')) for (let f in core.wan_forwards(wan_zone, 'udp'))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` }); push(out, { from: f.from, to: f.to, who: sprintf(_('port forward “%s”'), f.name) });
return out; return out;
} }
function check_udp_port(port, taken) { function check_udp_port(port, taken) {
for (let t in taken) for (let t in taken)
if (t.from <= port && port <= t.to) if (t.from <= port && port <= t.to)
die(`UDP ${port} is used by ${t.who}. Choose another port.`); die(sprintf(_('UDP %d is used by %s. Choose another port.'), port, t.who));
} }
/** The usual AmneziaWG port when free, otherwise a random high one. */ /** The usual AmneziaWG port when free, otherwise a random high one. */
@@ -77,8 +79,9 @@ function free_port(taken) {
} }
function free_subnet(taken) { function free_subnet(taken) {
for (let i = 0; i < 200; i++) { for (let i = 0; i < 300; i++) {
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250))); // 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
let bad = false; let bad = false;
for (let t in taken) { for (let t in taken) {
let tc = parse_cidr(t); let tc = parse_cidr(t);
@@ -164,35 +167,52 @@ function setup_defaults(a) {
let fc = cursor(); let fc = cursor();
fc.load('firewall'); fc.load('firewall');
fc.foreach('firewall', 'zone', (z) => push(zones, z.name)); fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
let host = m.settings.portal_host; let snap = net.snapshot(true);
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
let kind = health.wan_kind(wan_ip || null);
let host = m.settings.portal_host, from = host ? 'portal' : '';
if (!host) { if (!host) {
// Prefer a DDNS name, then an ACME certificate's, then the WAN address. // Prefer a DDNS name, then an ACME certificate's, then the WAN address —
// but never a private or CGNAT one: nobody on the internet reaches it.
let dc = cursor(); let dc = cursor();
if (dc.load('ddns')) if (dc.load('ddns'))
dc.foreach('ddns', 'service', (s) => { dc.foreach('ddns', 'service', (s) => {
if (!host && s.lookup_host && s.enabled == '1') if (!host && s.lookup_host && s.enabled == '1') {
host = s.lookup_host; host = s.lookup_host;
}); from = 'ddns';
if (!host)
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
if (!host)
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
} }
let wan_zone = index(zones, 'wan') >= 0 ? 'wan' : zones[1]; });
if (!host) {
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
from = host ? 'cert' : '';
}
if (!host && kind == 'public') {
host = wan_ip;
from = 'wan';
}
}
// The zones the WAN and LAN devices are in, whatever they are called.
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
let udp = udp_taken(m, null, wan_zone); let udp = udp_taken(m, null, wan_zone);
let tcp = tcp_taken(m); let tcp = tcp_taken(m);
let port = free_port(udp); let port = free_port(udp);
return { return {
id: free_server_id(m), id: free_server_id(m),
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home', // A name to start from, in the admin's language (it is theirs once saved).
name: length(m.servers) ? sprintf(_('Server %d'), length(m.servers) + 1) : _('Home'),
ifname: free_ifname(m), ifname: free_ifname(m),
port, port,
subnet: free_subnet(map(networks, (n) => n.cidr)), subnet: free_subnet(map(networks, (n) => n.cidr)),
endpoint: host, endpoint: host,
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
endpoint_from: from,
wan_kind: kind,
wan_ip: wan_ip || null,
// Automatic. // Automatic.
mtu: 0, mtu: 0,
zones, zones,
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0], lan_zone,
wan_zone, wan_zone,
// A portal already on keeps its port; a new one takes the server's number when it can. // A portal already on keeps its port; a new one takes the server's number when it can.
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp), portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
@@ -204,18 +224,34 @@ function setup_defaults(a) {
}; };
} }
/**
* Where a public address points, as the admin types it (debounced in the
* UI): the same facts Health uses, in words. `id` names the server whose WAN
* to compare with (a new one: the default WAN).
*/
function endpoint_probe(a) {
let host = str(a.host);
if (host != '' && !valid_host(host))
die(_('Public address must be a hostname or IP address.'));
let m = core.load();
let srv = m.servers[str(a.id)] ?? null;
let f = health.endpoint_facts(srv, host);
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
return { ...f, status: w.status, text: w.text };
}
/** AmneziaWG can run a server: installed, and its kernel module loads. */ /** AmneziaWG can run a server: installed, and its kernel module loads. */
function need_awg_loaded() { function need_awg_loaded() {
devices.need_awg(); devices.need_awg();
if (!awg.load().loaded) if (!awg.load().loaded)
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components."); die(_("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components."));
} }
/** An MTU as typed: '' (automatic) or 1280-1500. */ /** An MTU as typed: '' (automatic) or 1280-1500. */
function check_mtu(v) { function check_mtu(v) {
let s = str(v); let s = str(v);
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500)) if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
die('MTU must be 1280-1500.'); die(_('MTU must be 1280-1500.'));
return s; return s;
} }
@@ -227,24 +263,24 @@ function server_create(a) {
let id = str(a.id) || 'home'; let id = str(a.id) || 'home';
// A UCI section name: a dash would make uci drop it silently. // A UCI section name: a dash would make uci drop it silently.
if (!match(id, /^[a-z][a-z0-9_]{0,23}$/)) if (!match(id, /^[a-z][a-z0-9_]{0,23}$/))
die('Server ID may use lowercase letters, digits and underscores.'); die(_('Server ID may use lowercase letters, digits and underscores.'));
if (!id_free(m, id)) if (!id_free(m, id))
die(`"${id}" is already taken.`); die(sprintf(_('"%s" is already taken.'), id));
let nc = cursor(); let nc = cursor();
nc.load('network'); nc.load('network');
let ifname = str(a.ifname) || free_ifname(m); let ifname = str(a.ifname) || free_ifname(m);
if (!ifname_free(m, nc, ifname)) if (!ifname_free(m, nc, ifname))
die(`Network interface ${ifname} already exists.`); die(sprintf(_('Network interface %s already exists.'), ifname));
let udp = udp_taken(m, null, str(a.wan_zone) || 'wan'); let udp = udp_taken(m, null, str(a.wan_zone) || 'wan');
let port = free_port(udp); let port = free_port(udp);
if (a.port != null && str(a.port) != '' && str(a.port) != '0') { if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
if (!schema.valid_port(a.port)) if (!schema.valid_port(a.port))
die('UDP port must be 1-65535.'); die(_('UDP port must be 1-65535.'));
port = +str(a.port); port = +str(a.port);
} }
check_udp_port(port, udp); check_udp_port(port, udp);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu); let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
let preset = str(a.preset) || 'standard'; let preset = str(a.preset) || default_method();
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) }; let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
let pc = parse_cidr(srv.subnet); let pc = parse_cidr(srv.subnet);
if (pc) if (pc)
@@ -252,7 +288,7 @@ function server_create(a) {
// Public addresses inside the tunnel would hide the real hosts behind them. // Public addresses inside the tunnel would hide the real hosts behind them.
// New servers only: a restored backup keeps what it had. // New servers only: a restored backup keeps what it had.
if (pc && !core.private_cidr(pc)) if (pc && !core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'); die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
let taken = [ ...router_subnets ]; let taken = [ ...router_subnets ];
for (let sid, o in m.servers) for (let sid, o in m.servers)
push(taken, o.subnet); push(taken, o.subnet);
@@ -264,6 +300,8 @@ function server_create(a) {
let set = (k, v) => c.set(core.CONFIG, id, k, v); let set = (k, v) => c.set(core.CONFIG, id, k, v);
c.set(core.CONFIG, 'settings', 'settings'); c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server'); c.set(core.CONFIG, id, 'server');
if (!valid_name(str(a.name) || 'Home'))
die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(a.name) || 'Home'); set('name', str(a.name) || 'Home');
set('ifname', ifname); set('ifname', ifname);
set('port', `${port}`); set('port', `${port}`);
@@ -294,7 +332,7 @@ function server_create(a) {
c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0'); c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0');
if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') { if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') {
if (!schema.valid_port(a.portal_port)) if (!schema.valid_port(a.portal_port))
die('Portal port must be 1-65535.'); die(_('Portal port must be 1-65535.'));
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`); c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
} }
} }
@@ -359,7 +397,7 @@ function interfaces_get(a) {
let m = core.load(); let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0]; let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv) if (!srv)
die('No server yet.'); die(_('No server yet.'));
return interfaces_view(m, srv, net.snapshot(true)); return interfaces_view(m, srv, net.snapshot(true));
} }
@@ -371,12 +409,12 @@ function server_interfaces(a) {
let res = store.transact((c, m) => { let res = store.transact((c, m) => {
let srv = m.servers[a.id]; let srv = m.servers[a.id];
if (!srv) if (!srv)
die('Unknown server.'); die(_('Unknown server.'));
if (!auto_wan) { if (!auto_wan) {
if (!snap.devices[wan_dev]) if (!snap.devices[wan_dev])
die('Choose the interface that leads to the internet.'); die(_('Choose the interface that leads to the internet.'));
if (!snap.devices[wan_dev].zone) if (!snap.devices[wan_dev].zone)
die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`); die(sprintf(_('%s is not in a firewall zone, so the server port cannot be opened on it.'), wan_dev));
} }
let lans = []; let lans = [];
for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) { for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) {
@@ -385,9 +423,9 @@ function server_interfaces(a) {
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0)) if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
continue; continue;
if (snap.devices[d]?.master) if (snap.devices[d]?.master)
die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`); die(sprintf(_('%s is part of %s; choose %s instead.'), d, snap.devices[d].master, snap.devices[d].master));
if (d == (auto_wan ? snap.wan : wan_dev)) if (d == (auto_wan ? snap.wan : wan_dev))
die(`${d} is the WAN.`); die(sprintf(_('%s is the WAN.'), d));
push(lans, d); push(lans, d);
} }
lans = uniq(lans); lans = uniq(lans);
@@ -450,7 +488,7 @@ function dns_list(v) {
let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != ''); let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != '');
for (let d in list) for (let d in list)
if (!schema.ip(d)) if (!schema.ip(d))
die(`${d} is not an IP address.`); die(sprintf(_('%s is not an IP address.'), d));
return list; return list;
} }
@@ -462,21 +500,22 @@ function server_update(a) {
let srv = store.transact((c, m) => { let srv = store.transact((c, m) => {
let srv = m.servers[a.id]; let srv = m.servers[a.id];
if (!srv) if (!srv)
die('Unknown server.'); die(_('Unknown server.'));
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val); let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
if (v.name != null) { if (v.name != null) {
if (str(v.name) == '') if (!valid_name(str(v.name)))
die('Name cannot be empty.'); die(_('Server: Enter a name: up to 48 characters, without < > " or \\.'));
set('name', str(v.name)); set('name', str(v.name));
} }
// Empty = the portal's address (core.endpoint_host), as at creation.
if (v.endpoint != null) { if (v.endpoint != null) {
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint))) if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
die('Public address must be a hostname or IP address.'); die(_('Public address must be a hostname or IP address.'));
set('endpoint', str(v.endpoint)); set('endpoint', str(v.endpoint));
} }
if (v.port != null) { if (v.port != null) {
if (!schema.valid_port(v.port)) if (!schema.valid_port(v.port))
die('UDP port must be 1-65535.'); die(_('UDP port must be 1-65535.'));
let n = +str(v.port); let n = +str(v.port);
if (n != srv.port) if (n != srv.port)
check_udp_port(n, udp_taken(m, srv, srv.wan_zone)); check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
@@ -486,7 +525,7 @@ function server_update(a) {
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0'); set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
if (v.mesh != null) { if (v.mesh != null) {
if (index(core.MESH, v.mesh) < 0) if (index(core.MESH, v.mesh) < 0)
die('Unknown choice for devices reaching each other.'); die(_('Unknown choice for devices reaching each other.'));
set('mesh', v.mesh); set('mesh', v.mesh);
set('device_mesh', null); set('device_mesh', null);
} }
@@ -494,7 +533,7 @@ function server_update(a) {
set('mtu', check_mtu(v.mtu)); set('mtu', check_mtu(v.mtu));
if (v.keepalive != null) { if (v.keepalive != null) {
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600)) if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600))
die('Keep-alive must be 0-600 seconds.'); die(_('Keep-alive must be 0-600 seconds.'));
set('keepalive', str(v.keepalive)); set('keepalive', str(v.keepalive));
} }
if (v.dns != null) { if (v.dns != null) {
@@ -504,10 +543,23 @@ function server_update(a) {
else else
c.delete(core.CONFIG, srv.id, 'dns'); c.delete(core.CONFIG, srv.id, 'dns');
} }
// A new tunnel network: private, free, and every device renumbered into it.
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
let pc = parse_cidr(str(v.subnet));
if (!pc)
die(_('Subnet must look like 10.77.0.0/24.'));
if (!core.private_cidr(pc))
die(_('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.'));
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
for (let t in taken)
if (cidr_overlaps(pc, parse_cidr(t)))
die(sprintf(_('Subnet overlaps %s.'), t));
core.renumber_server(c, m, srv, cidr_str(pc));
}
return srv; return srv;
}); });
// For the log: what changed, in words. Turning on or off is its own line. // For the log: what changed, in words. Turning on or off is its own line.
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' }; let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
let what = []; let what = [];
for (let k, label in labels) { for (let k, label in labels) {
if (v[k] == null) if (v[k] == null)
@@ -529,13 +581,24 @@ function server_update(a) {
return r; return r;
} }
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
function server_ports(a) {
let m = core.load();
let srv = m.servers[a.id];
if (!srv)
die(_('Unknown server.'));
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
}
function server_obfuscation(a) { function server_obfuscation(a) {
let preset = str(a.preset) || 'standard'; let preset = str(a.preset) || default_method();
let o = awg.obf_preset(check_method(preset)); let o = awg.obf_preset(check_method(preset));
let srv = store.transact((c, m) => { let srv = store.transact((c, m) => {
let srv = m.servers[a.id]; let srv = m.servers[a.id];
if (!srv) if (!srv)
die('Unknown server.'); die(_('Unknown server.'));
for (let k in core.OBF_KEYS) for (let k in core.OBF_KEYS)
c.delete(core.CONFIG, srv.id, k); c.delete(core.CONFIG, srv.id, k);
for (let k, v in o) for (let k, v in o)
@@ -551,12 +614,12 @@ function server_obfuscation(a) {
/** Remove a server with its people, their devices and its circles (a backup is made first). */ /** Remove a server with its people, their devices and its circles (a backup is made first). */
function server_delete(a) { function server_delete(a) {
if (!core.load().servers[a.id]) if (!core.load().servers[a.id])
die('Unknown server.'); die(_('Unknown server.'));
backup.backup_create('pre-delete'); backup.backup_create('pre-delete');
let res = store.transact((c, m) => { let res = store.transact((c, m) => {
let srv = m.servers[a.id]; let srv = m.servers[a.id];
if (!srv) if (!srv)
die('Unknown server.'); die(_('Unknown server.'));
let gone = 0; let gone = 0;
for (let pid, p in m.people) for (let pid, p in m.people)
if (p.server == srv.id) { if (p.server == srv.id) {
@@ -581,6 +644,8 @@ export const methods = {
lan_like: true, portal_enabled: false, portal_port: 0 }, lan_like: true, portal_enabled: false, portal_port: 0 },
call: wrap(server_create), call: wrap(server_create),
}, },
server_ports: { args: { id: '' }, call: wrap(server_ports) },
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) }, server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
server_update: { args: { id: '', values: {} }, call: wrap(server_update) }, server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
interfaces: { args: { id: '' }, call: wrap(interfaces_get) }, interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
@@ -12,6 +12,7 @@ import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health'; import * as health from 'dawnline.health';
import * as pc from 'dawnline.portalcert'; import * as pc from 'dawnline.portalcert';
import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common'; import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
/** The portal's own checks from Health, shown next to its settings. */ /** The portal's own checks from Health, shown next to its settings. */
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ]; const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
@@ -92,7 +93,7 @@ function same(a, b) {
function settings_update(a) { function settings_update(a) {
let v = a.values ?? {}; let v = a.values ?? {};
if (type(v) != 'object') if (type(v) != 'object')
die('Nothing to save.'); die(_('Nothing to save.'));
let res = store.transact((c, m) => { let res = store.transact((c, m) => {
let restart = false; let restart = false;
c.set(core.CONFIG, 'settings', 'settings'); c.set(core.CONFIG, 'settings', 'settings');
@@ -2,6 +2,7 @@
// people, totals, map, recent activity), the activity log and traffic history. // people, totals, map, recent activity), the activity log and traffic history.
import { readfile } from 'fs'; import { readfile } from 'fs';
import { _ } from 'dawnline.i18n';
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util'; import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
@@ -11,8 +12,29 @@ import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop'; import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
import * as lookup from 'dawnline.lookup'; import * as lookup from 'dawnline.lookup';
import * as health from 'dawnline.health';
import { wrap, str, clamp_days } from 'dawnline.rpc.common'; import { wrap, str, clamp_days } from 'dawnline.rpc.common';
/** The router's public IPv4 (null when none or private). */
function wan_public(m) {
let w = lookup.router_wan(m);
return w && health.wan_kind(w) == 'public' ? w : null;
}
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
function own_addresses(m) {
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
return own;
}
/** Router location plus one point per (device, recent client address). */ /** Router location plus one point per (device, recent client address). */
function geo_view(m, usage, dmp) { function geo_view(m, usage, dmp) {
if (!m.settings.geo_enabled) if (!m.settings.geo_enabled)
@@ -84,15 +106,25 @@ function server_view(m, srv, usage, dmp, rates, days) {
online++; online++;
} }
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 }; let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
// The newest handshake from a public address that is not the router's own:
// proof that the port is reachable from the internet.
let own = own_addresses(m);
let reached = 0;
for (let id, d in m.devices)
if (m.people[d.person]?.server == srv.id)
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
if (geo.is_public(ip) && !own[ip] && ts > reached)
reached = ts;
return { return {
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled, endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns, lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
// What devices get now, by kind (mtu 0 = automatic). // What devices get now, by kind (mtu 0 = automatic).
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) }, mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0, address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
// Why the tunnel cannot run (its interface name belongs to another network section), or null. // Why the tunnel cannot run (its interface name belongs to another network section), or null.
blocked: srv.blocked ?? null, // Why it can't start, as a whole sentence in the admin's language (stored as a code).
blocked: awg.blocked_text(srv),
// Home networks (interfaces) for the per-person picker. // Home networks (interfaces) for the per-person picker.
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })), home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
peers, online, obf: srv.obf, peers, online, obf: srv.obf,
@@ -169,9 +201,12 @@ function status(a) {
like_home: loop.status(), like_home: loop.status(),
awg: awg.caps(), awg: awg.caps(),
awg_state: awg.state(), awg_state: awg.state(),
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
wan: wan_public(m),
}; };
} }
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */ /** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
function events_list(a) { function events_list(a) {
// Tunnel down/up events of older versions: the service log tells it better (names, reasons). // Tunnel down/up events of older versions: the service log tells it better (names, reasons).
@@ -188,19 +223,19 @@ function logs_clear(a) {
let f = {}; let f = {};
if (a.person) { if (a.person) {
if (!m.people[a.person]) if (!m.people[a.person])
die('Unknown person.'); die(_('Unknown person.'));
f.person = a.person; f.person = a.person;
} }
if (a.device) if (a.device)
f.device = a.device; f.device = a.device;
if (a.category) { if (a.category) {
if (index(live.CATEGORIES, a.category) < 0) if (index(live.CATEGORIES, a.category) < 0)
die('Unknown category.'); die(_('Unknown category.'));
f.category = a.category; f.category = a.category;
} }
if (a.older_days) { if (a.older_days) {
if (!match(a.older_days, /^[1-9][0-9]{0,3}$/)) if (!match(a.older_days, /^[1-9][0-9]{0,3}$/))
die('Older than must be a number of days.'); die(_('Older than must be a number of days.'));
f.before = time() - +a.older_days * 86400; f.before = time() - +a.older_days * 86400;
} }
let removed = live.clear_events(f); let removed = live.clear_events(f);
@@ -219,11 +254,11 @@ function logs_clear(a) {
function usage_clear(a) { function usage_clear(a) {
let m = core.load(); let m = core.load();
if (index([ 'all', 'person', 'device' ], a.scope) < 0) if (index([ 'all', 'person', 'device' ], a.scope) < 0)
die('Unknown scope.'); die(_('Unknown scope.'));
if (a.scope == 'person' && !m.people[a.id]) if (a.scope == 'person' && !m.people[a.id])
die('Unknown person.'); die(_('Unknown person.'));
if (a.scope == 'device' && !m.devices[a.id]) if (a.scope == 'device' && !m.devices[a.id])
die('Unknown device.'); die(_('Unknown device.'));
let req = { scope: a.scope, id: a.id, ts: time() }; let req = { scope: a.scope, id: a.id, ts: time() };
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
let l = lock('usage-reset'); let l = lock('usage-reset');
@@ -11,11 +11,14 @@ import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github'; import * as gh from 'dawnline.github';
import * as builds from 'dawnline.awg_builds'; import * as builds from 'dawnline.awg_builds';
import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs'; import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs';
import { langs } from 'dawnline.upd_app';
import * as i18n from 'dawnline.i18n';
import { _ } from 'dawnline.i18n';
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/; const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback] // check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback|:lang:<code>|:nolang]
// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages) // | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages)
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/; const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback|:lang:[a-z]{2,3}(_[A-Za-z]{2,4})?|:nolang)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
function wrap(fn) { function wrap(fn) {
return function(req) { return function(req) {
@@ -62,6 +65,8 @@ function status(a) {
policy: m.settings.updates, policy: m.settings.updates,
auto: upd.auto_state(), auto: upd.auto_state(),
kept: upd.kept_all(builds.firmware()?.postfix), kept: upd.kept_all(builds.firmware()?.postfix),
// The admin's translations installed (luci-i18n-dawnline-<lang>).
translations: langs(),
history: slice(upd.history(), 0, 12), history: slice(upd.history(), 0, 12),
tunnels: awg_tunnels(), tunnels: awg_tunnels(),
}; };
@@ -71,7 +76,7 @@ function status(a) {
function releases(a) { function releases(a) {
let page = +(a.page ?? 1); let page = +(a.page ?? 1);
if (page != int(page) || page < 1 || page > 50) if (page != int(page) || page < 1 || page > 50)
die('Unknown page.'); die(_('Unknown page.'));
return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page }; return { releases: map(gh.releases(REPO, page), (x) => ({ ...x, body: null, digests: null })), page };
} }
@@ -80,12 +85,12 @@ function notes(a) {
let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO; let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO;
let tag = a.tag ?? ''; let tag = a.tag ?? '';
if (!rp || !match(tag, TAG)) if (!rp || !match(tag, TAG))
die('Unknown release.'); die(_('Unknown release.'));
let r = gh.release(rp, tag); let r = gh.release(rp, tag);
if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v') if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v')
r = gh.release(rp, `v${tag}`); r = gh.release(rp, `v${tag}`);
if (!r) if (!r)
die(`No release ${tag} in ${rp}.`); die(sprintf(_('No release %s in %s.'), tag, rp));
return { ...r, digests: null, repo: rp }; return { ...r, digests: null, repo: rp };
} }
@@ -93,7 +98,7 @@ function notes(a) {
function changes(a) { function changes(a) {
let to = a.to ?? '', from = a.from ?? ''; let to = a.to ?? '', from = a.from ?? '';
if (!match(to, TAG) || (from != '' && !match(from, TAG))) if (!match(to, TAG) || (from != '' && !match(from, TAG)))
die('Unknown release.'); die(_('Unknown release.'));
// The installed version as a tag when it was released (a build ahead of the releases has none). // The installed version as a tag when it was released (a build ahead of the releases has none).
let base = null; let base = null;
for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : [])) for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : []))
@@ -109,18 +114,20 @@ function changes(a) {
function run(a) { function run(a) {
let what = a.what ?? 'check'; let what = a.what ?? 'check';
if (length(what) > 400 || !match(what, TARGET)) if (length(what) > 400 || !match(what, TARGET))
die('Unknown update target.'); die(_('Unknown update target.'));
// Checked here too, so a wrong name never becomes a failed job in the history. // Checked here too, so a wrong name never becomes a failed job in the history.
if (substr(what, 0, 5) == 'pkgs:') if (substr(what, 0, 5) == 'pkgs:')
for (let n in split(substr(what, 5), ',')) for (let n in split(substr(what, 5), ','))
if (index(PKG_NAMES, n) < 0) if (index(PKG_NAMES, n) < 0)
die(n == '' ? 'Unknown update target.' : `${n} is not a package Dawnline manages.`); die(n == '' ? _('Unknown update target.') : sprintf(_('%s is not a package Dawnline manages'), n));
if (upd.busy()) if (upd.busy())
die('Another component action is already running.'); die(_('Another component action is already running'));
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
let t0 = time(); let t0 = time();
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`; let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`); // The job speaks the admin's language (use() let only a plain language code through).
let lang = i18n.current();
system(`${lang ? `DAWNLINE_LANG=${lang} ` : ''}start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
for (let i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
let j = read_json(upd.JOB_FILE, null); let j = read_json(upd.JOB_FILE, null);
if (j?.state == 'running' && j.started >= t0) if (j?.state == 'running' && j.started >= t0)
@@ -6,8 +6,9 @@
// config_get_bool does, so the service and the code never disagree. // config_get_bool does, so the service and the code never disagree.
import { stat } from 'fs'; import { stat } from 'fs';
import { ip2int, valid_host } from 'dawnline.util'; import { ip2int, valid_host, ulength } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates'; import { INTERVALS, TARGETS } from 'dawnline.updates';
import { _ } from 'dawnline.i18n';
/* ---------- addresses ---------- */ /* ---------- addresses ---------- */
@@ -107,40 +108,38 @@ export function to_int(v, dflt, lo, hi) {
/* ---------- the settings section ---------- */ /* ---------- the settings section ---------- */
/* /*
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets * type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | targets
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes; * dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
* min/max: ints and text length; values: enums; msg: the error for a bad value. * min/max: ints; values: enums. The error for a bad value is in messages().
*/ */
export const SETTINGS = { export const SETTINGS = {
portal_enabled: { type: 'bool', dflt: false, restart: true }, portal_enabled: { type: 'bool', dflt: false, restart: true },
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' }, portal_host: { type: 'host', dflt: '', restart: true },
portal_alt: { type: 'hosts', dflt: [], restart: true }, portal_alt: { type: 'hosts', dflt: [], restart: true },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true, portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true },
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' }, portal_redirect: { type: 'url', dflt: '' },
portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
portal_cert: { type: 'file', dflt: '', restart: true }, portal_cert: { type: 'file', dflt: '', restart: true },
portal_key: { type: 'file', dflt: '', restart: true }, portal_key: { type: 'file', dflt: '', restart: true },
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' }, default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32 },
hostnames: { type: 'bool', dflt: true }, hostnames: { type: 'bool', dflt: true },
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' }, domain: { type: 'domain', dflt: 'lan' },
// Off until the admin turns it on: lookups send people's addresses to a third party. // Off until the admin turns it on: lookups send people's addresses to a third party.
geo_enabled: { type: 'bool', dflt: false }, geo_enabled: { type: 'bool', dflt: false },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' }, geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ] },
log_connections: { type: 'bool', dflt: true }, log_connections: { type: 'bool', dflt: true },
watchdog: { type: 'bool', dflt: true }, watchdog: { type: 'bool', dflt: true },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, msg: 'Keep activity for 0 (no age limit) to 9999 days.' }, log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999 },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' }, log_max: { type: 'int', dflt: 2000, min: 100, max: 20000 },
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' }, log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ] },
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' }, usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830 },
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' }, usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120 },
// Empty means "no fallback" (stored as 'none'); unset means the default. // Empty means "no fallback" (stored as 'none'); unset means the default.
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' }, home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1' },
update_check: { type: 'bool', dflt: true }, update_check: { type: 'bool', dflt: true },
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS), msg: 'Check every 6h, 12h, 1d or 7d.' }, update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS) },
update_auto: { type: 'bool', dflt: true }, update_auto: { type: 'bool', dflt: true },
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' }, update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ] },
update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' }, update_time: { type: 'time', dflt: '04:00' },
update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] }, update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] },
update_keep: { type: 'bool', dflt: false }, update_keep: { type: 'bool', dflt: false },
update_mirrors: { type: 'bool', dflt: true }, update_mirrors: { type: 'bool', dflt: true },
@@ -149,8 +148,30 @@ export const SETTINGS = {
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */ /** Ports the portal never takes: SSH, DNS and the LuCI web server. */
export const RESERVED_PORTS = [ 22, 53, 80, 443 ]; export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
function bad(spec, key) { /** What the admin is told about a bad value, by setting (made per call: the language changes between calls). */
die(spec.msg ?? `Invalid value for ${key}.`); function messages() {
return {
portal_host: _('Public address must be a hostname or IP address.'),
portal_alt: _('Other addresses must be hostnames or IP addresses.'),
portal_port: _('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).'),
portal_redirect: _('Redirect must be a full http:// or https:// address.'),
default_device_limit: _('Default device limit must be 1-32.'),
domain: _('Domain may use lowercase letters, digits, dashes and dots.'),
geo_provider: _('Unknown location service.'),
log_keep_days: _('Keep activity for 0 (no age limit) to 9999 days.'),
log_max: _('Log size must be 100-20000 events.'),
log_persist: _('Save the log every 10min, hourly or off.'),
usage_keep_days: _('Daily traffic history must be 7-1830 days.'),
usage_keep_months: _('Monthly traffic history must be 1-120 months.'),
home_dns_fallback: _('Fallback DNS must be an IPv4 address (or empty for none).'),
update_interval: _('Check every 6h, 12h, 1d or 7d.'),
update_mode: _('Install updates immediately or scheduled.'),
update_time: _('Enter a time as HH:MM, 00:00 to 23:59.'),
};
}
function bad(key) {
die(messages()[key] ?? sprintf(_('Invalid value for %s.'), key));
} }
/** /**
@@ -161,13 +182,17 @@ function bad(spec, key) {
export function validate(key, val) { export function validate(key, val) {
let spec = SETTINGS[key]; let spec = SETTINGS[key];
if (!spec) if (!spec)
die(`Unknown setting ${key}.`); die(sprintf(_('Unknown setting %s.'), key));
let t = spec.type; let t = spec.type;
if (t == 'hosts') { if (t == 'hosts') {
let lst = []; let lst = [];
for (let x in (type(val) == 'array' ? val : [])) for (let x in (type(val) == 'array' ? val : [])) {
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0) // A typo must not vanish on Save: refused, like the main address.
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
bad(key);
if (trim(x) != '' && index(lst, trim(x)) < 0)
push(lst, trim(x)); push(lst, trim(x));
}
return length(lst) ? lst : null; return length(lst) ? lst : null;
} }
if (t == 'targets') { if (t == 'targets') {
@@ -187,44 +212,40 @@ export function validate(key, val) {
return null; return null;
if (t == 'bool') { if (t == 'bool') {
if (val != '0' && val != '1') if (val != '0' && val != '1')
die(`${key} is 0 or 1.`); die(sprintf(_('%s is 0 or 1.'), key));
} }
else if (t == 'int') { else if (t == 'int') {
if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max) if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max)
bad(spec, key); bad(key);
val = `${+val}`; val = `${+val}`;
} }
else if (t == 'enum') { else if (t == 'enum') {
if (index(spec.values, val) < 0) if (index(spec.values, val) < 0)
bad(spec, key); bad(key);
} }
else if (t == 'host') { else if (t == 'host') {
if (!valid_host(val)) if (!valid_host(val))
bad(spec, key); bad(key);
} }
else if (t == 'url') { else if (t == 'url') {
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/)) if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
bad(spec, key); bad(key);
} }
else if (t == 'file') { else if (t == 'file') {
if (substr(val, 0, 1) != '/' || !stat(val)) if (substr(val, 0, 1) != '/' || !stat(val))
die(`${val} does not exist.`); die(sprintf(_('File %s does not exist.'), val));
} }
else if (t == 'domain') { else if (t == 'domain') {
if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/)) if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
bad(spec, key); bad(key);
} }
else if (t == 'ipv4') { else if (t == 'ipv4') {
if (!ipv4(val)) if (!ipv4(val))
bad(spec, key); bad(key);
} }
else if (t == 'time') { else if (t == 'time') {
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/)) if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
bad(spec, key); bad(key);
}
else if (t == 'text') {
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
bad(spec, key);
} }
return val; return val;
}; };
@@ -5,6 +5,7 @@
import { lock, unlock } from 'dawnline.util'; import { lock, unlock } from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import { _ } from 'dawnline.i18n';
/** Section names that are never ids of people, devices, servers, services or circles. */ /** Section names that are never ids of people, devices, servers, services or circles. */
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ]; export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
@@ -15,8 +16,11 @@ export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
* caller's change never happened, and nothing downstream may act on it. * caller's change never happened, and nothing downstream may act on it.
*/ */
export function commit(c) { export function commit(c) {
if (!c.commit(core.CONFIG)) if (!c.commit(core.CONFIG)) {
die(`Couldn't save /etc/config/dawnline: ${c.error() ?? 'the write failed'}. Is the flash full?`); let why = c.error();
die(why != null ? sprintf(_("Couldn't save /etc/config/dawnline: %s. Is the flash full?"), why)
: _("Couldn't save /etc/config/dawnline: the write failed. Is the flash full?"));
}
system('chmod 600 /etc/config/dawnline'); system('chmod 600 /etc/config/dawnline');
}; };
@@ -1,12 +1,15 @@
// Dawnline updater: Dawnline itself — check the latest release, install a // Dawnline updater: Dawnline itself — check the latest release, install a
// release (latest, a tag, the same one again) or the kept previous version. // release (latest, a tag, the same one again) or the kept previous version.
// The admin's translations installed on the router (luci-i18n-dawnline-<lang>)
// come from the same release and go in with it, in one transaction.
// ctx is the updater's job context (see usr/libexec/dawnline/updater). // ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { readfile } from 'fs'; import { readfile, lsdir } from 'fs';
import { VERSION, REPO } from 'dawnline.util'; import { VERSION, REPO } from 'dawnline.util';
import * as upd from 'dawnline.updates'; import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github'; import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg'; import * as pkg from 'dawnline.pkg';
import { _ } from 'dawnline.i18n';
function status(installed, latest) { function status(installed, latest) {
let c = upd.version_cmp(installed, latest); let c = upd.version_cmp(installed, latest);
@@ -16,12 +19,12 @@ function status(installed, latest) {
export function check(ctx) { export function check(ctx) {
let r = gh.latest(REPO); let r = gh.latest(REPO);
if (!r) if (!r)
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` }; return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: sprintf(_('Cannot reach github.com/%s'), REPO) };
let latest = replace(r.tag, /^v/, ''); let latest = replace(r.tag, /^v/, '');
let st = status(VERSION, latest); let st = status(VERSION, latest);
ctx.log(st == 'outdated' ? `Dawnline update is available: ${VERSION} → ${latest}` ctx.log(st == 'outdated' ? sprintf(_('Dawnline update is available: %s → %s'), VERSION, latest)
: st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}` : st == 'dev' ? sprintf(_('Installed Dawnline %s is newer than the release %s'), VERSION, latest)
: `Dawnline is up to date (${VERSION})`); : sprintf(_('Dawnline is up to date (%s)'), VERSION));
return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st }; return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st };
}; };
@@ -44,21 +47,51 @@ function want_sha(ctx, tag, asset, dir) {
return null; return null;
} }
/** Download a release's package, verified against its sha256. */ /** The languages of the translations installed here, by their catalogs (dawnline.<lang>.lmo). */
function fetch(ctx, tag, dir) { export function langs() {
let ver = replace(tag, /^v/, ''); let out = [];
let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`; for (let f in lsdir('/usr/lib/lua/luci/i18n') ?? []) {
ctx.phase(`Downloading ${asset}`); let m = match(f, /^dawnline\.([A-Za-z_-]+)\.lmo$/);
if (m)
push(out, m[1]);
}
return sort(out);
};
const i18n_pkg = (lang) => `luci-i18n-dawnline-${lang}`;
/**
* Download one file of a release, verified against its sha256. `optional`: a
* release without it (one from before the translations) gives null.
*/
function fetch_file(ctx, tag, asset, dir, optional) {
ctx.phase(sprintf(_('Downloading %s'), asset));
let want = want_sha(ctx, tag, asset, dir); let want = want_sha(ctx, tag, asset, dir);
if (!want && optional) {
ctx.log(sprintf(_('Release %s has no %s: it stays as it is'), tag, asset));
return null;
}
if (!want) if (!want)
die(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`); die(sprintf(_('Release %s publishes no checksum for %s: not installing an unverified package'), tag, asset));
let f = `${dir}/${asset}`; let f = `${dir}/${asset}`;
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log })) if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }))
die(`Download failed: ${asset}`); die(sprintf(_('Download failed: %s'), asset));
ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`); ctx.log(sprintf(_('sha256 matches the release (%s…)'), substr(want, 0, 12)));
return f; return f;
} }
/** A release's package and the translations installed here, verified. */
function fetch(ctx, tag, dir) {
let ver = replace(tag, /^v/, '');
let files = [ fetch_file(ctx, tag, `luci-app-dawnline-${ver}.${pkg.ext()}`, dir) ];
for (let l in langs()) {
let f = fetch_file(ctx, tag, `${i18n_pkg(l)}-${ver}.${pkg.ext()}`, dir, true);
if (f)
push(files, f);
}
return files;
}
/** The release tag of a version: tags may or may not carry the v. */ /** The release tag of a version: tags may or may not carry the v. */
function tag_of(ver) { function tag_of(ver) {
for (let t in [ `v${ver}`, ver ]) { for (let t in [ `v${ver}`, ver ]) {
@@ -72,23 +105,54 @@ function tag_of(ver) {
} }
function backup(ctx) { function backup(ctx) {
ctx.phase('Backing up configuration'); ctx.phase(_('Backing up configuration'));
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1'); system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
} }
/** arg: null (latest) | @<tag> | reinstall | rollback */ /**
* Add the translation `lang` of the installed version from its release, or
* (lang null) remove the installed ones. LuCI reads its catalogs once per web
* server process: it restarts after the job.
*/
function set_lang(ctx, lang) {
if (lang == null) {
let have = map(langs(), i18n_pkg);
if (length(have)) {
ctx.phase(_('Removing the translation'));
if (!pkg.remove(have, ctx.log))
die(_('The translation could not be removed'));
}
}
else {
let tag = tag_of(VERSION);
let f = fetch_file(ctx, tag, `${i18n_pkg(lang)}-${VERSION}.${pkg.ext()}`, ctx.work, true);
if (!f)
die(sprintf(_('Release %s has no translation into %s: install a release that has one'), tag, lang));
ctx.phase(_('Installing the translation'));
if (!pkg.install_files([ f ], false, ctx.log))
die(_('Installation failed'));
}
ctx.after('luci');
return { from: VERSION, to: VERSION, lang };
}
/** arg: null (latest) | @<tag> | reinstall | rollback | lang:<code> | nolang */
export function install(ctx, arg) { export function install(ctx, arg) {
if (arg == 'nolang')
return set_lang(ctx, null);
if (substr(arg ?? '', 0, 5) == 'lang:')
return set_lang(ctx, substr(arg, 5));
let out = { from: VERSION, to: null }; let out = { from: VERSION, to: null };
if (arg == 'rollback') { if (arg == 'rollback') {
let k = upd.kept('app'); let k = upd.kept('app');
if (!k) if (!k)
die('No previous Dawnline version is kept on the router'); die(_('No previous Dawnline version is kept on the router'));
out.to = k.version; out.to = k.version;
ctx.versions(VERSION, k.version); ctx.versions(VERSION, k.version);
backup(ctx); backup(ctx);
ctx.phase(`Rolling back to ${k.version}`); ctx.phase(sprintf(_('Rolling back to %s'), k.version));
if (!pkg.install_files(k.files, true, ctx.log)) if (!pkg.install_files(k.files, true, ctx.log))
die('Installation failed'); die(_('Installation failed'));
upd.forget('app'); upd.forget('app');
ctx.after('app'); ctx.after('app');
return out; return out;
@@ -114,25 +178,25 @@ export function install(ctx, arg) {
} }
out.to = replace(tag, /^v/, ''); out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to); ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work); let files = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps // The version being replaced, for Roll back (downloaded again: opkg keeps
// no package files). Always for an automatic run: nobody is there to // no package files). Always for an automatic run: nobody is there to
// recover a router whose new version does not come up (postupdate rolls // recover a router whose new version does not come up (postupdate rolls
// back to it on its own). // back to it on its own).
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) { if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`); ctx.phase(sprintf(_('Keeping Dawnline %s for rollback'), VERSION));
try { try {
system(`mkdir -p '${ctx.work}/keep'`); system(`mkdir -p '${ctx.work}/keep'`);
upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]); upd.keep('app', VERSION, fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`));
} }
catch (e) { catch (e) {
ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`); ctx.log(sprintf(_('Warning: could not keep %s: %s'), VERSION, e.message));
} }
} }
backup(ctx); backup(ctx);
ctx.phase('Installing package'); ctx.phase(_('Installing package'));
if (!pkg.install_files([ f ], force, ctx.log)) if (!pkg.install_files(files, force, ctx.log))
die('Installation failed'); die(_('Installation failed'));
ctx.after('app'); ctx.after('app');
return out; return out;
}; };
@@ -10,6 +10,7 @@ import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github'; import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg'; import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds'; import * as builds from 'dawnline.awg_builds';
import { _, N_ } from 'dawnline.i18n';
function sh(cmd) { function sh(cmd) {
return system(`${cmd} >/dev/null 2>&1`); return system(`${cmd} >/dev/null 2>&1`);
@@ -51,16 +52,16 @@ export function check(ctx) {
let fw = builds.firmware(); let fw = builds.firmware();
if (!fw) if (!fw)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '', return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'Cannot detect the firmware target' }; note: _('Cannot detect the firmware target') };
if (fw.snapshot) if (fw.snapshot)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '', return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only' }; note: _('This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only') };
let dir = `${ctx.work}/check`; let dir = `${ctx.work}/check`;
system(`mkdir -p '${dir}'`); system(`mkdir -p '${dir}'`);
let sources = {}; let sources = {};
for (let id in builds.ORDER) { for (let id in builds.ORDER) {
let src = builds.SOURCES[id]; let src = builds.SOURCES[id];
ctx.log(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`); ctx.log(sprintf(_('Looking for the %s build for OpenWrt %s'), src.label, substr(fw.tag, 1)));
let f = fetch(ctx, fw, 'amneziawg-tools', id, dir); let f = fetch(ctx, fw, 'amneziawg-tools', id, dir);
let v = f ? pkg.file_version(f) : null; let v = f ? pkg.file_version(f) : null;
let date = null; let date = null;
@@ -89,16 +90,16 @@ export function check(ctx) {
let mine = current ? sources[current] : null; let mine = current ? sources[current] : null;
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null; let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest'; let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
ctx.log(cur == null ? 'AmneziaWG is not installed' ctx.log(cur == null ? _('AmneziaWG is not installed')
: !current ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more` : !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
: st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}` : st == 'outdated' ? sprintf(_('AmneziaWG update is available: %s → %s'), cur, mine.version)
: `AmneziaWG is up to date (${cur})`); : sprintf(_('AmneziaWG is up to date (%s)'), cur));
return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources, return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources,
latest: mine?.version ?? null, status: st, latest: mine?.version ?? null, status: st,
update: cur == null || st == 'outdated', update: cur == null || st == 'outdated',
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic. // An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version), gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null }; note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null };
}; };
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */ /** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
@@ -112,7 +113,8 @@ function reload_module(ctx, before, after) {
if (s.proto == 'amneziawg' && s.disabled != '1') if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']); push(ifaces, s['.name']);
}); });
ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`); let n = length(ifaces);
ctx.phase(sprintf(N_(n, 'Reloading the kernel module (%d tunnel restarts)', 'Reloading the kernel module (%d tunnels restart)'), n));
for (let i in ifaces) { for (let i in ifaces) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i); iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`); sh(`ifdown '${i}'`);
@@ -121,10 +123,10 @@ function reload_module(ctx, before, after) {
// no module at all) leave every tunnel down while the job says "done". // no module at all) leave every tunnel down while the job says "done".
ctx.run('rmmod amneziawg'); ctx.run('rmmod amneziawg');
if (stat('/sys/module/amneziawg')) if (stat('/sys/module/amneziawg'))
die('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update'); die(_('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update'));
ctx.run('modprobe amneziawg'); ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg')) if (!stat('/sys/module/amneziawg'))
die("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"); die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
for (let i in ifaces) for (let i in ifaces)
sh(`ifup '${i}'`); sh(`ifup '${i}'`);
} }
@@ -132,15 +134,15 @@ function reload_module(ctx, before, after) {
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */ /** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
function settle(ctx, before, after) { function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) { if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
ctx.phase('Loading the kernel module'); ctx.phase(_('Loading the kernel module'));
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg')) if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
die("AmneziaWG is installed, but its kernel module doesn't load on this firmware"); die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
} }
else else
reload_module(ctx, before, after); reload_module(ctx, before, after);
// netifd reads its protocol handlers when it starts. // netifd reads its protocol handlers when it starts.
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) { if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
ctx.phase('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'); ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
ctx.run('/etc/init.d/network restart'); ctx.run('/etc/init.d/network restart');
} }
ctx.after('apply'); ctx.after('apply');
@@ -166,19 +168,19 @@ export function install(ctx, arg) {
let out = { from: before['amneziawg-tools'], to: null, before }; let out = { from: before['amneziawg-tools'], to: null, before };
let fw = builds.firmware(); let fw = builds.firmware();
if (!fw) if (!fw)
die('Cannot detect the firmware target'); die(_('Cannot detect the firmware target'));
if (arg == 'rollback') { if (arg == 'rollback') {
let k = upd.kept('amneziawg'); let k = upd.kept('amneziawg');
if (!k) if (!k)
die('No previous AmneziaWG build is kept on the router'); die(_('No previous AmneziaWG build is kept on the router'));
if (k.firmware && k.firmware != fw.postfix) if (k.firmware && k.firmware != fw.postfix)
die('The kept AmneziaWG build was made for another firmware: it would not load on this one'); die(_('The kept AmneziaWG build was made for another firmware: it would not load on this one'));
out.to = k.version; out.to = k.version;
out.build = k.build; out.build = k.build;
ctx.versions(out.from, out.to); ctx.versions(out.from, out.to);
ctx.phase(`Rolling back to ${k.version}`); ctx.phase(sprintf(_('Rolling back to %s'), k.version));
if (!pkg.install_files(k.files, true, ctx.log)) if (!pkg.install_files(k.files, true, ctx.log))
die('Package installation failed'); die(_('Package installation failed'));
upd.forget('amneziawg'); upd.forget('amneziawg');
out.after = builds.installed(); out.after = builds.installed();
settle(ctx, before, out.after); settle(ctx, before, out.after);
@@ -190,18 +192,18 @@ export function install(ctx, arg) {
if (id == 'auto') { if (id == 'auto') {
id = pick(fw); id = pick(fw);
if (!id) if (!id)
die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`); die(sprintf(_('No AmneziaWG build for OpenWrt %s (%s) yet'), substr(fw.tag, 1), fw.postfix));
} }
let src = builds.SOURCES[id]; let src = builds.SOURCES[id];
if (!src) if (!src)
die(`Unknown AmneziaWG build ${id}`); die(sprintf(_('Unknown AmneziaWG build %s'), id));
out.build = id; out.build = id;
let files = []; let files = [];
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) { for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
ctx.phase(`Downloading ${p} from ${src.repo}`); ctx.phase(sprintf(_('Downloading %s from %s'), p, src.repo));
let f = fetch(ctx, fw, p, id, ctx.work); let f = fetch(ctx, fw, p, id, ctx.work);
if (!f) if (!f)
die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`); die(sprintf(_('No %s build for OpenWrt %s in %s, or it could not be verified'), p, substr(fw.tag, 1), src.repo));
push(files, f); push(files, f);
} }
out.to = pkg.file_version(files[1]); out.to = pkg.file_version(files[1]);
@@ -219,19 +221,19 @@ export function install(ctx, arg) {
kept = sid; kept = sid;
} }
if (kept) { if (kept) {
ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`); ctx.phase(sprintf(_('Keeping AmneziaWG %s for rollback'), out.from));
let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x); let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x);
if (length(keepf) == length(builds.PKGS)) if (length(keepf) == length(builds.PKGS))
upd.keep('amneziawg', out.from, keepf, kept, fw.postfix); upd.keep('amneziawg', out.from, keepf, kept, fw.postfix);
} }
else else
ctx.log('Warning: the installed build is no longer published, nothing to keep for rollback'); ctx.log(_('Warning: the installed build is no longer published, nothing to keep for rollback'));
} }
ctx.phase('Refreshing package lists'); ctx.phase(_('Refreshing package lists'));
pkg.refresh(ctx.log); pkg.refresh(ctx.log);
ctx.phase(`Installing the ${src.label} build`); ctx.phase(sprintf(_('Installing the %s build'), src.label));
if (!pkg.install_files(files, true, ctx.log)) if (!pkg.install_files(files, true, ctx.log))
die('Package installation failed'); die(_('Package installation failed'));
if (!want_ru && pkg.version(builds.RU)) if (!want_ru && pkg.version(builds.RU))
pkg.remove([ builds.RU ], ctx.log); pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed(); out.after = builds.installed();
@@ -4,6 +4,7 @@
// ctx is the updater's job context (see usr/libexec/dawnline/updater). // ctx is the updater's job context (see usr/libexec/dawnline/updater).
import * as pkg from 'dawnline.pkg'; import * as pkg from 'dawnline.pkg';
import { _, N_ } from 'dawnline.i18n';
/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */ /** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */
export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ]; export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
@@ -41,7 +42,7 @@ function with_family(names, up) {
/** refresh: update the package lists first (a check by hand or on schedule). */ /** refresh: update the package lists first (a check by hand or on schedule). */
export function check(ctx, refresh) { export function check(ctx, refresh) {
if (refresh ?? true) { if (refresh ?? true) {
ctx.phase('Refreshing package lists'); ctx.phase(_('Refreshing package lists'));
pkg.refresh(); pkg.refresh();
} }
let up = pkg.upgradable(); let up = pkg.upgradable();
@@ -54,7 +55,8 @@ export function check(ctx, refresh) {
all[x] = true; all[x] = true;
} }
let n = length(keys(all)); let n = length(keys(all));
ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date'); ctx.log(n ? sprintf(N_(n, '%d package update in the feeds: %s', '%d package updates in the feeds: %s'), n, join(', ', sort(keys(all))))
: _('System packages are up to date'));
return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' }; return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' };
}; };
@@ -63,22 +65,22 @@ export function install(ctx, arg) {
let names = filter(split(arg ?? '', ','), (x) => x != ''); let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names) for (let n in names)
if (index(NAMES, n) < 0) if (index(NAMES, n) < 0)
die(`${n} is not a package Dawnline manages`); die(sprintf(_('%s is not a package Dawnline manages'), n));
if (!length(names)) if (!length(names))
die('Nothing to install'); die(_('Nothing to install'));
ctx.phase('Refreshing package lists'); ctx.phase(_('Refreshing package lists'));
pkg.refresh(ctx.log); pkg.refresh(ctx.log);
let missing = filter(names, (n) => pkg.version(n) == null); let missing = filter(names, (n) => pkg.version(n) == null);
let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable()); let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable());
if (length(have)) { if (length(have)) {
ctx.phase(`Updating ${join(', ', have)}`); ctx.phase(sprintf(_('Updating %s'), join(', ', have)));
if (!pkg.upgrade(have, ctx.log)) if (!pkg.upgrade(have, ctx.log))
die('Update failed'); die(_('Update failed'));
} }
if (length(missing)) { if (length(missing)) {
ctx.phase(`Installing ${join(', ', missing)}`); ctx.phase(sprintf(_('Installing %s'), join(', ', missing)));
if (!pkg.add(missing, ctx.log)) if (!pkg.add(missing, ctx.log))
die('Installation failed'); die(_('Installation failed'));
} }
// The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start. // The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start.
let touched = [ ...missing, ...have ]; let touched = [ ...missing, ...have ];
@@ -6,6 +6,7 @@
import { open, stat } from 'fs'; import { open, stat } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util'; import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util';
import { _ } from 'dawnline.i18n';
export const JOB_FILE = `${RUN_DIR}/update-job.json`; export const JOB_FILE = `${RUN_DIR}/update-job.json`;
export const CHECK_FILE = `${RUN_DIR}/update-check.json`; export const CHECK_FILE = `${RUN_DIR}/update-check.json`;
@@ -126,12 +127,16 @@ export function busy() {
return false; return false;
}; };
/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */ /**
* The last job; a "running" one whose worker is gone (the lock is free) reads
* as failed. Its phases, log and error are in the language of whoever started
* it (English for automatic runs); only the stopped-job error is made here.
*/
export function job() { export function job() {
let j = read_json(JOB_FILE, null); let j = read_json(JOB_FILE, null);
if (j?.state == 'running' && !busy()) { if (j?.state == 'running' && !busy()) {
j.state = 'failed'; j.state = 'failed';
j.error = 'The update stopped unexpectedly.'; j.error = _('The update stopped unexpectedly.');
j.finished = j.finished ?? time(); j.finished = j.finished ?? time();
} }
return j; return j;
@@ -3,8 +3,9 @@
// helpers work on a cursor the caller owns). // helpers work on a cursor the caller owns).
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
import { _ } from 'dawnline.i18n';
export const VERSION = '0.7.0'; export const VERSION = '0.12.1';
/** GitHub repository with Dawnline releases (updates and the installer). */ /** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline'; export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline'; export const RUN_DIR = '/var/run/dawnline';
@@ -455,38 +456,153 @@ export function in_cidr(ip, c) {
return n != null && n >= c.net && n < c.net + c.size; return n != null && n >= c.net && n < c.net + c.size;
}; };
/* ---------- text ---------- */
/** Characters in a UTF-8 string (length() counts bytes: "Мама" is 8 of them). */
export function ulength(s) {
let n = 0;
for (let i = 0; i < length(s); i++)
if ((ord(s, i) & 0xc0) != 0x80)
n++;
return n;
};
/** The first `n` characters of a UTF-8 string, never cut inside one. */
export function ucut(s, n) {
let i = 0, c = 0;
while (i < length(s)) {
if ((ord(s, i) & 0xc0) != 0x80) {
if (c == n)
break;
c++;
}
i++;
}
return substr(s, 0, i);
};
// Cyrillic (Russian, Ukrainian) to Latin: а-я by code point from U+0430, then
// ё, і, ї, є, ґ; the rest of a string passes as it is.
const CYR_A = 0x430;
const CYRILLIC = [ 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
'f', 'kh', 'ts', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya' ];
const CYRILLIC_MORE = { '1105': 'yo', '1110': 'i', '1111': 'yi', '1108': 'ye', '1169': 'g' };
/**
* Cyrillic letters written in Latin ("Мама" → "mama", "Юля" → "yulya"):
* ids, hostnames and file names are ASCII, and a person should recognise
* their own in them. Other characters are left alone.
*/
export function translit(s) {
let out = '', i = 0, n = length(s);
while (i < n) {
let b = ord(s, i);
if (b < 0x80) {
out += substr(s, i, 1);
i++;
continue;
}
let cp = 0, len = 1;
if ((b & 0xe0) == 0xc0 && i + 1 < n) {
cp = ((b & 0x1f) << 6) | (ord(s, i + 1) & 0x3f);
len = 2;
}
else if ((b & 0xf0) == 0xe0 && i + 2 < n) {
cp = ((b & 0x0f) << 12) | ((ord(s, i + 1) & 0x3f) << 6) | (ord(s, i + 2) & 0x3f);
len = 3;
}
else if ((b & 0xf8) == 0xf0 && i + 3 < n)
len = 4;
// Upper case to lower: А-Я, Ё, І, Ї, Є, Ґ.
if (cp >= 0x410 && cp <= 0x42f)
cp += 0x20;
else if (cp == 0x401)
cp = 0x451;
else if (cp == 0x406)
cp = 0x456;
else if (cp == 0x407)
cp = 0x457;
else if (cp == 0x404)
cp = 0x454;
else if (cp == 0x490)
cp = 0x491;
let t = cp >= CYR_A && cp < CYR_A + length(CYRILLIC) ? CYRILLIC[cp - CYR_A] : CYRILLIC_MORE[`${cp}`];
out += t != null ? t : substr(s, i, len);
i += len;
}
return out;
};
/* ---------- validation ---------- */ /* ---------- validation ---------- */
export function valid_slug(s) { export function valid_slug(s) {
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null; return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
}; };
/** A name people see: 1-48 characters (not bytes), none of < > " \ or control characters. */
export function valid_name(s) { export function valid_name(s) {
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null; return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
};
/** What valid_name wants, for the admin (in the admin's language). */
export function name_rule() {
return _('Enter a name: up to 48 characters, without < > " or \\.');
}; };
export function valid_key(s) { export function valid_key(s) {
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null; return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
}; };
/** An IPv6 address in its usual spelling (no zone, no brackets). */
export function is_ip6(s) {
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
};
export function valid_host(s) { export function valid_host(s) {
return type(s) == 'string' && length(s) <= 253 && return type(s) == 'string' && length(s) <= 253 &&
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null || (match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
ip2int(s) != null || match(s, /^[0-9a-fA-F:]+$/) != null); ip2int(s) != null || is_ip6(s));
}; };
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
export function valid_date(s) { export function valid_date(s) {
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null; let m = type(s) == 'string' ? match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) : null;
if (!m)
return false;
let l = localtime(timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 12, min: 0, sec: 0 }));
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
}; };
/** Turn a display name into a portal slug candidate. */ /** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
export function slugify(s) { export function slugify(s) {
let out = lc(trim(`${s ?? ''}`)); let out = lc(translit(trim(`${s ?? ''}`)));
out = replace(out, /[^a-z0-9]+/g, '-'); out = replace(out, /[^a-z0-9]+/g, '-');
out = replace(out, /^-+|-+$/g, ''); out = replace(out, /^-+|-+$/g, '');
return substr(out, 0, 32) || 'user'; return substr(out, 0, 32) || 'user';
}; };
/**
* A device's name as a DNS label ("Galaxy S24" → "galaxy-s24", "Телефон" →
* "telefon"): at most 40 characters, "device" when nothing is left.
*/
export function host_label(s) {
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
return l || 'device';
};
/**
* A server's name as a tunnel name ("Outline Home" → "Outline-Home"): the
* AmneziaWG and WireGuard apps name the tunnel after the file, and Android and
* wg-quick refuse anything but [a-zA-Z0-9_=+.-] up to 15 characters; Windows
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
*/
export function tunnel_name(s) {
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
};
/* ---------- time ---------- */ /* ---------- time ---------- */
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */ /** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
@@ -6,16 +6,21 @@ import * as live from 'dawnline.live';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
import { day_key_ago, month_key } from 'dawnline.util'; import { day_key_ago, month_key } from 'dawnline.util';
/** Daily totals (rx+tx) for the last `n` days, oldest first. */ /** Each day's [rx, tx] for the last `n` days, oldest first: the charts draw what came and what went apart. */
export function spark(rec, n) { export function spark(rec, n) {
let out = []; let out = [];
for (let i = n - 1; i >= 0; i--) { for (let i = n - 1; i >= 0; i--) {
let v = rec?.days?.[day_key_ago(i)]; let v = rec?.days?.[day_key_ago(i)];
push(out, v ? v[0] + v[1] : 0); push(out, v ? [ v[0], v[1] ] : [ 0, 0 ]);
} }
return out; return out;
}; };
/** Each day's [rx, tx] from the 1st of this month to today, oldest first (the portal's month chart). */
export function month_days(rec) {
return spark(rec, +substr(day_key_ago(0), 8, 2));
};
/** The device holds an older configuration than the one it would get now. */ /** The device holds an older configuration than the one it would get now. */
function config_stale(m, d) { function config_stale(m, d) {
m._issued ??= awg.issued(); m._issued ??= awg.issued();
@@ -23,12 +28,43 @@ function config_stale(m, d) {
return was != null && was != awg.config_fingerprint(m, d); return was != null && was != awg.config_fingerprint(m, d);
} }
/**
* The device a page request came from (`devs`: one person's device views):
* through the tunnel, by its tunnel address; outside it, the one online device
* whose tunnel comes from the request's address. The apps route the VPN's own
* address around their tunnel, and the portal shares it, so a device on the VPN
* opens the page from where its tunnel comes from. Two such devices behind one
* address (one NAT): neither.
*/
export function device_here(devs, peer) {
peer = replace(peer ?? '', /^::ffff:/, '');
if (!peer)
return null;
let near = [];
for (let d in devs) {
if (d.address == peer)
return d.id;
if (d.online && d.endpoint == peer)
push(near, d.id);
}
return length(near) == 1 ? near[0] : null;
};
export function device_view(m, d, usage, dmp) { export function device_view(m, d, usage, dmp) {
let u = usage.devices?.[d.id]; let u = usage.devices?.[d.id];
let peer = dmp.peers[d.public_key]; let peer = dmp.peers[d.public_key];
let ts = time(); let ts = time();
let hs = peer?.handshake || u?.handshake || 0; // Set up again (Reconnect): a handshake from before it does not count.
m._reconnect ??= awg.reconnects();
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
let p = m.people[d.person]; let p = m.people[d.person];
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
let label = '';
if (m.settings.hostnames && p) {
m._labels ??= {};
m._labels[p.id] ??= core.device_labels(m, p);
label = m._labels[p.id][d.id] ?? 'device';
}
let v = { let v = {
id: d.id, id: d.id,
name: d.name, name: d.name,
@@ -37,14 +73,14 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled, disabled: d.disabled,
created: d.created, created: d.created,
created_by: d.created_by, created_by: d.created_by,
online: live.online(dmp, d.id, peer), online: hs > 0 && live.online(dmp, d.id, peer),
handshake: hs, handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '', endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer, active: !!peer,
month: live.month(u), month: live.month(u),
total: u?.total ?? [ 0, 0 ], total: u?.total ?? [ 0, 0 ],
spark: spark(u, 7), spark: spark(u, 7),
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '', hostname: label ? `${label}.${p.id}.${m.settings.domain}` : '',
browser_key: d.private_key == '', browser_key: d.private_key == '',
// Its configuration changed since it was last shown or downloaded. // Its configuration changed since it was last shown or downloaded.
config_stale: config_stale(m, d), config_stale: config_stale(m, d),
@@ -1,10 +1,12 @@
// Dawnline — watchdog. The agent runs it every minute: it checks what keeps // Dawnline — watchdog. The agent runs it every minute: it checks what keeps
// people connected and repairs what it can, waiting longer after each repair // people connected and repairs what it can, waiting longer after each repair
// that did not help. What it finds goes to the service log; its state to // that did not help. What it finds goes to the service log (English, as
// RUN_DIR for the Health page. A cron job (libexec/dawnline/heartbeat) looks // logged); its state to RUN_DIR for the Health page, whose chip names are put
// after the agent itself. // in the admin's language when they are read (view()). A cron job
// (libexec/dawnline/heartbeat) looks after the agent itself.
import { stat } from 'fs'; import { stat } from 'fs';
import { _, L_ } from 'dawnline.i18n';
import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util'; import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop'; import * as loop from 'dawnline.loop';
@@ -34,8 +36,10 @@ function restart_services() {
} }
/** /**
* What to look at: { id (= the Health check id), src, name (chip), who (the log's subject), ok, * What to look at: { id (= the Health check id), src, name (chip, stored in English: view()
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> — <what>". * shows names() by id), who (the log's subject), ok,
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> - <what>"; its
* words are L_(): English in the log, translated where it is shown.
*/ */
function probes(m) { function probes(m) {
let out = []; let out = [];
@@ -43,48 +47,48 @@ function probes(m) {
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) })); push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
if (length(m.servers)) if (length(m.servers))
push(out, { push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: nft.present(), id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
problem: 'are missing', back: 'are loaded again', problem: L_('are missing'), back: L_('are loaded again'),
repair: { what: 'loading them again', run: () => apply.apply() }, repair: { what: L_('loading them again'), run: () => apply.apply() },
}); });
if (length(filter(values(m.servers), (x) => x.private_key))) { if (length(filter(values(m.servers), (x) => x.private_key))) {
let fw = apply.firewall_drift(m); let fw = apply.firewall_drift(m);
push(out, { push(out, {
id: 'fw', src: 'dawnline', name: 'Firewall', who: 'Firewall', ok: fw == null, id: 'fw', src: 'dawnline', name: 'Firewall', who: L_('Firewall'), ok: fw == null,
problem: fw == 'off' ? "isn't running on this router (fw4): tunnels and the portal are closed" problem: fw == 'off' ? L_("isn't running on this router (fw4): tunnels and the portal are closed")
: fw == 'changed' ? "rules for Dawnline were changed or removed" : "rules for Dawnline aren't loaded", : fw == 'changed' ? L_("rules for Dawnline were changed or removed") : L_("rules for Dawnline aren't loaded"),
back: 'rules for Dawnline are in place again', back: L_('rules for Dawnline are in place again'),
// fw4 stopped on purpose is the admin's call: report it, do not start it. // fw4 stopped on purpose is the admin's call: report it, do not start it.
repair: fw == 'off' ? null : { what: 'restoring them', run: () => { apply.apply(); system('fw4 -q reload'); } }, repair: fw == 'off' ? null : { what: L_('restoring them'), run: () => { apply.apply(); system('fw4 -q reload'); } },
}); });
} }
let s = m.settings; let s = m.settings;
if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port))) if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port)))
push(out, { push(out, {
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: health.tcp_listening(s.portal_port), id: 'portal', src: 'portal', name: 'Portal', who: L_('Personal portal'), ok: health.tcp_listening(s.portal_port),
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again', problem: sprintf(L_("isn't answering on port %d"), s.portal_port), back: L_('answers again'),
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"), detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
repair: { what: 'restarting it', run: restart_services }, repair: { what: L_('restarting it'), run: restart_services },
}); });
// Only while a server is on: with all of them off it idles on loopback. // Only while a server is on: with all of them off it idles on loopback.
if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key))) if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key)))
push(out, { push(out, {
id: 'resolver', src: 'dawnline', name: 'Resolver', who: 'DNS for Home-only devices', ok: loop.resolver_running(), id: 'resolver', src: 'dawnline', name: 'Resolver', who: L_('DNS for Home-only devices'), ok: loop.resolver_running(),
problem: "isn't running", back: 'runs again', problem: L_("isn't running"), back: L_('runs again'),
repair: { what: 'restarting it', run: restart_services }, repair: { what: L_('restarting it'), run: restart_services },
}); });
push(out, { push(out, {
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0, id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again', problem: L_("can't reach Dawnline (luci.dawnline is missing in rpcd)"), back: L_('reaches Dawnline again'),
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'), detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
// A reload keeps LuCI logins; a restart (second try) signs everyone out — // A reload keeps LuCI logins; a restart (second try) signs everyone out —
// and after three it stops: restarting rpcd every hour for good would // and after three it stops: restarting rpcd every hour for good would
// sign every admin out for good. // sign every admin out for good.
repair: { what: 'reloading rpcd', max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') }, repair: { what: L_('reloading rpcd'), max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
}); });
return out; return out;
} }
@@ -107,7 +111,8 @@ export function run(m) {
x.ok = p.ok; x.ok = p.ok;
if (p.ok) { if (p.ok) {
if (x.reported) if (x.reported)
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who); slog(p.src, 'up', x.stuck ? sprintf(L_('%s · restored'), p.back)
: x.tries ? sprintf(x.tries > 1 ? L_('%s (after %d repairs)') : L_('%s (after %d repair)'), p.back, x.tries) : p.back, null, p.who);
x.bad = 0; x.bad = 0;
x.next = 0; x.next = 0;
x.reported = false; x.reported = false;
@@ -128,7 +133,7 @@ export function run(m) {
if (busy) if (busy)
continue; continue;
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) { if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
slog(p.src, 'error', `${p.problem} — not repaired again (${p.repair.max} repairs didn't help)`, p.detail?.(), p.who); slog(p.src, 'error', sprintf(L_("%s - not repaired again (%d repairs didn't help)"), p.problem, p.repair.max), p.detail?.(), p.who);
x.reported = true; x.reported = true;
continue; continue;
} }
@@ -142,7 +147,7 @@ export function run(m) {
// trying quietly until it works again (that is logged). // trying quietly until it works again (that is logged).
if (x.tries >= 3 && !x.stuck && now - (x.last ?? 0) >= 50) { if (x.tries >= 3 && !x.stuck && now - (x.last ?? 0) >= 50) {
x.stuck = true; x.stuck = true;
slog(p.src, 'error', `${p.problem} — ${x.tries} repairs didn't help`, p.detail?.(), p.who); slog(p.src, 'error', sprintf(L_("%s - %d repairs didn't help"), p.problem, x.tries), p.detail?.(), p.who);
} }
if (now < x.next) if (now < x.next)
continue; continue;
@@ -151,13 +156,13 @@ export function run(m) {
x.next = now + WAIT[min(x.tries, length(WAIT) - 1)]; x.next = now + WAIT[min(x.tries, length(WAIT) - 1)];
x.reported = true; x.reported = true;
if (!x.stuck) if (!x.stuck)
slog(p.src, 'repair', `${p.problem} — ${p.repair.what}`, p.detail?.(), p.who); slog(p.src, 'repair', sprintf(L_('%s - %s'), p.problem, p.repair.what), p.detail?.(), p.who);
try { try {
p.repair.run(x.tries); p.repair.run(x.tries);
} }
catch (e) { catch (e) {
if (!x.stuck) if (!x.stuck)
slog(p.src, 'error', `couldn't be repaired: ${e.message}`, null, p.who); slog(p.src, 'error', sprintf(L_("couldn't be repaired: %s"), e.message), null, p.who);
} }
if (!x.stuck) if (!x.stuck)
push(repairs, { ts: now, id: p.id, name: p.name }); push(repairs, { ts: now, id: p.id, name: p.name });
@@ -168,18 +173,33 @@ export function run(m) {
write_json(STATE, { last: now, targets: t, repairs }, 0o644); write_json(STATE, { last: now, targets: t, repairs }, 0o644);
}; };
/** For the Health page: the watchdog's state and the newest log entries. */ /**
* The chip names of probes() by target id, in the language of the call. The
* others (AmneziaWG's, "Home · AmneziaWG") are names only and stay as stored.
*/
function names() {
return {
agent: _('Agent'), nft: _('Access rules'), fw: _('Firewall'), portal: _('Portal'),
resolver: _('Resolver'), rpc: _('LuCI link'),
};
}
/**
* For the Health page: the watchdog's state and the newest log entries. Target
* and repair names in the language of the call; the log as it was written.
*/
export function view(m) { export function view(m) {
let st = read_json(STATE, {}); let st = read_json(STATE, {});
let beat = +(read_json(BEAT, 0) ?? 0); let beat = +(read_json(BEAT, 0) ?? 0);
let n = names();
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without). // The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
let targets = [ { id: 'agent', name: 'Agent', ok: beat > 0 && time() - beat < 180, tries: 0 } ]; let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ];
for (let id, x in (type(st.targets) == 'object' ? st.targets : {})) for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
push(targets, { id, name: x.name, ok: !!x.ok, tries: x.tries ?? 0 }); push(targets, { id, name: n[id] ?? x.name, ok: !!x.ok, tries: x.tries ?? 0 });
return { return {
watchdog: { watchdog: {
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(), enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
targets, repairs: st.repairs ?? [], targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })),
}, },
log: slog_read(200), log: slog_read(200),
}; };
+1
View File
@@ -16,6 +16,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
- Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script. - Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script.
- Doc comments (`/** … */`) on every export: what it returns, including the null/empty case. - Doc comments (`/** … */`) on every export: what it returns, including the null/empty case.
- Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked. - Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked.
- Messages people read (`die()` texts, check titles and details, phases) go through `_()` / `N_()` of `dawnline.i18n`, inside functions, with `sprintf()` for values (`i18n.md`).
- nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table). - nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table).
## Cost on the router ## Cost on the router
+1 -1
View File
@@ -15,7 +15,7 @@ Match the code around you: its naming, comment density and idiom win over person
- **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it). - **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it).
- **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`. - **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`.
- **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module. - **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks. - **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks. The same goes for its strings: new text is translated in the same change, removed text leaves the catalogs (`i18n.md`).
## Logic and state ## Logic and state
+2 -2
View File
@@ -1,6 +1,6 @@
# Frontend (TypeScript: admin UI and portal) # Frontend (TypeScript: admin UI and portal)
Read with `code-standards.md` and, for anything visible, `ui-design.md`. Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`).
## Code ## Code
@@ -16,4 +16,4 @@ Read with `code-standards.md` and, for anything visible, `ui-design.md`.
## Checks ## Checks
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build`; the rebuilt bundles under `package/` are committed (CI fails otherwise). - In `web/`: `npm run format:check`, `npm run typecheck`, `npm run i18n:check`, `npm test`, `npm run build`; the rebuilt bundles under `package/` and the catalogs are committed (CI fails otherwise).
+97
View File
@@ -0,0 +1,97 @@
# Translations (admin UI, portal, backend messages)
Dawnline is written in English and translated through gettext catalogs. Russian is the first translation. Read with `frontend.md` (and `backend.md` for messages the router sends).
## The rule
- **What is added is localized in the same change.** A new page, section, control, toast, error, check or log line in the admin UI, the portal or the backend comes with its strings wrapped (`_()`, `N_()`, `plural()`, `L_()`) and translated in every `ru.po`. Not "later": CI refuses a catalog with an untranslated string.
- **What is removed leaves nothing behind.** Deleting or rewording text deletes its old entries: `npm run i18n` drops every entry no code uses any more, and `npm run i18n:check` (CI) fails while a catalog still holds one. No dead entries, no hand-kept leftovers, no commented-out translations: the catalogs follow the code, as the code follows `code-standards.md` ("Delete, don't deprecate").
- **Every change to visible text is checked in Russian too**: the wording against the glossary below, the layout at narrow widths (Russian runs longer).
## How it fits together
- **Admin UI (LuCI).** Every visible string goes through LuCI's globals `_()` and `N_()`. The catalog is `package/luci-app-dawnline/po/ru/dawnline.po`; luci.mk compiles it with po2lmo into the separate package `luci-i18n-dawnline-ru` (`/usr/lib/lua/luci/i18n/dawnline.ru.lmo`, plus the uci-defaults that adds Russian to LuCI's languages). LuCI loads it when the page language is Russian (`luci.main.lang`, or `auto` with a Russian browser). Without the package everything stays English. The LuCI menu titles (`menu.d`) are in the same catalog.
- **Portal.** Not LuCI: it carries its own catalog (`web/src/portal/i18n/ru.po`, made into a lookup table at build time and bundled into `portal.js`), so it speaks Russian on every router, with or without the admin's package. `portal/i18n.ts` installs `_()`/`N_()` with LuCI's meaning, opens in the visitor's kept choice or the browser's language, and the language menu in the breadcrumb switches it in place. The demo's own strings are in `web/src/portal/demo/i18n/`.
- **Shared code** (`web/src/shared`) runs in both and is in both catalogs.
- **Backend messages** (ucode: `die()` texts, health checks, endpoint verdicts, the updater's phases) go through `_()` / `N_()` from `dawnline.i18n` and are in the `dawnline` catalog too. The admin page sends its language with every RPC call (`lang`, added by `web/src/admin/api.ts` and stripped by `rpcd/ucode/luci.dawnline`), the updater gets it from the job's start (`DAWNLINE_LANG`), the portal's CGI from `Accept-Language` (the portal's fetch sends the visitor's choice). `dawnline.i18n` reads LuCI's catalog through `luci.core`, so the backend speaks Russian where `luci-i18n-dawnline-ru` is installed; the portal page translates what reaches it in English from `portal.uc`, `devices.uc`, `core.uc` and `awg.uc` with its own catalog. The agent's and the CLI's terminal output stay English. Text the backend stores and shows later is stored as a code (or, for service log lines, as `L_()` templates) and put into words when it is read.
- **Delivery.** The release has `luci-i18n-dawnline-ru-<version>.{ipk,apk}` next to the app. `install.sh` adds it when LuCI is in Russian (its setting, or `luci-i18n-base-ru` installed) or with `--lang ru`; the updater installs it with every Dawnline update when it is installed; Components → Dawnline → Translation adds or removes it. LuCI reads a language's catalogs once per web server process, so each of these restarts uhttpd afterwards.
- **Collecting.** `npm run i18n` (in `web/`) reads the code and rewrites the `.pot` templates and the `.po` files: new strings are added untranslated, gone ones removed, translations kept (and reused across catalogs). `npm run i18n:check` (CI) fails when a catalog is out of date, a string is untranslated, or a translation lost a placeholder. After changing visible text: run `npm run i18n`, translate the new entries in each `ru.po`, commit the catalogs with the code.
## Writing strings
- **Every visible string is wrapped**: text, buttons, headings, toasts, errors, tooltips (`title`), `aria-label`, `placeholder`, `alt`, the page title, confirm dialogs, CSV headers. Not wrapped: product and protocol names standing alone (Dawnline, AmneziaWG, WireGuard, OpenWrt, LuCI), ids, keys, paths, commands, package names, CSS classes, URLs, values sent to the router, log/event ids, `console` output.
- **Literals only.** `_('Save')`, never `_(label)` or `` _(`Hello ${name}`) ``: the extractor cannot collect them and fails. Placeholders `%s` (or `%d`) are filled with `fmt()` from `shared/i18n.ts`: `fmt(_('Removed %s'), name)`.
- **Whole sentences.** Never glue a sentence from pieces (`'Removed ' + name + ' from ' + circle`, or `_('ends') + ' ' + date`): word order and case endings differ. One msgid per sentence with placeholders. Pieces joined by separators (`PC · 10.0.0.2 · online`) are separate facts and stay separate strings.
- **Elements inside a sentence** (a link, a `<b>`): `fill(_('Install it in %s'), link)` returns the children for `E()` / `h()`. The link text is its own `_()`.
- **Counts** go through `plural(n, '%s device', '%s devices')` (number formatted, both forms literals) or `N_(n, 'Device', 'Devices')` when the number is not in the text. Never `n === 1 ? … : …` or `` `${n} devices` ``: Russian has three forms (1 устройство, 2 устройства, 5 устройств), and 21 takes the singular. Use them even where English always has the plural.
- **Numbers and dates** in the page's language: `num(n)` (2,000 / 2 000), `num(v, 1)` for one decimal, `bytes()`, `fmtDay()`, `toLocaleDateString(locale(), …)`. Never a hard-coded `'en-GB'` or `toFixed()` for shown numbers.
- **Text is made when it is drawn**, inside functions, never at module level in the portal and the shared code (the portal changes language in place; the extractor refuses it there). A table of labels becomes a function: `kindLabel(k)` in `shared/format.ts`.
- **Context** when one English word means two things: `_('Off', 'state')` vs `_('Off', 'switch')`. Use it only for real clashes.
- **Whitespace and line breaks** are not part of a msgid: no leading/trailing spaces, no double spaces, no `\n` (LuCI squeezes whitespace before the lookup; po2lmo cannot carry newlines). Put spacing in the markup or the separator.
- **Keep the English as it is** when wrapping, except to turn a glued sentence into one with placeholders.
- **Other apps' labels** (the menus of AmneziaVPN, WireGuard and AmneziaWG in set-up steps) are quoted word for word, with a context of their own (`_('Create from QR code', 'WireGuard app')`), and translated with the app's own Russian from its sources (English where the app has no Russian). Where they come from is noted in `portal/setup.ts`.
- **Messages from the router** arrive in the page's language already (admin) or are translated with `routerText()` (portal): never glue them into a sentence of the page's own; ask the backend for a whole sentence instead.
## Writing backend messages
- `import { _, N_ } from 'dawnline.i18n';` and wrap literals only: `die(_('Backup not found.'))`, `die(sprintf(_('Download failed: %s'), asset))`, `sprintf(N_(n, '%d device', '%d devices'), n)`. Placeholders `%s` and `%d` only, filled after the lookup.
- `_()` inside functions only: rpcd keeps the modules loaded and the language changes with each call (the extractor refuses module-level calls).
- Wrap what a person reads in LuCI or the portal; leave ids, status values, command lines and sentinels alone.
- Messages a portal visitor can get belong in `portal.uc` or `devices.uc` and are best static sentences: the page can translate those without the package.
- **Service log lines** (`slog()` and the watchdog's problem/back/what texts) are written once, in English, by processes with no language (the agent), and read later. Mark their words with `L_()` instead of `_()`: `slog('awg', 'up', sprintf(L_('updated · %s → %s'), a, b), null, L_('System packages'))`. `L_` returns the English; the extractor collects it into the catalog and into `web/src/admin/events/log-templates.ts`, and the admin page matches each line against those templates and translates it (`logText()` in `events/model.ts`), values and nested templates included. Keep a template's English when you touch it (lines already in logs match it), and give the Russian the agreement its subject needs; a translation may start with «:» to go on after the subject («Сервер Home: AmneziaWG не работает»).
## Russian
Write like a careful Russian product (Telegram, Яндекс), not a word-for-word translation.
- **Tone:** polite and short, «вы» in lower case. Buttons and menu items are verbs in the infinitive (perfective where it fits): «Сохранить», «Удалить», «Скопировать», «Добавить устройство», «Изменить»; «Отмена» for Cancel, «Закрыть», «Готово», «Назад», «Далее».
- **States** in forms that fit any person: «На паузе» (not «Приостановлен/а»), «Доступ закончился», «В сети» / «Не в сети». Prefer constructions without gender; when unavoidable, masculine as the neutral form.
- **Typography:** «ёлочки» for quotes, «ё» where it belongs (ещё, всё, истёк), the ellipsis character «…». No em dashes (—): where a dash is needed, a plain one with spaces ( - ), or a colon or a comma (the catalog check refuses «—»). Ranges keep the en dash (1–32, 07:00–23:00). Numbers with a space before units: «1,5 ГБ», «20 Мбит/с».
- **Units:** Б, КБ, МБ, ГБ, ТБ; бит/с, кбит/с, Мбит/с, Гбит/с; «5 мин назад», «3 ч назад», «2 дн. назад»; «2 д 5 ч», «5 ч 12 мин», «12 мин».
- **Length:** Russian runs ~20–30% longer. Keep buttons, pills, tabs and segmented controls short (abbreviate or rephrase), and check the layout in the browser at narrow widths.
- **Product and technical names stay as they are:** Dawnline, AmneziaWG, AmneziaVPN, WireGuard, OpenWrt, LuCI, GitHub, Cloudflare, Let's Encrypt, DDNS, DNS, MTU, UDP, TCP, IPv4/IPv6, NAT, CGNAT, LAN, WAN, QR-код, opkg/apk.
### Glossary
| English | Russian |
|---|---|
| server | сервер |
| person / people (the page) | человек / люди («Люди»); Add person — «Добавить человека» |
| device | устройство |
| circle | круг |
| access | доступ |
| home network | домашняя сеть |
| internet | интернет |
| home network + internet | домашняя сеть и интернет |
| portal, personal link, personal page | портал, личная ссылка, личная страница |
| invite (card) | приглашение (карточка приглашения) |
| disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная |
| data limit | лимит трафика |
| usage, traffic | трафик |
| end date; ends in 3 days | дата окончания; закончится через 3 дня |
| allowed hours; outside allowed hours | часы доступа; вне часов доступа |
| pause / resume; paused | приостановить / возобновить; на паузе |
| online / offline; last seen 12 min ago | в сети / не в сети; «В сети 12 мин назад» (not «Было в сети») |
| set up a device; setup | настроить устройство; настройка |
| app | приложение |
| key, public key, private key | ключ, публичный ключ, приватный ключ |
| configuration file (.conf) | файл конфигурации (.conf) |
| endpoint, public address | адрес сервера, публичный адрес |
| port, port forward | порт, проброс порта |
| tunnel | туннель |
| handshake | рукопожатие |
| router | роутер |
| firewall, zone | межсетевой экран, зона |
| interface, network | интерфейс, сеть |
| certificate | сертификат |
| Overview / Servers / People / Activity | Обзор / Серверы / Люди / События |
| Diagnostics / Health / Logs | Диагностика / Состояние / Журналы |
| Settings / Components / Updates | Настройки / Компоненты / Обновления |
| backup, restore | резервная копия, восстановить |
| check (health), fix | проверка, исправить |
| What's new | Что нового |
| Advanced | Дополнительно |
| watchdog | автовосстановление |
| places (map) | места |
| Copied | Скопировано |
| Undo | Отменить |
+1 -1
View File
@@ -29,4 +29,4 @@ A mock is judged against the page it will live on, so it must already look like
## Done means seen ## Done means seen
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow. Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow. Look at it in Russian too: a visible change is localized in the same change (`i18n.md`), and Russian text is longer.
+27 -9
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Build the release packages with the OpenWrt SDK in Docker (as CI does): # Build the release packages with the OpenWrt SDK in Docker (as CI does):
# scripts/build-packages.sh [ipk|apk|all] # scripts/build-packages.sh [ipk|apk|all]
# Output: dist/luci-app-dawnline-<version>.{ipk,apk} and dist/sha256sums.txt # Output: dist/luci-app-dawnline-<version>.{ipk,apk}, a translation package per
# po/<lang> (dist/luci-i18n-dawnline-<lang>-<version>.{ipk,apk}) and dist/sha256sums.txt
set -euo pipefail set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)" ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -25,13 +26,29 @@ build() {
rm -rf "$OUT/.$type" && mkdir -p "$OUT/.$type" rm -rf "$OUT/.$type" && mkdir -p "$OUT/.$type"
docker cp "$id:/builder/out/." "$OUT/.$type/" docker cp "$id:/builder/out/." "$OUT/.$type/"
docker rm "$id" >/dev/null docker rm "$id" >/dev/null
local f local f name
f="$(find "$OUT/.$type" -type f -name "*.$type" | head -n1)" for f in "$OUT/.$type"/*."$type"; do
[ -n "$f" ] || { echo "no .$type built" >&2; exit 1; } [ -f "$f" ] || continue
# ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk): one stable name for both. # ipk names use underscores (luci-app-dawnline_0.1.0-r1_all.ipk), apk names
mv "$f" "$OUT/luci-app-dawnline-$VERSION.$type" # dashes: one stable name per package for both, its name and the version.
name="$(basename "$f")"
name="${name%%[_-][0-9]*}"
mv "$f" "$OUT/$name-$VERSION.$type"
echo "$OUT/$name-$VERSION.$type"
done
rm -rf "$OUT/.$type" rm -rf "$OUT/.$type"
echo "$OUT/luci-app-dawnline-$VERSION.$type" for name in luci-app-dawnline $(i18n_packages); do
[ -f "$OUT/$name-$VERSION.$type" ] || { echo "no $name .$type built" >&2; exit 1; }
done
}
# The translation packages luci.mk makes: one per po/<lang>.
i18n_packages() {
local d
for d in "$APP"/po/*/; do
d="$(basename "$d")"
[ "$d" = templates ] || printf 'luci-i18n-dawnline-%s\n' "$d"
done
} }
case "$WHAT" in case "$WHAT" in
@@ -43,9 +60,10 @@ esac
( (
cd "$OUT" cd "$OUT"
set -- luci-app-dawnline-"$VERSION".ipk luci-app-dawnline-"$VERSION".apk
files="" files=""
for f in "$@"; do [ -f "$f" ] && files="$files $f"; done for name in luci-app-dawnline $(i18n_packages); do
for f in "$name-$VERSION".ipk "$name-$VERSION".apk; do [ -f "$f" ] && files="$files $f"; done
done
# shellcheck disable=SC2086 # shellcheck disable=SC2086
if command -v sha256sum >/dev/null; then sha256sum $files; else shasum -a 256 $files; fi > sha256sums.txt if command -v sha256sum >/dev/null; then sha256sum $files; else shasum -a 256 $files; fi > sha256sums.txt
) )
+14 -2
View File
@@ -1,7 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Build the web bundles and pack luci-app-dawnline as a filesystem overlay # Build the web bundles and pack luci-app-dawnline as a filesystem overlay
# tarball: dist/luci-app-dawnline-<version>.tar.gz (paths relative to /). # tarball: dist/luci-app-dawnline-<version>.tar.gz (paths relative to /), with
# This is the asset the in-app updater and install.sh install. # the translations as their packages lay them out (the catalogs compiled by
# web/i18n/lmo.ts, byte for byte po2lmo's, and the uci-defaults that adds the
# language to LuCI). scripts/deploy.sh installs it for development; releases
# are the .ipk/.apk packages (build-packages.sh).
set -euo pipefail set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)" ROOT="$(cd "$(dirname "$0")/.." && pwd)"
@@ -19,6 +22,15 @@ grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/pack
mkdir -p "$STAGE/www" "$OUT" mkdir -p "$STAGE/www" "$OUT"
cp -R "$APP/root/." "$STAGE/" cp -R "$APP/root/." "$STAGE/"
cp -R "$APP/htdocs/." "$STAGE/www/" cp -R "$APP/htdocs/." "$STAGE/www/"
for po in "$APP"/po/*/dawnline.po; do
l="$(basename "$(dirname "$po")")"
[ "$l" = templates ] && continue
mkdir -p "$STAGE/usr/lib/lua/luci/i18n"
node "$ROOT/web/i18n/lmo.ts" "$po" "$STAGE/usr/lib/lua/luci/i18n/dawnline.$l.lmo"
# The name LuCI lists the language by (luci.mk's LUCI_LANG.<lang>).
case "$l" in ru) name='Русский (Russian)' ;; *) name="$l" ;; esac
printf "uci set luci.languages.%s='%s'; uci commit luci\n" "$l" "$name" > "$STAGE/etc/uci-defaults/luci-i18n-dawnline-$l"
done
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \ chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \
"$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \ "$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc" "$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc"
+80 -29
View File
@@ -10,11 +10,13 @@
// //
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id] // scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
// [--mask real=shown ...] [--name real=shown ...] // [--mask real=shown ...] [--name real=shown ...]
// [--only overview,people] // [--only overview,people] [--demo]
// //
// --mask replaces text on every page before the capture (a domain, a name); // --mask replaces text on every page before the capture (a domain, a name);
// --name does the same for a person's name in any case, and for their initials. // --name does the same for a person's name in any case, and for their initials.
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x). // Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
// the router's answers are rewritten in the headless browser on their way to the page.
import { execFileSync, spawn } from 'node:child_process'; import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -22,12 +24,20 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path'; import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline'; import { createInterface } from 'node:readline';
import { demoRpc } from './screenshot-demo.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const RAW = join(ROOT, 'docs', 'screenshots', 'raw'); const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
const SCALE = 2; const SCALE = 2;
const args = { router: 'https://outline.lan', person: '', mask: [], names: [], only: [] }; const args = {
router: 'https://outline.lan',
person: '',
mask: [],
names: [],
only: [],
demo: false,
};
for (let i = 2; i < process.argv.length; i++) { for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i]; const a = process.argv[i];
const v = () => process.argv[++i] ?? die(`${a} needs a value`); const v = () => process.argv[++i] ?? die(`${a} needs a value`);
@@ -36,6 +46,7 @@ for (let i = 2; i < process.argv.length; i++) {
else if (a === '--mask') args.mask.push(v().split('=', 2)); else if (a === '--mask') args.mask.push(v().split('=', 2));
else if (a === '--name') args.names.push(v().split('=', 2)); else if (a === '--name') args.names.push(v().split('=', 2));
else if (a === '--only') args.only = v().split(','); else if (a === '--only') args.only = v().split(',');
else if (a === '--demo') args.demo = true;
else die(`unknown argument ${a}`); else die(`unknown argument ${a}`);
} }
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown'); if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
@@ -100,31 +111,26 @@ const SHOTS = [
url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`, url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`,
width: 1400, width: 1400,
ready: '.dl-grid-person .dl-row', ready: '.dl-grid-person .dl-row',
// Down to the end of Access & limits; activity rows that would be cut are hidden. // Where they connected from, on the map.
prep: `(() => {
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
b?.click();
})()`,
settle: 6000,
// Down to the end of Access & limits or of the map, whichever is lower; activity rows that would be cut are hidden.
clip: `(() => { clip: `(() => {
const c = ${column}, cut = document.querySelector('.dl-grid-person > .dl-col:last-child').getBoundingClientRect().bottom + 40; const c = ${column}, cols = document.querySelectorAll('.dl-grid-person > .dl-col');
const places = cols[0].children[2];
const cut = Math.max(cols[1].getBoundingClientRect().bottom, places ? places.getBoundingClientRect().bottom : 0) + 40;
document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => { document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => {
if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden'; if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden';
}); });
// Activity that would start right at the cut goes too, its heading with it.
const act = cols[0].children[3];
if (act && act.getBoundingClientRect().top > cut - 120) act.style.visibility = 'hidden';
return { x: c.x, y: 0, width: c.w, height: cut }; return { x: c.x, y: 0, width: c.w, height: cut };
})()`, })()`,
}, },
{
name: 'access',
url: () => `${LUCI}/server?section=access`,
width: 1400,
ready: 'section.dl-ifcard details',
// The home network card alone, its folded lists closed.
prep: `(() => {
const card = [...document.querySelectorAll('section.dl-ifcard')].find((s) => s.querySelector('details'));
card.querySelectorAll('details[open]').forEach((d) => (d.open = false));
card.setAttribute('data-shot', '');
})()`,
clip: `(() => {
const r = document.querySelector('[data-shot]').getBoundingClientRect();
return { x: r.left - 12, y: r.top - 12, width: r.width + 24, height: r.height + 24 };
})()`,
},
{ {
name: 'portal', name: 'portal',
url: (s) => s.portal, url: (s) => s.portal,
@@ -156,7 +162,17 @@ const MASK = `((pairs, inits) => {
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size)); if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
return doc.get(m); return doc.get(m);
}; };
const swap = (s) => pairs.reduce((t, [a, b]) => t.split(a).join(b), s).replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip); // IPv6 too, unless link-local or private (fe80::, fc00::/7).
const ip6 = (m) => {
if (/^(fe8|fe9|fea|feb|fc|fd)/i.test(m)) return m;
if (!doc.has(m)) doc.set(m, '2001:db8::' + (24 + doc.size));
return doc.get(m);
};
const swap = (s) =>
pairs
.reduce((t, [a, b]) => t.split(a).join(b), s)
.replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip)
.replace(/\\b(?:[0-9a-f]{1,4}:){3,7}[0-9a-f]{1,4}\\b/gi, ip6);
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
for (let n; (n = w.nextNode()); ) { for (let n; (n = w.nextNode()); ) {
const ini = inits.find(([a]) => n.nodeValue.trim() === a); const ini = inits.find(([a]) => n.nodeValue.trim() === a);
@@ -203,6 +219,7 @@ async function connect(wsUrl) {
let id = 0; let id = 0;
const pending = new Map(); const pending = new Map();
const waiters = []; const waiters = [];
const listeners = [];
ws.onmessage = (m) => { ws.onmessage = (m) => {
const msg = JSON.parse(m.data); const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) { if (msg.id && pending.has(msg.id)) {
@@ -210,6 +227,7 @@ async function connect(wsUrl) {
pending.delete(msg.id); pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result); msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) { } else if (msg.method) {
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
for (const w of waiters.filter((x) => x.method === msg.method)) { for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1); waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params); w.ok(msg.params);
@@ -222,7 +240,8 @@ async function connect(wsUrl) {
ws.send(JSON.stringify({ id, method, params })); ws.send(JSON.stringify({ id, method, params }));
}); });
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok })); const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
return { send, waitFor, close: () => ws.close() }; const on = (method, fn) => listeners.push({ method, fn });
return { send, waitFor, on, close: () => ws.close() };
} }
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms)); const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
@@ -255,10 +274,40 @@ async function main() {
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl); const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable'); await page.send('Page.enable');
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] }); await page.send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
});
// The person shown on the Person page; known once People has loaded (or from --person).
const s = { person: args.person, portal: '' };
if (args.demo) {
page.on('Fetch.requestPaused', async (e) => {
try {
const r = await page.send('Fetch.getResponseBody', {
requestId: e.requestId,
});
const body = r.base64Encoded ? Buffer.from(r.body, 'base64').toString('utf8') : r.body;
const out = demoRpc(e.request.postData ?? '', body, s.person);
await page.send('Fetch.fulfillRequest', {
requestId: e.requestId,
responseCode: e.responseStatusCode ?? 200,
responseHeaders: e.responseHeaders ?? [],
body: Buffer.from(out, 'utf8').toString('base64'),
});
} catch {
await page.send('Fetch.continueRequest', { requestId: e.requestId }).catch(() => {});
}
});
await page.send('Fetch.enable', {
patterns: [{ urlPattern: '*ubus*', requestStage: 'Response' }],
});
}
const evaluate = async (expression) => { const evaluate = async (expression) => {
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }); const r = await page.send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
});
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value; return r.result.value;
}; };
@@ -276,7 +325,12 @@ async function main() {
}; };
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything. // A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
const viewport = (width, height = 2600) => const viewport = (width, height = 2600) =>
page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: SCALE, mobile: false }); page.send('Emulation.setDeviceMetricsOverride', {
width,
height,
deviceScaleFactor: SCALE,
mobile: false,
});
await viewport(1400); await viewport(1400);
await go(`${args.router}/cgi-bin/luci/`); await go(`${args.router}/cgi-bin/luci/`);
@@ -297,13 +351,10 @@ async function main() {
} }
// The person to show (the first one on People unless --person) and their personal link. // The person to show (the first one on People unless --person) and their personal link.
const s = { person: args.person, portal: '' };
await go(`${LUCI}/server?section=people`); await go(`${LUCI}/server?section=people`);
await waitSel('.dl-srvbody a[href*="dawnline/person"]'); await waitSel('.dl-srvbody a[href*="dawnline/person"]');
if (!s.person) if (!s.person)
s.person = await evaluate( s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`,
);
s.portal = await evaluate(`L.require('rpc').then((rpc) => s.portal = await evaluate(`L.require('rpc').then((rpc) =>
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)})) rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
.then((r) => r.link ?? r.links?.[0] ?? '')`); .then((r) => r.link ?? r.links?.[0] ?? '')`);
+5
View File
@@ -20,6 +20,11 @@ ls -d /root/dawnline-predeploy-* 2>/dev/null | sort | head -n -5 | xargs -r rm -
tar -xozf /tmp/luci-app-dawnline.tar.gz -C / tar -xozf /tmp/luci-app-dawnline.tar.gz -C /
rm -f /tmp/luci-app-dawnline.tar.gz rm -f /tmp/luci-app-dawnline.tar.gz
sh /etc/uci-defaults/90_dawnline && rm -f /etc/uci-defaults/90_dawnline sh /etc/uci-defaults/90_dawnline && rm -f /etc/uci-defaults/90_dawnline
for f in /etc/uci-defaults/luci-i18n-dawnline-*; do
if [ -f "$f" ]; then sh "$f" && rm -f "$f"; fi
done
# LuCI reads a language's catalogs once per web server: the new ones need a fresh one.
/etc/init.d/uhttpd restart
sleep 1 sleep 1
ubus list luci.dawnline >/dev/null && echo "luci.dawnline registered (backup: /root/dawnline-predeploy-$ts)" ubus list luci.dawnline >/dev/null && echo "luci.dawnline registered (backup: /root/dawnline-predeploy-$ts)"
REMOTE REMOTE
+63 -34
View File
@@ -1,12 +1,16 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Put the README screenshots into a browser window on a dawn gradient. """Frame the README screenshots the way the portal draws its own surfaces.
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
are written to docs/screenshots/<name>.png at the same scale. Needs a are written to docs/screenshots/<name>.png at the same scale. Each page sits on
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
in a row in front of the page's lower edge, numbered: sheets captured alone on
a transparent page (raw/<step>.png, FLOW_MARGIN around each). Needs a
Chromium-based browser for the headless render (BROWSER=/path/to/chrome, Chromium-based browser for the headless render (BROWSER=/path/to/chrome,
default: Brave or Chrome on macOS). default: Brave or Chrome on macOS).
Run: scripts/frame-screenshots.py Run: scripts/frame-screenshots.py [name ...] (all of them when no name is given)
""" """
import os import os
import shutil import shutil
@@ -18,16 +22,18 @@ import tempfile
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw') RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
OUT = os.path.join(ROOT, 'docs', 'screenshots') OUT = os.path.join(ROOT, 'docs', 'screenshots')
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
'geist-latin-wght-normal.woff2')
# name -> what the address bar shows SHOTS = ['overview', 'people', 'person', 'portal']
SHOTS = { # name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
'overview': 'router.lan · Dawnline', # adding a device there would add one.
'people': 'router.lan · Dawnline · People', FLOWS = {
'person': 'router.lan · Dawnline · Myata', 'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
'portal': 'vpn.example.com/kamiro-telosu-bavine',
'access': 'router.lan · Dawnline · Home · Access',
} }
PAD_X, PAD_Y, BAR = 120, 96, 40 PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
STEP_GAP, STEP_OVER, STEP_PAD = 28, 150, 120 # between steps; how far they reach over the page; canvas beside them
SCALE = 2 SCALE = 2
CANDIDATES = [ CANDIDATES = [
@@ -39,26 +45,18 @@ CANDIDATES = [
] ]
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style> TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
@font-face{{font-family:Geist;src:url('file://{font}') format('woff2');font-weight:100 900}}
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}} html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
body{{display:flex;align-items:center;justify-content:center; body{{position:relative;background:#080808}}
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; .panel{{position:absolute;left:{px}px;top:{py}px;width:{pw}px;height:{ph}px;
background: border-radius:36px;background:#121212;box-shadow:inset 0 0 0 1px rgba(255,255,255,.05),0 30px 80px rgba(0,0,0,.5)}}
radial-gradient({gw}px {gh}px at 50% 118%, rgba(255,140,70,.55), rgba(255,140,70,0) 70%), .page{{position:absolute;left:{x}px;top:{y}px;width:{iw}px;height:{ih}px;display:block;border-radius:20px;
radial-gradient({gw2}px {gh2}px at 50% 100%, rgba(250,90,120,.30), rgba(250,90,120,0) 70%), box-shadow:0 0 0 1px rgba(255,255,255,.04)}}
linear-gradient(180deg,#070a14 0%,#0c1226 55%,#1a1430 100%)}} .sheet{{position:absolute;display:block;filter:drop-shadow(0 24px 48px rgba(0,0,0,.6))}}
.win{{width:{iw}px;border-radius:14px;overflow:hidden;background:#000; .n{{position:absolute;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;
box-shadow:0 0 0 1px rgba(255,255,255,.08),0 40px 120px rgba(0,0,0,.65),0 10px 30px rgba(0,0,0,.4)}} font:600 16px Geist,sans-serif;color:#ededed;background:#232323;
.bar{{height:{bar}px;background:#15171c;display:flex;align-items:center;gap:8px;padding:0 16px; box-shadow:0 0 0 1px rgba(255,255,255,.12),0 6px 16px rgba(0,0,0,.5)}}
border-bottom:1px solid rgba(255,255,255,.06);position:relative}} </style></head><body><div class="panel"></div><img class="page" src="file://{src}">{steps}</body></html>"""
.dot{{width:12px;height:12px;border-radius:50%}}
.url{{position:absolute;left:50%;transform:translateX(-50%);height:24px;padding:0 14px;border-radius:7px;
background:#0d0f13;color:#8b8f98;font-size:13px;display:flex;align-items:center;gap:6px;white-space:nowrap}}
.url svg{{width:11px;height:11px;fill:none;stroke:#8b8f98;stroke-width:2}}
img{{display:block;width:{iw}px;height:{ih}px}}
</style></head><body><div class="win"><div class="bar">
<span class="dot" style="background:#ff5f57"></span><span class="dot" style="background:#febc2e"></span><span class="dot" style="background:#28c840"></span>
<span class="url"><svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>{url}</span>
</div><img src="file://{src}"></div></body></html>"""
def png_size(path): def png_size(path):
@@ -67,22 +65,53 @@ def png_size(path):
return struct.unpack('>II', head[16:24]) return struct.unpack('>II', head[16:24])
def layout(iw, ih, flow):
"""Where the page goes and its steps in a row in front of its lower edge: (width, height, page x, page y, steps)."""
w, h = iw + 2 * (INSET + PAD_X), ih + 2 * (INSET + PAD_Y)
x, y = PAD_X + INSET, PAD_Y + INSET
if not flow:
return w, h, x, y, ''
ml, mt, mr, mb = FLOW_MARGIN
sizes = [tuple(v // SCALE for v in png_size(src)) for src in flow]
row = sum(pw - ml - mr for pw, _ in sizes) + STEP_GAP * (len(sizes) - 1)
w = max(w, row + 2 * STEP_PAD)
x = (w - iw) // 2
top = y + ih - STEP_OVER
h = top + max(ph - mt - mb for _, ph in sizes) + PAD_Y
out, sx = [], (w - row) // 2
for i, (src, (pw, ph)) in enumerate(zip(flow, sizes)):
out.append(f'<img class="sheet" src="file://{src}" style="left:{sx - ml}px;top:{top - mt}px;width:{pw}px;height:{ph}px">')
out.append(f'<span class="n" style="left:{sx - 14}px;top:{top - 14}px">{i + 1}</span>')
sx += pw - ml - mr + STEP_GAP
return w, h, x, y, ''.join(out)
def main(): def main():
browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None) browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None)
if not browser: if not browser:
sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome') sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome')
only = sys.argv[1:]
unknown = [n for n in only if n not in SHOTS]
if unknown:
sys.exit(f'unknown screenshot {", ".join(unknown)} (one of {", ".join(SHOTS)})')
tmp = tempfile.mkdtemp() tmp = tempfile.mkdtemp()
for name, url in SHOTS.items(): for name in SHOTS:
if only and name not in only:
continue
src = os.path.join(RAW, f'{name}.png') src = os.path.join(RAW, f'{name}.png')
if not os.path.exists(src): if not os.path.exists(src):
print(f'skip {name}: no raw capture') print(f'skip {name}: no raw capture')
continue continue
iw, ih = (v // SCALE for v in png_size(src)) iw, ih = (v // SCALE for v in png_size(src))
w, h = iw + 2 * PAD_X, ih + BAR + 2 * PAD_Y flow = [os.path.join(RAW, f'{step}.png') for step in FLOWS.get(name, [])]
if not all(os.path.exists(p) for p in flow):
print(f'{name}: a step is missing, the page alone')
flow = []
w, h, x, y, steps = layout(iw, ih, flow)
html = os.path.join(tmp, f'{name}.html') html = os.path.join(tmp, f'{name}.html')
with open(html, 'w', encoding='utf-8') as f: with open(html, 'w', encoding='utf-8') as f:
f.write(TEMPLATE.format(w=w, h=h, iw=iw, ih=ih, bar=BAR, url=url, src=src, f.write(TEMPLATE.format(w=w, h=h, x=x, y=y, iw=iw, ih=ih, px=x - INSET, py=y - INSET, pw=iw + 2 * INSET,
gw=int(w * .8), gh=int(h * .5), gw2=int(w * .6), gh2=int(h * .45))) ph=ih + 2 * INSET, src=src, font=FONT, steps=steps))
out = os.path.join(OUT, f'{name}.png') out = os.path.join(OUT, f'{name}.png')
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files', subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'], f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
+1 -1
View File
@@ -146,7 +146,7 @@ if methods and os.path.exists(ACL):
# Layering (rules/backend.md): util, schema → core → store → domain modules → # Layering (rules/backend.md): util, schema → core → store → domain modules →
# apply → entry points. A module importing one from a layer above it is # apply → entry points. A module importing one from a layer above it is
# reported, not failed, until the existing edges are untangled. # reported, not failed, until the existing edges are untangled.
LAYER = {'util': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5} LAYER = {'util': 0, 'i18n': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'} LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'}
notes = 0 notes = 0
for f in modules: for f in modules:
+397
View File
@@ -0,0 +1,397 @@
// Demo data for the README screenshots (scripts/capture-screenshots.mjs --demo):
// the router's own answers (luci.dawnline status, events) with a made-up cast in
// place of its people, devices, places and activity, in the states the
// screenshots should show (online, ending soon, over the limit, paused, ended,
// outside their hours). The router's ids stay, so every page keeps working; it
// is only ever read.
// The admin counts in binary units: "100 GB" is 100 GiB.
const GB = 2 ** 30;
const MIN = 60;
const HOUR = 3600;
const DAY = 86400;
/** Where the cast connects from: [lat, lon, country, cc, network]. */
const CITIES = {
Lisbon: [38.7223, -9.1393, 'Portugal', 'PT', 'MEO'],
Porto: [41.1579, -8.6291, 'Portugal', 'PT', 'NOS'],
Sintra: [38.8029, -9.3817, 'Portugal', 'PT', 'Vodafone Portugal'],
Madrid: [40.4168, -3.7038, 'Spain', 'ES', 'Telefonica de Espana'],
Barcelona: [41.3874, 2.1686, 'Spain', 'ES', 'Orange Espagne'],
Berlin: [52.52, 13.405, 'Germany', 'DE', 'Deutsche Telekom'],
Milan: [45.4642, 9.19, 'Italy', 'IT', 'TIM'],
Amsterdam: [52.3676, 4.9041, 'Netherlands', 'NL', 'KPN'],
Paris: [48.8566, 2.3522, 'France', 'FR', 'Orange'],
London: [51.5072, -0.1276, 'United Kingdom', 'GB', 'BT'],
Stockholm: [59.3293, 18.0686, 'Sweden', 'SE', 'Telia'],
};
/** The router's own place. */
const HOME = 'Lisbon';
/** Shared at home (Access): what a Home-only person can be limited to. */
const SERVICES = [
{ id: 'demo-nas', name: 'NAS', address: '10.0.1.20', ports: ['445', '5000'] },
{
id: 'demo-ha',
name: 'Home Assistant',
address: '10.0.1.30',
ports: ['8123'],
},
];
/** How busy each day of the week is, Monday first. */
const WEEK = [0.9, 1.15, 0.8, 1.05, 1.3, 0.75, 1.1];
/**
* Who the screenshots show, the --person first (the Person page), each with
* their city. A device: [name, kind, when it was last seen, GB this month,
* earlier places as 'City:days ago']; when: 'online', 'mins:N', 'hours:N',
* 'days:N', 'never', 'stale' (settings changed since), 'disabled'. Its last
* place is the person's city unless `at` names another.
*/
export const CAST = [
{
name: 'Lena Ortiz',
city: 'Lisbon',
limit: 4,
quota: 100,
used: 38.6,
note: 'Family',
devices: [
['iPhone 16', 'phone', 'online', 14.2, ['Sintra:3', 'Porto:9', 'Madrid:16']],
['MacBook Pro', 'computer', 'hours:3', 21.9, ['Berlin:12']],
['iPad Air', 'tablet', 'never', 0],
],
added: [['iPad Air', 2, 'portal']],
},
{
name: 'Marco Rossi',
city: 'Milan',
ends: 4,
devices: [
['Pixel 9', 'phone', 'online', 6.4, ['Barcelona:8']],
['ThinkPad X1', 'computer', 'days:1', 12.8],
],
},
{
name: 'Yuki Tanaka',
city: 'Amsterdam',
state: 'quota',
quota: 20,
used: 20.4,
devices: [
['Galaxy S24', 'phone', 'hours:6', 14.1, ['Paris:5']],
['Living room TV', 'other', 'stale', 6.3],
],
},
{
name: 'Sam Okafor',
city: 'London',
state: 'paused',
paused: 3,
devices: [
['Gaming PC', 'computer', 'days:9', 3.1],
['Steam Deck', 'other', 'disabled', 0],
],
},
{
name: 'Nora Lindqvist',
city: 'Stockholm',
state: 'expired',
ends: -3,
devices: [['iPhone 13 mini', 'phone', 'days:4', 1.2]],
},
{
name: 'Mia Ortiz',
city: 'Lisbon',
state: 'hours',
hours: '07:00-21:00',
limit: 1,
devices: [['Fire HD 10', 'tablet', 'hours:11', 2.6]],
},
];
const slug = (s) =>
s
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
const date = (t) => new Date(t * 1000).toISOString().slice(0, 10);
const seen = (when, now) => {
const [k, n] = when.split(':');
const v = +n || 0;
return (
{
online: now - 40,
mins: now - v * MIN,
hours: now - v * HOUR,
days: now - v * DAY,
stale: now - 2 * DAY,
disabled: now - 41 * DAY,
}[k] ?? 0
);
};
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
const week = (gb, last, now) =>
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
let ipN = 10;
/** A documentation address (the capture swaps public addresses for these anyway). */
const ip = () => `203.0.113.${ipN++}`;
const where = (city) => `${city} · ${CITIES[city][4]}`;
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
const demo = { events: [], people: new Map(), days: [], now: 0 };
/**
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
* only partly gone. Each day's [rx, tx] in bytes, rx (from the devices) about an eighth.
*/
function daily(days, gb, now) {
const month = days[days.length - 1].slice(0, 7);
const w = days.map((d, i) => {
const wd = (new Date(`${d}T12:00:00Z`).getUTCDay() + 6) % 7;
const today = i === days.length - 1 ? ((now % DAY) / DAY) * 0.9 + 0.1 : 1;
return WEEK[wd] * (0.85 + ((i * 37) % 11) / 30) * today;
});
const inMonth = w.reduce((s, x, i) => s + (days[i].startsWith(month) ? x : 0), 0) || 1;
return w.map((x) => {
const b = (x / inMonth) * gb * GB;
return [Math.round(b * 0.12), Math.round(b * 0.88)];
});
}
const usage = (days, pairs) => days.map((day, i) => ({ day, rx: pairs[i][0], tx: pairs[i][1] }));
/** The places a device was at, oldest first: [city, ts, ip]. */
function trail(c, d, hs, now) {
if (!hs) return [];
const earlier = (d[4] ?? []).map((s) => {
const [city, ago] = s.split(':');
return [city, now - +ago * DAY - 5 * HOUR, ip()];
});
return [...earlier.reverse(), [c.city, hs, ip()]];
}
function demoStatus(st, first) {
const now = st.now;
ipN = 10;
const real = [...st.people].sort((a, b) => (a.id === first ? -1 : b.id === first ? 1 : a.id < b.id ? -1 : 1));
const spare = real.flatMap((p) => p.devices);
const points = [];
const events = [];
const people = CAST.map((c, i) => {
const base = real[i] ?? {
...real[real.length - 1],
id: `demo-${i}`,
devices: [],
};
const state = c.state ?? 'active';
const devices = c.devices.map((cd, j) => {
const [name, kind, when, gb] = cd;
const tpl = base.devices[j] ?? {
...spare[j % spare.length],
id: `${base.id}-demo-${j}`,
address: `10.8.0.${200 + i * 8 + j}`,
};
const hs = when === 'never' ? 0 : seen(when, now);
const online = when === 'online' && !['paused', 'expired', 'hours'].includes(state);
const places = trail(c, cd, hs, now);
places.forEach(([city, ts, addr], k) => {
const [lat, lon, country, cc, org] = CITIES[city];
const current = online && k === places.length - 1;
points.push({
person: base.id,
device: tpl.id,
ip: addr,
ts,
online: current,
lat,
lon,
city,
country,
cc,
asn: 0,
org,
});
const ev = {
person: base.id,
device: tpl.id,
pname: c.name,
dname: name,
dkind: kind,
};
// Online now: connected a while ago (the handshake renews every few minutes); otherwise on for a couple of hours.
events.push({
...ev,
type: 'connect',
detail: addr,
where: where(city),
ts: current ? now - 95 * MIN - j * 13 * MIN : ts - 2 * HOUR,
});
if (!current) events.push({ ...ev, type: 'disconnect', ts });
});
// A phone in hand switches between Wi-Fi and mobile data.
if (online && kind === 'phone') {
const [, , addr] = places[places.length - 1];
events.push({
person: base.id,
device: tpl.id,
pname: c.name,
dname: name,
dkind: kind,
type: 'roam',
detail: `${ip()} → ${addr}`,
ts: now - 25 * MIN,
});
}
return {
...tpl,
name,
kind,
online,
active: online,
handshake: hs,
endpoint: places.length ? places[places.length - 1][2] : '',
config_stale: when === 'stale',
disabled: when === 'disabled',
month: [Math.round(gb * 0.12 * GB), Math.round(gb * 0.88 * GB)],
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
spark: week(gb, hs, now),
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
};
});
for (const [name, ago, by] of c.added ?? []) {
const d = devices.find((x) => x.name === name);
if (d)
events.push({
person: base.id,
device: d.id,
pname: c.name,
dname: name,
dkind: d.kind,
type: 'device_added',
detail: name,
by,
ts: now - ago * DAY,
});
}
if (c.paused)
events.push({
person: base.id,
pname: c.name,
type: 'paused',
by: 'admin',
ts: now - c.paused * DAY,
});
const month = devices.reduce((s, d) => [s[0] + d.month[0], s[1] + d.month[1]], [0, 0]);
const live = devices.some((d) => d.online);
demo.people.set(base.id, {
devices: devices.map((d, j) => [d.id, c.devices[j][3]]),
});
return {
...base,
name: c.name,
state,
paused: state === 'paused',
hours: c.hours ?? '',
note: c.note ?? '',
expires: c.ends !== undefined ? date(now + c.ends * DAY) : '',
device_limit: c.limit ?? Math.max(3, devices.length),
quota_gb: c.quota ?? 0,
quota_period: 'month',
quota_limit: (c.quota ?? 0) * GB,
quota_used: Math.round((c.used ?? (month[0] + month[1]) / GB) * GB),
bonus_gb: 0,
month,
total: [month[0] * 3, month[1] * 3],
online: devices.filter((d) => d.online).length,
last_seen: Math.max(0, ...devices.map((d) => d.handshake)),
rate: (base.rate ?? []).map(([t], k) => [t, live ? 12000 + ((k * 7919) % 9000) : 0, live ? 120000 + ((k * 104729) % 90000) : 0]),
devices,
};
});
const devices = people.flatMap((p) => p.devices);
const month = people.reduce((s, p) => [s[0] + p.month[0], s[1] + p.month[1]], [0, 0]);
events.sort((a, b) => a.ts - b.ts);
demo.events = events;
points.sort((a, b) => b.ts - a.ts);
demo.now = now;
demo.days = (st.series ?? []).map((x) => x.day);
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
const series = usage(demo.days, daily(demo.days, all, now));
const today = series[series.length - 1];
const [lat, lon, country, cc, org] = CITIES[HOME];
return {
...st,
people,
totals: {
...st.totals,
people: people.length,
devices: devices.length,
online: devices.filter((d) => d.online).length,
active: people.filter((p) => p.state === 'active').length,
today: [today.rx, today.tx],
month,
},
series,
servers: st.servers.map((x) => ({ ...x, series })),
services: st.services?.length ? st.services : SERVICES,
geo: st.geo && {
...st.geo,
home: { lat, lon, city: HOME, country, cc, asn: 0, org },
points,
},
events: events.slice(-60),
};
}
/**
* A ubus JSON-RPC exchange (LuCI batches calls into one request) with the
* luci.dawnline answers made into the demo; anything else as it came.
*/
export function demoRpc(request, response, first) {
let req;
let res;
try {
req = JSON.parse(request);
res = JSON.parse(response);
} catch {
return response;
}
const calls = new Map((Array.isArray(req) ? req : [req]).map((c) => [c.id, c.params ?? []]));
const fix = (r) => {
const [, object, method, args] = calls.get(r?.id) ?? [];
const data = r?.result?.[1];
if (object !== 'luci.dawnline' || !data || typeof data !== 'object') return r;
if (method === 'status' && Array.isArray(data.people)) return { ...r, result: [r.result[0], demoStatus(data, first)] };
if (method === 'person_usage' && demo.people.has(args?.id) && demo.days.length) {
const devs = demo.people.get(args.id).devices ?? [];
const per = Object.fromEntries(devs.map(([id, gb]) => [id, daily(demo.days, gb, demo.now)]));
const sum = demo.days.map((_, i) => devs.reduce((s, [id]) => [s[0] + per[id][i][0], s[1] + per[id][i][1]], [0, 0]));
const devices = Object.fromEntries(devs.map(([id]) => [id, usage(demo.days, per[id])]));
return {
...r,
result: [r.result[0], { ...data, person: usage(demo.days, sum), devices }],
};
}
// Every check passes: the screenshots show Dawnline, not this router's own setup.
if (method === 'health' && Array.isArray(data.checks))
return {
...r,
result: [
r.result[0],
{
...data,
checks: data.checks.map((c) => (c.status === 'warn' || c.status === 'error' ? { ...c, status: 'ok', problem: null } : c)),
},
],
};
if (method === 'events' && Array.isArray(data.events)) {
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
return {
...r,
result: [r.result[0], { ...data, events: mine, total: mine.length }],
};
}
return r;
};
return JSON.stringify(Array.isArray(res) ? res.map(fix) : fix(res));
}
+29 -18
View File
@@ -1,6 +1,6 @@
// dawnline.awg: disguise presets against their own validation, and the parser // dawnline.awg: disguise presets against their own validation, the parser
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 // of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP). // (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
import { readfile, writefile, unlink } from 'fs'; import { readfile, writefile, unlink } from 'fs';
import * as awg from 'dawnline.awg'; import * as awg from 'dawnline.awg';
@@ -13,27 +13,17 @@ test('obf_preset off', () => {
eq(awg.obf_errors(o), [], 'valid'); eq(awg.obf_errors(o), [], 'valid');
}); });
test('obf_preset standard and strong', () => {
for (let name in [ 'standard', 'strong' ])
for (let i = 0; i < 25; i++) {
let o = awg.obf_preset(name);
eq(awg.obf_errors(o), [], `${name} is valid`);
let jc = +o.jc, jmin = +o.jmin, jmax = +o.jmax;
ok(name == 'strong' ? jc >= 6 && jc <= 10 : jc >= 3 && jc <= 6, `${name} jc=${o.jc}`);
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `${name} junk sizes ${o.jmin}-${o.jmax}`);
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
ok(+o[k] >= 5, `${k} above the reserved values`);
eq(o.s3, null, 'no 2.0 values');
}
});
test('obf_preset balanced', () => { test('obf_preset balanced', () => {
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
let o = awg.obf_preset('balanced'); let o = awg.obf_preset('balanced');
eq(awg.obf_errors(o), [], 'balanced is valid'); eq(awg.obf_errors(o), [], 'balanced is valid');
ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`); ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`);
let jmin = +o.jmin, jmax = +o.jmax;
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `junk sizes ${o.jmin}-${o.jmax}`);
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
ok(+o[k] >= 5, `${k} above the reserved values`);
ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`); ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`);
ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets'); ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets');
eq(o.header_protection_key, null, 'no 3.1 values'); eq(o.header_protection_key, null, 'no 3.1 values');
@@ -104,3 +94,24 @@ test('dump: the tool fails', () => {
let d = awg.dump(); let d = awg.dump();
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known'); eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
}); });
test('handshake_since: Reconnect hides older handshakes', () => {
eq(awg.handshake_since(1000, null), 1000, 'never set up again');
eq(awg.handshake_since(1000, 0), 1000, 'no time');
eq(awg.handshake_since(1000, 1500), 0, 'connected before: not set up yet');
eq(awg.handshake_since(1500, 1500), 0, 'the same second does not count');
eq(awg.handshake_since(1600, 1500), 1600, 'connected after');
eq(awg.handshake_since(0, 1500), 0, 'never connected');
});
test('blocked reasons', () => {
let srv = (b) => ({ name: 'Home', blocked: b });
eq(awg.blocked_text(srv(null)), null, 'not kept down');
eq(awg.blocked_text(srv({ code: 'ifname', ifname: 'bad name' })), 'Home has an invalid interface name "bad name".', 'interface name');
eq(awg.blocked_text(srv({ code: 'taken', ifname: 'wg0' })), "Home can't use the network interface wg0: it exists and isn't Dawnline's.", 'foreign interface');
eq(awg.blocked_text(srv({ code: 'disguise', need: '3.1', installed: '2.0' })), 'Home is kept down: its disguise needs AmneziaWG 3.1 (installed: 2.0).', 'disguise');
eq(awg.blocked_text(srv({ code: 'disguise', need: '3.1' })), 'Home is kept down: its disguise needs AmneziaWG 3.1 (installed: none).', 'disguise, none installed');
// Files of older versions hold the English fragment after the name.
eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment');
eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment');
});
+28
View File
@@ -136,3 +136,31 @@ test('names and codes', () => {
for (let i = 0; i < 20; i++) for (let i = 0; i < 20; i++)
ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code'); ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code');
}); });
test('renumber_server', () => {
let srv = { id: 'main', name: 'Main', subnet: '10.9.0.0/29' };
let mm = {
servers: { main: srv, other: { id: 'other', subnet: '10.9.1.0/29' } },
people: { a: { server: 'main', devices: [ 'a1', 'a2' ] }, o: { server: 'other', devices: [ 'o1' ] } },
devices: { a1: { person: 'a', address: '10.9.0.5' }, a2: { person: 'a', address: '10.9.0.3' }, o1: { person: 'o', address: '10.9.1.2' } },
};
let set = {};
let c = { set: (cfg, s, k, v) => { set[`${s}.${k}`] = v; }, delete: () => {} };
core.renumber_server(c, mm, srv, '10.77.0.0/24');
eq(srv.subnet, '10.77.0.0/24', 'the server moves');
eq([ mm.devices.a1.address, mm.devices.a2.address ], [ '10.77.0.2', '10.77.0.3' ], 'devices renumbered lowest first');
eq(mm.devices.o1.address, '10.9.1.2', 'another server untouched');
eq(set, { 'a1.address': '10.77.0.2', 'a2.address': '10.77.0.3', 'main.subnet': '10.77.0.0/24' }, 'written to uci');
let err = null;
try { core.renumber_server(c, mm, srv, '10.9.2.0/30'); } catch (e) { err = e; }
ok(err != null, 'refuses a subnet too small for the devices');
});
test('device_labels', () => {
let mm = { devices: {
a: { id: 'a', name: 'iPhone', created: 1 }, b: { id: 'b', name: 'iPhone!', created: 2 },
c: { id: 'c', name: 'Телефон', created: 3 }, d: { id: 'd', name: 'телефон', created: 4 },
} };
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
});
+3 -2
View File
@@ -1,11 +1,12 @@
# Test fixture: a small installation (one server, two people, one device). # Test fixture: a small installation (one server, two people, one device).
# migrate.test.uc expects bob's random code, the server's stored MTU 1380 and # migrate.test.uc expects bob's random code, the server's stored MTU 1380,
# uhttpd's error_page: the one-time steps remove them. # the old portal title and uhttpd's error_page: the one-time steps remove them.
config settings 'settings' config settings 'settings'
option portal_enabled '1' option portal_enabled '1'
option portal_port '8443' option portal_port '8443'
option portal_host 'vpn.example.com' option portal_host 'vpn.example.com'
option portal_title 'My VPN'
option log_connections '0' option log_connections '0'
option update_interval '7d' option update_interval '7d'
list update_targets 'app' list update_targets 'app'
+52
View File
@@ -0,0 +1,52 @@
// dawnline.geo: which addresses need a lookup, how results go into the cache
// (bounded, never pushing out what is still shown) and the activity-log label.
import * as geo from 'dawnline.geo';
const NOW = 1790000000;
const PLACE = { lat: 45.04, lon: 38.98, city: 'Krasnodar', country: 'Russia', cc: 'RU', asn: 12389, org: 'Rostelecom' };
test('stale', () => {
let cache = { ips: {
'37.78.36.76': { ...PLACE, ts: NOW - 86400 },
'212.233.85.1': { ...PLACE, ts: NOW - 31 * 86400 },
'185.135.150.35': { fail: NOW - 3600 },
'185.135.150.28': { fail: NOW - 2 * 86400 },
'83.239.111.148': { lat: 1, lon: 2, city: 'Old', ts: NOW },
}, home: null };
eq(geo.stale(cache, [ '37.78.36.76' ], NOW), [], 'fresh: known');
eq(geo.stale(cache, [ '212.233.85.1' ], NOW), [ '212.233.85.1' ], 'older than the TTL');
eq(geo.stale(cache, [ '185.135.150.35' ], NOW), [], 'failed today: not again yet');
eq(geo.stale(cache, [ '185.135.150.28' ], NOW), [ '185.135.150.28' ], 'failed two days ago: retried');
eq(geo.stale(cache, [ '83.239.111.148' ], NOW), [ '83.239.111.148' ], 'an entry from before ASNs were kept');
eq(geo.stale(cache, [ '10.0.1.164', '100.64.1.1', '', null, 'fe80::1' ], NOW), [], 'local addresses never');
eq(geo.stale(cache, [ '1.1.1.1', '8.8.8.8', '1.1.1.1' ], NOW), [ '1.1.1.1', '8.8.8.8' ], 'once each, in order');
});
test('merge', () => {
let cache = { ips: {}, home: null };
ok(geo.merge(cache, { '1.1.1.1': { ...PLACE }, '8.8.8.8': false }, [], NOW), 'changed');
eq(cache.ips['1.1.1.1'], { ...PLACE, ts: NOW }, 'a place, stamped');
eq(cache.ips['8.8.8.8'], { fail: NOW }, 'nothing found: a failure, retried later');
ok(!geo.merge(cache, {}, [], NOW), 'no results: unchanged');
ok(!geo.merge(cache, { '10.0.0.1': PLACE }, [], NOW) && !cache.ips['10.0.0.1'], 'a local address is not kept');
eq(geo.place(cache, '1.1.1.1')?.city, 'Krasnodar', 'place');
eq(geo.place(cache, '8.8.8.8'), null, 'no place for a failure');
});
test('merge keeps the cache bounded, what is shown stays', () => {
let cache = { ips: {}, home: null };
for (let i = 0; i < 500; i++)
cache.ips[`1.0.${int(i / 250)}.${i % 250 + 1}`] = { ...PLACE, ts: NOW - 1000 + i };
let oldest = '1.0.0.1', second = '1.0.0.2';
ok(geo.merge(cache, { '9.9.9.9': PLACE }, [ oldest ], NOW), 'changed');
eq(length(keys(cache.ips)), 500, 'back to the cap');
ok(cache.ips[oldest] != null, 'the oldest is still shown: kept');
ok(cache.ips[second] == null, 'the oldest not shown went');
ok(cache.ips['9.9.9.9'] != null, 'the new one is in');
});
test('label', () => {
eq(geo.label(PLACE), 'Krasnodar · Rostelecom', 'city and ISP');
eq(geo.label({ city: '', org: 'Rostelecom' }), 'Rostelecom', 'no city');
eq(geo.label(null), null, 'no place');
});
+20
View File
@@ -0,0 +1,20 @@
// dawnline.i18n: without LuCI's catalogs (this rootfs has no luci-base) every
// message stays English, whatever language is asked for; plural forms pick
// by the count.
import * as i18n from 'dawnline.i18n';
test('English without a catalog', () => {
i18n.use('ru');
eq(i18n.current(), null, 'no Russian catalog here');
eq(i18n._('Backup not found.'), 'Backup not found.', 'as written');
eq(sprintf(i18n.N_(1, '%d device', '%d devices'), 1), '1 device', 'singular');
eq(sprintf(i18n.N_(5, '%d device', '%d devices'), 5), '5 devices', 'plural');
eq(i18n.N_(0, 'a', 'b'), 'b', 'zero takes the plural in English');
});
test('only plain language codes', () => {
for (let l in [ null, '', 'en', 'ru; rm -rf /', '../../etc', 'russian', 42 ]) {
i18n.use(l);
eq(i18n.current(), null, `${l}`);
}
});
+18
View File
@@ -48,3 +48,21 @@ test('endpoint_ip', () => {
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6'); eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
eq(live.endpoint_ip(''), '', 'none'); eq(live.endpoint_ip(''), '', 'none');
}); });
// A connect is logged before its new address is located; the place comes later.
test('fill_places', () => {
let ev = [
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 100 },
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 200 },
{ type: 'disconnect', detail: null, ts: 210 },
{ type: 'connect', detail: '8.8.8.8', where: 'Mountain View · Google', ts: 220 },
{ type: 'connect', detail: '9.9.9.9', where: null, ts: 230 },
];
ok(live.fill_places(ev, { '1.1.1.1': 'Sydney · Cloudflare', '8.8.8.8': 'Elsewhere' }, 150), 'changed');
eq(ev[1].where, 'Sydney · Cloudflare', 'the waiting connect gets its place');
eq(ev[0].where, null, 'older than `since`: left alone');
eq(ev[3].where, 'Mountain View · Google', 'a place already there stays');
eq(ev[4].where, null, 'another address');
ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged');
ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log');
});
+12
View File
@@ -0,0 +1,12 @@
// dawnline.loop: the "like a home device" link's errors, stored as codes and
// put into words when read.
import * as loop from 'dawnline.loop';
test('error_text', () => {
eq(loop.error_text(null), null, 'no error');
eq(loop.error_text({ code: 'no_lan' }), 'No LAN detected.', 'no LAN');
eq(loop.error_text({ code: 'not_bridge', dev: 'eth1' }), 'eth1 is not a bridge, so Dawnline cannot join the LAN as a device.', 'not a bridge');
eq(loop.error_text({ code: 'no_address', net: 'lan' }), 'No free address on lan.', 'no address');
eq(loop.error_text({ code: 'setup', detail: 'ip: RTNETLINK answers: File exists' }), 'Setup failed: ip: RTNETLINK answers: File exists', 'setup');
eq(loop.error_text('an old message'), 'an old message', 'older files: as written');
});
+2
View File
@@ -16,6 +16,7 @@ test('before: the fixture holds the old state', () => {
let c = conf('dawnline'); let c = conf('dawnline');
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code'); eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU'); eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
eq(c.get('dawnline', 'settings', 'portal_title'), 'My VPN', 'a portal title');
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page'); eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
}); });
@@ -27,6 +28,7 @@ test('run: the steps change what they must', () => {
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic'); eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays'); eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443'); eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
eq(c.get('dawnline', 'settings', 'portal_title'), null, 'no portal title');
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone'); eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays'); eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false, eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
+3 -11
View File
@@ -34,8 +34,9 @@ test('validate: host and hosts', () => {
eq(schema.validate('portal_host', 'vpn.example.com'), 'vpn.example.com', 'name'); eq(schema.validate('portal_host', 'vpn.example.com'), 'vpn.example.com', 'name');
eq(schema.validate('portal_host', '203.0.113.7'), '203.0.113.7', 'address'); eq(schema.validate('portal_host', '203.0.113.7'), '203.0.113.7', 'address');
throws(() => schema.validate('portal_host', 'bad host!'), /hostname or IP/, 'bad'); throws(() => schema.validate('portal_host', 'bad host!'), /hostname or IP/, 'bad');
eq(schema.validate('portal_alt', [ 'a.example.com', ' a.example.com ', 'bad host', 'b.example.com' ]), eq(schema.validate('portal_alt', [ 'a.example.com', ' a.example.com ', '', 'b.example.com' ]),
[ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, bad ones dropped'); [ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, empty ones dropped');
throws(() => schema.validate('portal_alt', [ 'a.example.com', 'bad host' ]), /hostnames or IP/, 'a typo is refused, not dropped');
eq(schema.validate('portal_alt', []), null, 'empty list removes the option'); eq(schema.validate('portal_alt', []), null, 'empty list removes the option');
eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list'); eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list');
}); });
@@ -76,13 +77,6 @@ test('validate: time', () => {
throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60'); throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60');
}); });
test('validate: text', () => {
eq(schema.validate('portal_title', 'My VPN'), 'My VPN', 'plain');
eq(schema.validate('portal_title', replace(sprintf('%64s', ''), ' ', 'a')), replace(sprintf('%64s', ''), ' ', 'a'), '64 characters');
throws(() => schema.validate('portal_title', replace(sprintf('%65s', ''), ' ', 'a')), /64 characters/, '65 characters');
throws(() => schema.validate('portal_title', 'a\nb'), /64 characters/, 'control character');
});
test('validate: targets', () => { test('validate: targets', () => {
eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once'); eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once');
eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice'); eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice');
@@ -109,8 +103,6 @@ test('get', () => {
eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty'); eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty');
eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4'); eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4');
eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4'); eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4');
eq(schema.get({}, 'portal_title'), 'Dawnline', 'missing text');
eq(schema.get({ portal_title: '' }, 'portal_title'), 'Dawnline', 'empty text');
eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through'); eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through');
eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value'); eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value');
eq(schema.get(null, 'portal_port'), 8443, 'no section'); eq(schema.get(null, 'portal_port'), 8443, 'no section');
+31 -3
View File
@@ -8,8 +8,10 @@ test('valid_name', () => {
ok(!util.valid_name(' '), 'blank'); ok(!util.valid_name(' '), 'blank');
ok(!util.valid_name(null), 'null'); ok(!util.valid_name(null), 'null');
ok(!util.valid_name(42), 'number'); ok(!util.valid_name(42), 'number');
ok(util.valid_name('a' + replace(sprintf('%47s', ''), ' ', 'b')), '48 bytes'); ok(util.valid_name('a' + replace(sprintf('%47s', ''), ' ', 'b')), '48 characters');
ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 bytes'); ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 characters');
ok(util.valid_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧ'), '25 Cyrillic letters (50 bytes) are 25 characters');
ok(!util.valid_name('Bob "B"'), 'quotes');
ok(!util.valid_name('a<b'), 'angle bracket'); ok(!util.valid_name('a<b'), 'angle bracket');
ok(!util.valid_name('a"b'), 'quote'); ok(!util.valid_name('a"b'), 'quote');
ok(!util.valid_name('a\\b'), 'backslash'); ok(!util.valid_name('a\\b'), 'backslash');
@@ -96,7 +98,9 @@ test('slugify', () => {
eq(util.slugify(' --Bob!! '), 'bob', 'trimmed dashes'); eq(util.slugify(' --Bob!! '), 'bob', 'trimmed dashes');
eq(util.slugify(''), 'user', 'empty'); eq(util.slugify(''), 'user', 'empty');
eq(util.slugify(null), 'user', 'null'); eq(util.slugify(null), 'user', 'null');
eq(util.slugify('Мама'), 'user', 'nothing left'); eq(util.slugify('Мама'), 'mama', 'Cyrillic written in Latin');
eq(util.slugify('Юля Щукина'), 'yulya-shchukina', 'Cyrillic words');
eq(util.slugify('日本'), 'user', 'nothing left');
eq(length(util.slugify(replace(sprintf('%40s', ''), ' ', 'x'))), 32, 'cut at 32'); eq(length(util.slugify(replace(sprintf('%40s', ''), ' ', 'x'))), 32, 'cut at 32');
}); });
@@ -112,3 +116,27 @@ test('dates', () => {
eq(util.day_key_ago(0, noon), '2026-03-01', 'zero days'); eq(util.day_key_ago(0, noon), '2026-03-01', 'zero days');
eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq'); eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq');
}); });
test('text: ulength, ucut, translit, host_label, tunnel_name', () => {
eq(util.ulength('Мама'), 4, 'characters, not bytes');
eq(util.ulength('abc'), 3, 'ascii');
eq(util.ucut('Привет', 3), 'При', 'cut by characters');
eq(util.ucut('ab', 5), 'ab', 'shorter than the cut');
eq(util.translit('Мама Таня'), 'mama tanya', 'Russian');
eq(util.translit('Їжак Ґава ёж'), 'yizhak gava yozh', 'Ukrainian letters and ё');
eq(util.translit('Mixed Текст 1'), 'Mixed tekst 1', 'Latin and digits pass');
eq(util.host_label('Galaxy S24'), 'galaxy-s24', 'label');
eq(util.host_label('Телефон Ёжика'), 'telefon-yozhika', 'Cyrillic label');
eq(util.tunnel_name('Outline Home'), 'Outline-Home', 'tunnel name keeps the case');
eq(util.tunnel_name('Дом у моря'), 'dom-u-morya', 'Cyrillic tunnel name');
eq(util.tunnel_name(' My VPN (home)! '), 'My-VPN-home', 'tunnel name: runs of other characters are one dash');
eq(util.tunnel_name('A very long server name'), 'A-very-long-ser', 'tunnel name: 15 characters at most');
eq(util.tunnel_name('Home server 12345'), 'Home-server-123', 'tunnel name: cut');
eq(util.tunnel_name('Lakeside house x'), 'Lakeside-house', 'tunnel name: no dash left at the cut');
eq(util.tunnel_name('nul'), 'dawnline', 'tunnel name: a Windows device name');
eq(util.tunnel_name('COM1'), 'dawnline', 'tunnel name: a Windows device name, any case');
eq(util.tunnel_name('???'), 'dawnline', 'tunnel name: nothing left');
eq(util.tunnel_name(null), 'dawnline', 'tunnel name: null');
eq(util.host_label('!!!'), 'device', 'nothing left');
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
});
+39
View File
@@ -0,0 +1,39 @@
// dawnline.view: which device a portal page was opened from, and the usage series it draws.
import * as view from 'dawnline.view';
import { day_key_ago } from 'dawnline.util';
const devs = [
{ id: 'd_1', address: '10.0.0.2', online: true, endpoint: '203.0.113.7' },
{ id: 'd_2', address: '10.0.0.3', online: false, endpoint: '198.51.100.4' },
{ id: 'd_3', address: '10.0.0.4', online: true, endpoint: '192.0.2.9' },
];
test('device_here', () => {
eq(view.device_here(devs, '10.0.0.3'), 'd_2', 'through the tunnel: its address, online or not');
eq(view.device_here(devs, '203.0.113.7'), 'd_1', 'beside the tunnel: where its tunnel comes from');
eq(view.device_here(devs, '::ffff:203.0.113.7'), 'd_1', 'an IPv4 request on a dual-stack socket');
eq(view.device_here(devs, '198.51.100.4'), null, 'a device that is not online does not count');
eq(view.device_here(devs, '233.252.0.1'), null, 'from elsewhere');
eq(view.device_here([ ...devs, { id: 'd_4', address: '10.0.0.5', online: true, endpoint: '203.0.113.7' } ], '203.0.113.7'), null,
'two devices behind one address: neither');
eq(view.device_here(devs, ''), null, 'no address');
eq(view.device_here([ { id: 'd_5', address: '10.0.0.6', online: true, endpoint: '' } ], ''), null, 'no address, no endpoint');
});
test('month_days', () => {
let n = +substr(day_key_ago(0), 8, 2);
let days = {};
// On the 1st, today is the 1st: then only today's own value.
if (n > 1)
days[day_key_ago(n - 1)] = [ 1, 2 ];
days[day_key_ago(0)] = [ 5, 7 ];
// Last month's last day stays out of this month's chart.
days[day_key_ago(n)] = [ 100, 100 ];
let s = view.month_days({ days });
eq(length(s), n, 'one bar a day, from the 1st to today');
eq(s[n - 1], [ 5, 7 ], 'today last, received and sent apart');
eq(s[0], n > 1 ? [ 1, 2 ] : [ 5, 7 ], 'the 1st first');
eq(length(view.month_days(null)), n, 'no usage yet: zeros');
eq(view.month_days(null)[0], [ 0, 0 ], 'a day without traffic is zero both ways');
eq(view.spark({ days }, 1), [ [ 5, 7 ] ], 'the week the same way, today last');
});
+2
View File
@@ -655,6 +655,8 @@ do_leftovers() {
/usr/share/luci/menu.d/luci-app-dawnline.json /www/luci-static/resources/dawnline \ /usr/share/luci/menu.d/luci-app-dawnline.json /www/luci-static/resources/dawnline \
/www/luci-static/resources/view/dawnline /www/luci-static/resources/view/dawnline
for _r in /etc/rc.d/*dawnline; do [ -e "$_r" ] && set -- "$@" "$_r"; done for _r in /etc/rc.d/*dawnline; do [ -e "$_r" ] && set -- "$@" "$_r"; done
# The translations' catalogs (luci-i18n-dawnline-<lang> depends on the package, so it is gone too).
for _r in /usr/lib/lua/luci/i18n/dawnline.*.lmo; do [ -e "$_r" ] && set -- "$@" "$_r"; done
fi fi
if [ "$PURGE" -eq 1 ]; then if [ "$PURGE" -eq 1 ]; then
set -- "$@" "$DATA_DIR" /etc/config/dawnline /etc/config/dawnline-opkg /etc/config/dawnline.apk-new set -- "$@" "$DATA_DIR" /etc/config/dawnline /etc/config/dawnline-opkg /etc/config/dawnline.apk-new
+1
View File
@@ -3,3 +3,4 @@ coverage/
package-lock.json package-lock.json
src/portal/fonts/ src/portal/fonts/
src/admin/styles/*.css src/admin/styles/*.css
dist/
+418
View File
@@ -0,0 +1,418 @@
// Dawnline's string catalogs, collected from the code (run in web/):
//
// node i18n/extract.ts rewrite the .pot templates and merge the .po translations
// node i18n/extract.ts --check CI: fail when a catalog is out of date or a string is untranslated
// node i18n/extract.ts --import a.json … also take translations from drafts: [{ id, ctx?, plural?, str }],
// str a string or, for a plural, one per form
// node i18n/extract.ts --lint [--import a.json …] [--only src/admin/x.ts …]
// write nothing: report string problems, bad or stray drafts
// and, with --only, the strings of those files left untranslated
//
// Three catalogs (rules/i18n.md):
// dawnline — the admin UI, its shared code, the backend's messages and the
// LuCI menu: package/luci-app-dawnline/po (luci.mk builds
// luci-i18n-dawnline-<lang> from it)
// portal — the personal portal, the shared code and the messages of the
// backend modules the portal runs: src/portal/i18n, bundled into portal.js
// demo — what only the portal demo says: src/portal/demo/i18n
//
// A string is collected from _('…'), N_(n, '…', '…') and plural(n, '…', '…')
// with literal arguments, and from the backend's L_('…'): a service log line's
// words, written in English and put into the reader's language when shown (they
// also go into src/admin/events/log-templates.ts, the list the admin page
// matches log lines against). Anything else under those names is an error, as is
// a string LuCI could not find again (leading, trailing or doubled whitespace,
// newlines) and, in the portal and the shared code, a call at module level
// (the portal changes language in place, so text is made when it is drawn).
// The catalogs keep the files a string comes from, not lines: they change
// only when strings do.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as prettier from 'prettier';
import ts from 'typescript';
import { keyOf, parsePo, pluralForms, translated, writePo, type Entry, type Po } from './po.ts';
const WEB = path.resolve(import.meta.dirname, '..');
const REPO = path.resolve(WEB, '..');
const PKG = path.join(REPO, 'package/luci-app-dawnline');
/** The translations and their gettext plural rules (po2lmo hands the formula to LuCI's N_()). */
const LANGS: Record<string, { team: string; plural: string }> = {
ru: {
team: 'Russian',
plural: 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);',
},
};
const walk = (dir: string, keep: (f: string) => boolean): string[] =>
!fs.existsSync(dir)
? []
: fs
.readdirSync(dir, { withFileTypes: true })
.flatMap((d) =>
d.isDirectory() ? walk(path.join(dir, d.name), keep) : keep(path.join(dir, d.name)) ? [path.join(dir, d.name)] : [],
)
.sort();
const tsFiles = (dir: string, skip?: string) =>
walk(path.join(WEB, dir), (f) => f.endsWith('.ts') && !f.endsWith('.d.ts') && !(skip && f.startsWith(path.join(WEB, skip) + path.sep)));
/** The backend: ucode modules and the ucode programs (by their shebang) in the package. */
const ucodeFiles = () =>
walk(path.join(PKG, 'root'), (f) => f.endsWith('.uc') || (!path.extname(f) && fs.readFileSync(f, 'utf8').startsWith('#!/usr/bin/ucode')));
/**
* The backend modules whose messages reach the portal's visitors (its own
* refusals, what refuses a device change, the keys): the page translates them when
* the router sends them in English (no translation package installed).
*/
const PORTAL_UCODE = ['portal.uc', 'devices.uc', 'core.uc', 'awg.uc'].map((f) => path.join(PKG, 'root/usr/share/ucode/dawnline', f));
const menuFiles = () => walk(path.join(PKG, 'root/usr/share/luci/menu.d'), (f) => f.endsWith('.json'));
interface CatalogSpec {
name: string;
pot: string;
po: (lang: string) => string;
sources: () => string[];
menus?: () => string[];
/** Strings here are made when the page is drawn (the portal switches language in place). */
lazy: (file: string) => boolean;
/** The service log's words (L_) are in it: only the admin page shows the log. */
logs?: boolean;
}
const CATALOGS: CatalogSpec[] = [
{
name: 'dawnline',
pot: path.join(PKG, 'po/templates/dawnline.pot'),
po: (l) => path.join(PKG, `po/${l}/dawnline.po`),
sources: () => [...tsFiles('src/admin'), ...tsFiles('src/shared'), ...ucodeFiles()],
menus: menuFiles,
logs: true,
// rpcd keeps the backend's modules loaded while the language changes per call.
lazy: (f) => f.startsWith(path.join(WEB, 'src/shared')) || f.startsWith(path.join(PKG, 'root')),
},
{
name: 'portal',
pot: path.join(WEB, 'src/portal/i18n/portal.pot'),
po: (l) => path.join(WEB, `src/portal/i18n/${l}.po`),
sources: () => [...tsFiles('src/portal', 'src/portal/demo'), ...tsFiles('src/shared'), ...PORTAL_UCODE],
lazy: () => true,
},
{
name: 'demo',
pot: path.join(WEB, 'src/portal/demo/i18n/demo.pot'),
po: (l) => path.join(WEB, `src/portal/demo/i18n/${l}.po`),
sources: () => tsFiles('src/portal/demo'),
lazy: () => true,
},
];
/** Where the wrappers themselves pass strings on: not literals, by design. */
const WRAPPERS = new Set([path.join(WEB, 'src/shared/i18n.ts'), path.join(WEB, 'src/portal/i18n.ts')]);
/** The string arguments of each translation call: [msgid, msgid_plural?, msgctxt?]; `log`: a log line's words (L_). */
const CALLS: Record<string, { id: number; plural?: number; ctx?: number; log?: boolean }> = {
_: { id: 0, ctx: 1 },
N_: { id: 1, plural: 2, ctx: 3 },
plural: { id: 1, plural: 2 },
L_: { id: 0, log: true },
};
/** The generated list of log line templates (L_), for the admin page. */
const LOG_TEMPLATES_FILE = path.join(WEB, 'src/admin/events/log-templates.ts');
const logTemplates = new Set<string>();
const rel = (f: string) => path.relative(REPO, f).split(path.sep).join('/');
/** Why LuCI would not find this string again, or null. Its lookup squeezes whitespace (cbi.js trimws). */
export function badText(s: string): string | null {
if (!s) return 'is empty';
if (/[\n\r\t]/.test(s)) return 'has a newline or a tab (po2lmo cannot carry them)';
if (/^\s|\s$/.test(s)) return 'starts or ends with a space';
if (/\s\s/.test(s)) return 'has two spaces in a row';
return null;
}
interface Found extends Entry {
files: Set<string>;
}
class Errors {
list: string[] = [];
add(where: string, msg: string) {
this.list.push(`${where}: ${msg}`);
}
}
function isFunctionLike(n: ts.Node): boolean {
return ts.isFunctionLike(n) || ts.isPropertyDeclaration(n) || ts.isClassStaticBlockDeclaration(n);
}
/** Every translation call in one file. */
function scan(file: string, lazy: boolean, logs: boolean, errors: Errors, out: Found[]) {
const text = fs.readFileSync(file, 'utf8');
const kind = file.endsWith('.ts') ? ts.ScriptKind.TS : ts.ScriptKind.JS;
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind);
const wrapper = WRAPPERS.has(file);
const visit = (node: ts.Node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && CALLS[node.expression.text] && !wrapper) {
const name = node.expression.text;
const spec = CALLS[name];
const where = `${rel(file)}:${sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1}`;
const lit = (i: number | undefined): string | undefined | null => {
if (i === undefined) return undefined;
const a = node.arguments[i];
if (!a) return undefined;
return ts.isStringLiteral(a) || ts.isNoSubstitutionTemplateLiteral(a) ? a.text : null;
};
const id = lit(spec.id);
const pl = lit(spec.plural);
const ctx = lit(spec.ctx);
if (id == null || pl === null || (spec.plural !== undefined && pl === undefined) || ctx === null) {
errors.add(
where,
`${name}() needs string literals: a variable or a template with \${…} cannot be collected (fill placeholders with fmt())`,
);
} else {
for (const [what, s] of [
['msgid', id],
['plural', pl],
['context', ctx],
] as const)
if (s !== undefined) {
const why = badText(s);
if (why) errors.add(where, `the ${what} ${JSON.stringify(s)} ${why}`);
}
// A log line's words are not translated where they are written: anywhere goes.
if (spec.log) logTemplates.add(id);
else if (lazy && !wrapper) {
let p: ts.Node | undefined = node.parent;
while (p && !isFunctionLike(p)) p = p.parent;
if (!p) errors.add(where, `${name}() at module level: here text is made when it is drawn (the portal changes language in place)`);
}
const e: Found = { id, str: [], refs: [], files: new Set([rel(file)]) };
if (spec.log && !logs) return;
if (pl !== undefined) e.plural = pl;
if (ctx !== undefined) e.ctx = ctx;
out.push(e);
}
}
ts.forEachChild(node, visit);
};
visit(sf);
}
/** LuCI's menu titles (translated by the theme's menu). */
function scanMenu(file: string, out: Found[]) {
const menu = JSON.parse(fs.readFileSync(file, 'utf8')) as Record<string, { title?: string }>;
for (const node of Object.values(menu)) if (node.title) out.push({ id: node.title, str: [], refs: [], files: new Set([rel(file)]) });
}
/** One catalog's strings, deduplicated and sorted (by code unit: the same order on every machine). */
function collect(spec: CatalogSpec, errors: Errors): Entry[] {
const found: Found[] = [];
for (const f of spec.sources()) scan(f, spec.lazy(f), !!spec.logs, errors, found);
for (const f of spec.menus?.() ?? []) scanMenu(f, found);
const byKey = new Map<string, Found>();
for (const e of found) {
const k = keyOf(e);
const had = byKey.get(k);
if (!had) byKey.set(k, e);
else if (had.plural !== e.plural)
errors.add(
[...e.files][0],
`${JSON.stringify(e.id)} is used ${had.plural === undefined || e.plural === undefined ? 'both as a plural and as a plain string' : `with two plurals (${JSON.stringify(had.plural)}, ${JSON.stringify(e.plural)})`}: give one of them a context`,
);
else e.files.forEach((f) => had.files.add(f));
}
return [...byKey.values()]
.map(({ files, ...e }) => ({ ...e, refs: [...files].sort() }))
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : (a.ctx ?? '') < (b.ctx ?? '') ? -1 : (a.ctx ?? '') > (b.ctx ?? '') ? 1 : 0));
}
const HEADER: [string, string][] = [
['Project-Id-Version', 'Dawnline'],
['MIME-Version', '1.0'],
['Content-Type', 'text/plain; charset=UTF-8'],
['Content-Transfer-Encoding', '8bit'],
];
const read = (f: string): Po | null => (fs.existsSync(f) ? parsePo(fs.readFileSync(f, 'utf8')) : null);
interface Draft {
id: string;
ctx?: string;
plural?: string;
str: string | string[];
}
/** The placeholders of a string, in order: what a translation must keep. */
export const holes = (s: string) => (s.match(/%[sd]/g) ?? []).join(' ');
/** Problems in one translation, for --check and the summary. */
export function badTranslation(e: Entry): string | null {
const want = holes(e.plural ?? e.id);
if (e.plural !== undefined && holes(e.id) !== want) return `the singular and the plural have different placeholders`;
for (const s of e.str) {
if (!s) continue;
if (s.includes('\\')) return `${JSON.stringify(s)} has a backslash (po2lmo would show it as written)`;
if (s.includes('—')) return `${JSON.stringify(s)} has an em dash: use a plain dash (rules/i18n.md)`;
const why = badText(s);
if (why) return `${JSON.stringify(s)} ${why}`;
if (holes(s) !== want) return `${JSON.stringify(s)} has the placeholders "${holes(s)}", the English "${want}"`;
}
return null;
}
/** The command line: --check, --lint, and the files after --import and --only. */
function options(argv: string[]) {
const o = { check: false, lint: false, imports: [] as string[], only: [] as string[] };
let list: string[] | null = null;
for (const a of argv) {
if (a === '--check' || a === '--lint') {
o[a === '--check' ? 'check' : 'lint'] = true;
list = null;
} else if (a === '--import') list = o.imports;
else if (a === '--only') list = o.only;
else if (list) list.push(a);
else throw new Error(`unknown argument ${a} (see the top of i18n/extract.ts)`);
}
return o;
}
const draftKey = (d: { ctx?: string; id: string; plural?: string }) => keyOf(d) + (d.plural !== undefined ? '\u0002' : '');
/** The list of log line templates as a module (formatted as the repo formats code). */
async function logTemplatesModule(): Promise<string> {
const list = [...logTemplates].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
const code = [
"// Generated by web/i18n/extract.ts from the backend's L_() strings (npm run i18n): do not edit.",
'// The words of service log lines, as written; events/model.ts matches log lines against them.',
'',
`export const LOG_TEMPLATES: string[] = ${JSON.stringify(list)};`,
'',
].join('\n');
return prettier.format(code, { ...(await prettier.resolveConfig(LOG_TEMPLATES_FILE)), filepath: LOG_TEMPLATES_FILE });
}
async function main() {
const opt = options(process.argv.slice(2));
const errors = new Errors();
const problems: string[] = [];
const drafts = new Map<string, Draft & { from: string }>();
for (const f of opt.imports)
for (const d of JSON.parse(fs.readFileSync(path.resolve(f), 'utf8')) as Draft[]) {
const had = drafts.get(draftKey(d));
if (had && JSON.stringify(had.str) !== JSON.stringify(d.str))
problems.push(
`drafts disagree on ${JSON.stringify(d.id)}: ${JSON.stringify(had.str)} (${had.from}), ${JSON.stringify(d.str)} (${f})`,
);
drafts.set(draftKey(d), { ...d, from: f });
}
const usedDrafts = new Set<string>();
const collected = CATALOGS.map((spec) => ({ spec, entries: collect(spec, errors) }));
const only = opt.only.map((f) => rel(path.resolve(f)));
const under = (r: string) => only.some((o) => r === o || r.startsWith(`${o}/`));
// Linting some files: the problems of those (other files may be half-way through a change).
if (opt.lint) problems.push(...errors.list.filter((e) => !only.length || under(e.replace(/:\d+: [\s\S]*$/, ''))));
else if (errors.list.length) {
console.error(errors.list.join('\n'));
console.error(`\n${errors.list.length} string problem(s): fix them in the code (rules/i18n.md).`);
process.exit(1);
}
// What each language already has, across catalogs: a string translated in one is reused in the others.
const known = new Map<string, Map<string, string[]>>();
for (const lang of Object.keys(LANGS)) {
const m = new Map<string, string[]>();
for (const { spec } of collected)
for (const e of read(spec.po(lang))?.entries ?? [])
if (translated(e)) m.set(keyOf(e) + (e.plural !== undefined ? `\u0002${e.plural}` : ''), e.str);
known.set(lang, m);
}
const inOnly = (e: Entry) => e.refs.some(under);
const out = new Map<string, string>();
const report: string[] = [];
const missingOnly = new Set<string>();
for (const { spec, entries } of collected) {
out.set(
spec.pot,
writePo({
header: [...HEADER, ['Plural-Forms', 'nplurals=2; plural=(n != 1);']],
entries: entries.map((e) => ({ ...e, str: e.plural !== undefined ? ['', ''] : [''] })),
}),
);
for (const [lang, info] of Object.entries(LANGS)) {
const file = spec.po(lang);
const old = new Map((read(file)?.entries ?? []).map((e) => [draftKey(e), e]));
const header: [string, string][] = [...HEADER, ['Language', lang], ['Language-Team', info.team], ['Plural-Forms', info.plural]];
const forms = pluralForms({ header, entries: [] });
const merged = entries.map((e): Entry => {
const k = draftKey(e);
const blank = e.plural !== undefined ? Array<string>(forms).fill('') : [''];
const draft = drafts.get(k);
if (draft) {
usedDrafts.add(k);
const str = Array.isArray(draft.str) ? draft.str : [draft.str];
if (str.length === blank.length) return { ...e, str };
problems.push(`${spec.name}/${lang}: the draft for ${JSON.stringify(e.id)} has ${str.length} form(s), ${blank.length} needed`);
}
const was = old.get(k);
// A changed plural keeps its forms only when the English plural stayed the same.
if (was && translated(was) && was.plural === e.plural) return { ...e, str: was.str };
const other = known.get(lang)!.get(keyOf(e) + (e.plural !== undefined ? `\u0002${e.plural}` : ''));
return { ...e, str: other && other.length === blank.length ? other : blank };
});
out.set(file, writePo({ header, entries: merged }));
const missing = merged.filter((e) => !translated(e));
for (const e of merged) {
const why = badTranslation(e);
if (why && (!only.length || inOnly(e))) problems.push(`${rel(file)}: ${JSON.stringify(e.id)}: ${why}`);
}
report.push(`${spec.name}/${lang}: ${merged.length - missing.length} of ${merged.length} translated`);
if (opt.check)
for (const e of missing) problems.push(`${rel(file)}: untranslated ${JSON.stringify(e.id)}${e.ctx ? ` (${e.ctx})` : ''}`);
for (const e of missing)
if (inOnly(e))
missingOnly.add(
`no translation for ${JSON.stringify(e.id)}${e.ctx ? ` (context ${e.ctx})` : ''}${e.plural !== undefined ? ` (plural ${JSON.stringify(e.plural)})` : ''} [${e.refs.filter(under).join(' ')}]`,
);
}
}
for (const [k, d] of drafts)
if (!usedDrafts.has(k))
problems.push(`draft ${JSON.stringify(d.id)}${d.plural !== undefined ? ' (plural)' : ''} is not in the code (${d.from})`);
problems.push(...missingOnly);
out.set(LOG_TEMPLATES_FILE, await logTemplatesModule());
if (opt.check || opt.lint) {
if (opt.check)
for (const [f, text] of out)
if (!fs.existsSync(f) || fs.readFileSync(f, 'utf8') !== text)
problems.unshift(`${rel(f)} is out of date: run "npm run i18n" in web/ and commit the result`);
if (problems.length) {
console.error(problems.join('\n'));
process.exit(1);
}
console.log(opt.lint ? 'No problems.' : report.join('\n'));
return;
}
for (const [f, text] of out) {
if (fs.existsSync(f) && fs.readFileSync(f, 'utf8') === text) continue;
fs.mkdirSync(path.dirname(f), { recursive: true });
fs.writeFileSync(f, text);
}
console.log(report.join('\n'));
if (problems.length) console.warn(`\n${problems.join('\n')}`);
}
// Run as a program; imported (by the tests), only the checks above.
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();
+110
View File
@@ -0,0 +1,110 @@
// The LMO catalog LuCI loads (/usr/lib/lua/luci/i18n/<name>.<lang>.lmo), made
// from a .po byte for byte as LuCI's po2lmo makes it. The release packages are
// built by the SDK's own po2lmo (luci.mk); this one is for the dev deploy
// (scripts/build-release.sh), which has no SDK.
//
// Layout: the translations, each padded with zeros to 4 bytes, in the .po's
// order (the Plural-Forms formula first, under key 0); then an index entry per
// string, sorted by key: key hash, number of forms, offset, length (big-endian
// uint32s); then the index's offset. A key is the msgid, with "ctx\x01" before
// it and "\x02<n>" after it for plural form n; its hash is Paul Hsieh's
// SuperFastHash seeded with the length (lmo.c sfh_hash, cbi.js sfh).
//
// node i18n/lmo.ts in.po out.lmo
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parsePo, type Po } from './po.ts';
/** SuperFastHash of the bytes, seeded with their length, as a uint32. */
export function sfh(data: Uint8Array): number {
const get16 = (i: number) => data[i] | (data[i + 1] << 8);
const s8 = (i: number) => (data[i] << 24) >> 24;
let hash = data.length >>> 0;
if (!data.length) return 0;
let i = 0;
for (let n = data.length >>> 2; n > 0; n--, i += 4) {
hash = (hash + get16(i)) >>> 0;
const tmp = ((get16(i + 2) << 11) ^ hash) >>> 0;
hash = ((hash << 16) ^ tmp) >>> 0;
hash = (hash + (hash >>> 11)) >>> 0;
}
switch (data.length & 3) {
case 3:
hash = (hash + get16(i)) >>> 0;
hash = (hash ^ (hash << 16)) >>> 0;
hash = (hash ^ (s8(i + 2) << 18)) >>> 0;
hash = (hash + (hash >>> 11)) >>> 0;
break;
case 2:
hash = (hash + get16(i)) >>> 0;
hash = (hash ^ (hash << 11)) >>> 0;
hash = (hash + (hash >>> 17)) >>> 0;
break;
case 1:
hash = (hash + s8(i)) >>> 0;
hash = (hash ^ (hash << 10)) >>> 0;
hash = (hash + (hash >>> 1)) >>> 0;
}
hash = (hash ^ (hash << 3)) >>> 0;
hash = (hash + (hash >>> 5)) >>> 0;
hash = (hash ^ (hash << 4)) >>> 0;
hash = (hash + (hash >>> 17)) >>> 0;
hash = (hash ^ (hash << 25)) >>> 0;
hash = (hash + (hash >>> 6)) >>> 0;
return hash;
}
const utf8 = (s: string) => new TextEncoder().encode(s);
export function lmo(po: Po): Uint8Array {
const chunks: Uint8Array[] = [];
const index: { key: number; forms: number; offset: number; length: number }[] = [];
let offset = 0;
const add = (key: number, forms: number, value: Uint8Array) => {
const padded = new Uint8Array(value.length + ((4 - (value.length % 4)) % 4));
padded.set(value);
index.push({ key, forms, offset, length: value.length });
chunks.push(padded);
offset += padded.length;
};
const pf = po.header.find(([k]) => k === 'Plural-Forms');
if (pf) add(0, 0, utf8(pf[1]));
for (const e of po.entries) {
if (!e.str[0]) continue;
e.str.forEach((s, i) => {
if (!s) return;
const key = utf8(`${e.ctx !== undefined ? `${e.ctx}\u0001` : ''}${e.id}${e.plural !== undefined ? `\u0002${i}` : ''}`);
const value = utf8(s);
const k = sfh(key);
// An unchanged string is left out: LuCI shows the English anyway.
if (k !== sfh(value)) add(k, e.str.length, value);
});
}
index.sort((a, b) => a.key - b.key);
const out = new Uint8Array(offset + index.length * 16 + (offset > 0 ? 4 : 0));
const view = new DataView(out.buffer);
let at = 0;
for (const c of chunks) {
out.set(c, at);
at += c.length;
}
for (const x of index) {
for (const v of [x.key, x.forms, x.offset, x.length]) {
view.setUint32(at, v);
at += 4;
}
}
if (offset > 0) view.setUint32(at, offset);
return out;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const [src, dst] = process.argv.slice(2);
if (!src || !dst) {
console.error('usage: node i18n/lmo.ts in.po out.lmo');
process.exit(2);
}
fs.writeFileSync(dst, lmo(parsePo(fs.readFileSync(src, 'utf8'))));
}
+137
View File
@@ -0,0 +1,137 @@
// Gettext catalogs (.pot / .po) as Dawnline writes them: the subset LuCI's
// po2lmo reads. Entries have an optional msgctxt, a msgid, an optional
// msgid_plural and the msgstr (or msgstr[n], one per plural form), with their
// "#:" source references. Strings are one line each and know two escapes, \"
// and \\: po2lmo copies any other escape as written ("\n" stays a backslash and
// an n), so extract.ts refuses newlines and tabs in strings, and backslashes in
// translations. No dates in the header: a catalog changes only when its strings do.
//
// Pure: no files. extract.ts reads and writes the catalogs; the portal's
// bundle turns a .po into a lookup table with catalogOf().
export interface Entry {
ctx?: string;
id: string;
plural?: string;
/** The translation: one string, or one per plural form. '' where there is none yet. */
str: string[];
/** Where the string is used: "src/admin/pages/people.ts:120". */
refs: string[];
}
export interface Po {
/** Header fields in their order ("Language", "Plural-Forms", …). */
header: [string, string][];
entries: Entry[];
}
/** An entry's identity: its context and msgid (the plural form shares its msgid's). */
export const keyOf = (e: { ctx?: string; id: string }) => (e.ctx ? `${e.ctx}\u0004${e.id}` : e.id);
export const translated = (e: Entry) => e.str.length > 0 && e.str.every((s) => s !== '');
/** A quoted po string's content: \" and \\ read, any other escape kept as written (the header's \n). */
function unquote(s: string, line: number): string {
const m = /^"((?:[^"\\]|\\.)*)"$/.exec(s);
if (!m) throw new Error(`po line ${line}: expected a quoted string, got ${s}`);
return m[1].replace(/\\(.)/g, (all, c: string) => (c === '"' || c === '\\' ? c : all));
}
const quote = (s: string) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
type Draft = { ctx?: string; id?: string; plural?: string; str: string[]; refs: string[] };
export function parsePo(text: string): Po {
const po: Po = { header: [], entries: [] };
let cur: Draft = { str: [], refs: [] };
// Where a continuation line ("…") goes: the field the last keyword opened.
let append: ((s: string) => void) | null = null;
const flush = () => {
if (cur.id === '' && cur.ctx === undefined) {
for (const f of (cur.str[0] ?? '').split('\\n')) {
const i = f.indexOf(':');
if (i > 0) po.header.push([f.slice(0, i).trim(), f.slice(i + 1).trim()]);
}
} else if (cur.id !== undefined) {
const e: Entry = { id: cur.id, str: cur.str.map((s) => s ?? ''), refs: cur.refs };
if (cur.ctx !== undefined) e.ctx = cur.ctx;
if (cur.plural !== undefined) e.plural = cur.plural;
po.entries.push(e);
}
cur = { str: [], refs: [] };
};
text.split(/\r?\n/).forEach((raw, n) => {
const line = raw.trim();
if (!line) return void (append = null);
if (line.startsWith('#')) {
if (cur.id !== undefined) flush();
if (line.startsWith('#:')) cur.refs.push(...line.slice(2).trim().split(/\s+/).filter(Boolean));
append = null;
return;
}
if (line.startsWith('"')) {
if (!append) throw new Error(`po line ${n + 1}: a string outside an entry`);
return append(unquote(line, n + 1));
}
const m = /^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d)\])?)\s+(".*")$/.exec(line);
if (!m) throw new Error(`po line ${n + 1}: cannot read ${line}`);
const [, kw, idx, val] = m;
const v = unquote(val, n + 1);
if ((kw === 'msgctxt' || kw === 'msgid') && cur.id !== undefined) flush();
if (kw === 'msgctxt') {
cur.ctx = v;
append = (s) => (cur.ctx += s);
} else if (kw === 'msgid') {
cur.id = v;
append = (s) => (cur.id += s);
} else if (kw === 'msgid_plural') {
cur.plural = v;
append = (s) => (cur.plural += s);
} else {
const i = idx === undefined ? 0 : Number(idx);
cur.str[i] = v;
append = (s) => (cur.str[i] += s);
}
});
flush();
return po;
}
export function writePo(po: Po): string {
const out = ['msgid ""', 'msgstr ""', ...po.header.map(([k, v]) => `${quote(`${k}: ${v}`).slice(0, -1)}\\n"`), ''];
for (const e of po.entries) {
for (const r of e.refs) out.push(`#: ${r}`);
if (e.ctx !== undefined) out.push(`msgctxt ${quote(e.ctx)}`);
out.push(`msgid ${quote(e.id)}`);
if (e.plural !== undefined) {
out.push(`msgid_plural ${quote(e.plural)}`);
e.str.forEach((s, i) => out.push(`msgstr[${i}] ${quote(s)}`));
} else out.push(`msgstr ${quote(e.str[0] ?? '')}`);
out.push('');
}
return out.join('\n');
}
/** The number of plural forms a catalog's header declares (2 when it says nothing). */
export function pluralForms(po: Po): number {
const pf = po.header.find(([k]) => k === 'Plural-Forms')?.[1] ?? '';
const m = /nplurals\s*=\s*(\d+)/.exec(pf);
return m ? Number(m[1]) : 2;
}
/** What the portal looks strings up in: translated strings by key, plural forms by the singular's key. */
export interface Catalog {
s: Record<string, string>;
p: Record<string, string[]>;
}
/** A .po as a lookup table: translated entries only (an untranslated string stays English). */
export function catalogOf(po: Po): Catalog {
const c: Catalog = { s: {}, p: {} };
for (const e of po.entries) {
if (!translated(e)) continue;
if (e.plural !== undefined) c.p[keyOf(e)] = e.str;
else c.s[keyOf(e)] = e.str[0];
}
return c;
}
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "dawnline-web", "name": "dawnline-web",
"version": "0.7.0", "version": "0.12.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "dawnline-web", "name": "dawnline-web",
"version": "0.7.0", "version": "0.12.1",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"qrcode-generator": "1.4.4" "qrcode-generator": "1.4.4"
+5 -2
View File
@@ -1,17 +1,20 @@
{ {
"name": "dawnline-web", "name": "dawnline-web",
"version": "0.7.0", "version": "0.12.1",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "tsc --noEmit && tsup", "build": "tsc --noEmit && tsup",
"dev": "tsup --watch", "dev": "tsup --watch",
"build:demo": "tsc --noEmit && tsup --config tsup.demo.config.ts",
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json", "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
"test": "vitest run", "test": "vitest run",
"format": "prettier --write .", "format": "prettier --write .",
"format:check": "prettier --check .", "format:check": "prettier --check .",
"ci": "npm run format:check && npm run typecheck && npm run test && npm run build" "ci": "npm run format:check && npm run typecheck && npm run i18n:check && npm run test && npm run build",
"i18n": "node i18n/extract.ts",
"i18n:check": "node i18n/extract.ts --check"
}, },
"dependencies": { "dependencies": {
"qrcode-generator": "1.4.4" "qrcode-generator": "1.4.4"
Loaded 100 of 252 files, more files were not shown because too many files have changed in this diff. Show more