Compare commits

12 Commits
Author SHA1 Message Date
Aemeath f8130e39a8 Dawnline 0.18.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
- Add V2RayTun to a device's set-up on Android: its awg:// link as a code and to copy, in the portal and in the admin (phones, tablets and other devices), with the server's IP, which its Android app needs; not with the Maximum disguise. Its Windows app is ready but stays off until it gives the tunnel the server's DNS.
- Portal: show V2RayTun's Telegram channel beside Google Play.
- Make WireGuard part of AmneziaWG's choice when the disguise is off: the same file and code, both apps named in the steps, WireGuard's store a tap away; a router still picks its package.
- Portal: Reconnect asks again what the device is and about LAN Bypass, and LAN Bypass switches from a device's ⋯ menu, in a group of its own between the copy actions and Rename, Reconnect, Remove (the keys stay; the device takes its updated configuration).
- Turn LAN Bypass on by default for new devices, in the portal and the admin.
- Portal: an app's name too long for the picker fades at its edge and glides to its end on hover or tap; two store buttons stack where they do not fit side by side; the month chart's "Today" stays inside its axis.
- Write to the router's system log by level (Settings → Logs & history → System log: errors, warnings, normal, verbose): the service starting and stopping, every apply with its time, network, firewall, nftables and peer changes, changed settings and portal errors, in English whatever the admin's language, with keys masked.
- Activity: say what a device's change on the portal was (LAN Bypass on or off, its type).
- Demo: build again after a force-pushed main instead of failing on the commit that is gone.
2026-11-05 13:56:20 +03:00
Aemeath 18e3013047 Dawnline 0.17.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
- Redraw the admin's charts in the connection map's style: the live speed as lines, the last 30 days and a device's week as stacked download and upload bars, a device's days as a strip, data use as meters.
- Read any chart point by point with the pointer, a tap or the arrow keys; a day's tooltip compares it with the average and shows its download and upload.
- Show where a data limit leads at the recent pace: the week ahead on the meter, and when the limit fills or what a monthly one reaches by the reset.
- Make Speed now live, one point a second, on a person's page, in the People list and in an online person's card.
- Name every place an online person's devices connect from, and the city each device connects from now.
- Portal: read the month and the week by tap or arrow keys, see how a day compares with the others, the pace toward the data limit and how long the allowed hours still run.
- Send VPN clients' DNS to the LAN's DNS after its interceptors, so transparent proxies such as forkop also handle their lookups.
2026-11-02 09:48:31 +03:00
Aemeath b0d9982796 Dawnline 0.16.3
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
- Move Dawnline to Services in LuCI and update links and documentation.
- Make activity messages clearer, including device renames and person-specific history.
- Prune redundant frontend tests.
2026-10-31 12:21:53 +03:00
Aemeath f2b5ba101b Dawnline 0.16.2
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 personal page switches to a renewed HTTPS certificate on its own:
  after ACME issues or renews one, the page restarts with it instead of
  serving the old certificate until Dawnline restarts
2026-10-26 07:39:32 +03:00
Aemeath 0fd22b917a Dawnline 0.16.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
- Checking one component for updates in Components no longer fails
  with "XHR request timed out": the check starts at once instead of
  keeping the page waiting twenty seconds
- On a router without curl, updates and the installer download release
  files through GitHub's API: GitHub's own download links can make
  OpenWrt's built-in downloader hang
- Adding a device in the admin offers the same four types as the
  personal page: PC, Mobile, Router and Other (phones and tablets are
  one choice)
2026-10-26 06:41:54 +03:00
Aemeath 2388603322 Dawnline 0.16.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 personal page loads faster and costs the router less: its script
  and styles come compressed, stay in the browser until the next update,
  and the icon comes with the page instead of a request of its own
- The page uses the system's own font (SF Pro on Apple devices, Segoe UI
  on Windows, Roboto on Android) instead of downloading one
- The top of the page shows the server's name alone, so it fits on a
  phone
- Text can be selected only where it is there to be copied (addresses,
  file names, the configuration), with the name field's own selection:
  a soft highlight with handles that glides after the pointer
- Sheets scroll without a scrollbar
- Red buttons (Remove) light up under the pointer, as the others do
- Demo: "Demo" and GitHub are one button; on a phone it floats at the
  bottom of the screen, and switching scenarios no longer makes the
  edge fades jump
2026-10-24 21:33:48 +03:00
Aemeath 750564ab7e Dawnline 0.15.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
- Dropdowns (the ⋯ menu, the language picker, the page's QR card) open
  on a softer spring: they grow in without the wobble at the end
- Renaming a device on its card: the hint under the name and a refusal
  take the status's place as whole words, and after a save the status
  comes back the same way
- Cancelling a rename started while the status was still changing puts
  back what it said, not a mix of its old and new letters
2026-10-22 18:01:01 +03:00
dependabot[bot] 3fadee87d3 Bump vitest from 3.2.4 to 5.0.5 in /web
Closes the open Dependabot alerts for vitest, @vitest/mocker and tinypool (dev dependencies only; tinypool is no longer pulled in).
2026-10-22 17:58:11 +03:00
Aemeath ba231e7187 Dawnline 0.15.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 device menu (⋯) is an iOS-style menu on frosted glass: the copy
  actions show the address they copy, Rename, Reconnect and Remove sit
  under them, and one highlight glides from row to row
- The language picker shows flags; pick a language with a click, or
  press the pill and slide onto one. The flag and the code change in
  place
- The page's QR code opens as a small card under its button, with Copy
  link and Share
- All dropdowns look and behave the same: frosted glass, one open at a
  time, and a press outside, Escape or the button again closes them
- Setting a device up: when it can't finish connecting or connects but
  passes no data, the sheet keeps just the status and what it means.
  No data now says the router drops its traffic because the address
  doesn't match, and the device's card says "Connected, but no data"
  right away instead of "Connected"
- Setting a phone up from another device: Download and Copy for the
  connection sit on its row, next to the arrow
- On iPhone and iPad the caret shows as soon as a field is focused, the
  page no longer zooms on a pinch or a double tap, and sheets and their
  animations run smoother
- A press near the edge of a button or a card always counts, even as it
  shrinks under the pointer
- Animations settle without a jump at the end
- New green, orange and red
- The focus ring shows only while moving around with the keyboard
2026-10-22 04:02:54 +03:00
Aemeath a1915f070b Dawnline 0.14.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
- The updater started without a command, with one it doesn't know, or
  with an install of nothing prints its usage and exits. It no longer
  counts that as a failed update: nothing goes into the service log,
  Activity or the update history, and Components shows no failed job.
  `updater --help` prints the same usage
2026-10-22 00:20:51 +03:00
Aemeath dc0f159447 Dawnline 0.14.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
- A device is renamed where its name stands on its card: a click on the
  name, Return or Space on it, or Rename in the ⋯ menu turns it into a
  field with the name selected. Return saves, and the words shimmer until
  the router answers. Esc or a click elsewhere puts the old name back. The
  rename window is gone, and the page no longer redraws under a name being
  edited
- Device names take up to 20 characters: letters of any language, digits,
  spaces and - _ . The router refuses anything else when a device is added
  or renamed, so a name can't carry symbols into configurations, file
  names or the AmneziaVPN key. The portal and the admin turn a character
  like that away as it is typed: the field shakes, its outline goes red
  and a short line says why. Suggested names (a phone's model, "Phone 2")
  are stripped of such characters and cut to fit. Names set before this
  stay as they are
- LAN Bypass: Add a device, in the portal and in the admin, has a switch
  that keeps the device's own local network (printer, TV, NAS) reachable
  while it is connected. It is off by default and stays as chosen; the
  admin's device drawer shows it. With home and internet access the switch
  says which addresses still lead to the home network
- Health warns when a server's home network is on one of the subnets home
  routers come with (192.168.0.x, 192.168.1.x and others). People with
  home access who connect from a network on the same addresses reach your
  home instead of their own, LAN Bypass or not
- The router tells when a device can't connect properly. After the problem
  lasts three minutes, the portal card and the admin drawer name it:
  can't finish connecting (the network may block it), connected but no
  data (an outdated configuration, and the card offers Reconnect), on two
  devices at once, or a connection that keeps dropping. Activity lists
  these under Problems, one line per device per hour, and says when the
  device connects normally again
- The set-up sheet's connection line follows what the device does:
  waiting, can't finish, connected, or connected but no data. The sheet
  closes by itself only once data comes through. On the device itself and
  for a router, the steps regroup to what fixes the problem: "Set it up
  again" when the handshake never finishes, "Add the connection again"
  ("Import the configuration again" for a router) when no data comes
- Set-up in the portal: a QR code too long for a camera to read gives its
  place to a code that opens the set-up link (a LAN Bypass configuration
  or a long AmneziaVPN key can be that long). A TV, box or NAS added from
  a phone gets the steps for setting up from another device. Back from
  "Open on the device" keeps the kind, LAN Bypass and the name typed. The
  packet-size note under the kinds is gone
- The portal on phones keeps its place: nothing jumps when an access row
  opens or folds, a notice comes or goes, or Safari redraws the cards. A
  reload, or coming back from the VPN app, opens where the page was. Cards
  glide to their new height, and an animation interrupted half-way goes on
  from where it is instead of snapping. A double click no longer closes
  the sheet it just opened
- In the admin, a device's drawer has its own MTU and keep-alive (empty
  means the server's), each with a Change dialog. A change touches only
  that device's configuration and restarts nothing on the router. Opening
  the drawer no longer counts as handing out the configuration: "Update
  config" stays until the new configuration is shown as a QR code,
  downloaded or copied ("Show the new configuration"). New keys set the
  device up again, as the portal's Reconnect does
- "Speed now" on a server's Overview is live: one point a second over the
  last two minutes, all there as soon as the Overview opens. The agent
  keeps those two minutes in memory and writes them out only while someone
  is looking
- Disguise values that AmneziaWG refuses or crashes on are stopped before
  they reach the kernel. That covers overlapping H1-H4, Jmin above Jmax,
  broken I1-I5 tags, padding under 12 with header protection, and more.
  Import and restore refuse them. After a hand edit in uci, the server's
  tunnel stays down and Health and the service log say why and what to do.
  Errors are full sentences in the reader's language
- The header protection key no longer shows in the status that read-only
  users can see: the Server page says only that the key is set, and each
  device's configuration still has it. The server no longer turns off
  WireGuard's protection against handshake floods (devices keep
  DisableCookies). A device can't be added with a server's own key
- An AmneziaWG update whose kernel module can't be swapped (another
  AmneziaWG interface holds the old one) no longer fails. It is installed,
  the tunnels come back on the old module, and Health and Components say
  the update starts after a reboot. On apk firmware, an install that apk
  left at the old version counts as failed. A module installed by hand is
  recorded, so after a firmware upgrade Health can tell that it is gone
- Dawnline reads only its own tunnels, each one separately. Another
  AmneziaWG interface on the router no longer slows the agent's
  once-a-second check, has its keys read or breaks Dawnline's reads. A
  portal request reads only that person's server: one process however many
  servers there are
- Fewer false disconnects: a tunnel that netifd sets up again no longer
  logs everyone as leaving and coming back, and a device with a long
  keep-alive stays online between handshakes. One configuration on two
  devices isn't logged as roaming every few seconds, and new keys end the
  old session at once. A tunnel that is missing devices is synced within a
  minute, and traffic across a tunnel restart is no longer undercounted
- Renaming a server no longer restarts its tunnel. If a tunnel's interface
  is edited outside Dawnline (LuCI, uci), the watchdog sets it up again
  with Dawnline's settings and names only the changed options. The routing
  rules for "Internet like a home device" change one at a time, new ones
  first, so traffic never falls between them. Health and the Server page
  warn when the address's AAAA record isn't this router's, or the router
  has no public IPv6: devices that prefer IPv6 fail to connect
- The README screenshots come in English and Russian; the portal's are
  taken from its demo. The demo has a switch beside × in the set-up sheet
  to show each state of the connection line. In Russian, long labels in
  the admin's wide option buttons wrap under their icon. DESIGN.md
  describes the switch, renaming on the card, the shimmer, the shake and
  how the portal scrolls. New tests cover link states, the meter, access,
  Health, firewall rules, network settings and packages
2026-10-22 00:11:50 +03:00
Aemeath 58492be021 Dawnline 0.13.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
- "Internet like a home device" starts off on new servers: sending the
  tunnel through the home network costs speed. Both server wizards (the
  first one and "Add server") have the switch, and on it says what it
  costs. Servers that have it on keep it
- With it off, Server → Access says what that means: DNS still goes
  through the router, its proxies and filters see the tunnel only once its
  interface is added to their source interfaces, and sites the router's
  DNS answers with proxy addresses won't open
- With it on, established connections skip the second pass through
  netfilter in Dawnline's network namespace (a software flowtable): about
  12% less router CPU per packet, and about a quarter more speed through a
  proxy on the router. Without kmod-nft-offload the old rules load and the
  service log says so
- Its address at home stays the same when it is turned off and on again;
  it moved down by one each time (.254, .253, .252)
- Less CPU for the same work: the background agent's once-a-second look at
  the tunnels, Status, Health and the portal no longer compile the same
  patterns again for each line, address and device. At idle the agent uses
  about a quarter of the CPU it did; a portal request 5-10 ms less
- On LuCI's Bootstrap themes the admin looks as it does on Outline: cards
  and menus a step above the page, icon tiles that keep their colour,
  Outline's status colours in dark mode. The choices in Settings → Logs &
  history and Updates are LuCI's own controls in every theme
- "Add from devices at home" keeps a device's name readable in a narrow
  window: its ports go under the name
- DESIGN.md describes the portal's look, components and motion, and the
  rules send portal work there first. lint-ucode no longer ends a function
  at a brace inside a template literal
2026-10-21 01:42:23 +03:00
279 changed files with 21477 additions and 3794 deletions

No files matched your search

+8 -8
View File
@@ -33,7 +33,7 @@ jobs:
version: ${{ steps.version.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -63,14 +63,14 @@ jobs:
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
steps:
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
node-version: '26'
cache: npm
cache-dependency-path: web/package-lock.json
@@ -87,7 +87,7 @@ jobs:
run: scripts/build-packages.sh ${{ matrix.type }}
- name: Upload
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: package-${{ matrix.type }}
# The app and its translation packages (luci-i18n-dawnline-<lang>).
@@ -105,7 +105,7 @@ jobs:
steps:
# The whole history and the tags: the notes list the commits since the previous tag.
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
fetch-depth: 0
@@ -116,7 +116,7 @@ jobs:
cat notes.md
- name: Download packages
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: package-*
path: release
@@ -129,7 +129,7 @@ jobs:
cat sha256sums.txt
- name: Publish the release
uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
name: Dawnline ${{ github.ref_name }}
tag_name: ${{ github.ref_name }}
+27 -11
View File
@@ -24,14 +24,14 @@ jobs:
working-directory: web
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: '22'
node-version: '26'
cache: npm
cache-dependency-path: web/package-lock.json
@@ -51,6 +51,20 @@ jobs:
id: types
run: npm run --silent typecheck
# oxlint's correctness rules: what the types let through (a stray expression, a needless escape).
- name: Lint
id: lint
run: npm run --silent lint
# Exports nobody imports, files nobody reaches, dependencies used but not listed (or listed but unused).
- name: Unused code
id: knip
run: |
if ! npm run --silent knip; then
echo "::error::knip found unused code or a dependency problem: remove it, or drop the export when only its own file uses it."
exit 1
fi
# The catalogs follow the code: every string collected, translated, its placeholders kept.
- name: Translations
id: i18n
@@ -64,17 +78,17 @@ jobs:
id: tests
run: npm test
# The bundles under package/ are committed: a build must change nothing
# and leave no new file behind (an output nobody added to git would be
# missing from the package).
- name: Build bundles and check they are committed
# The bundles under package/ are not committed (build.yml builds them
# before packaging): a build must touch no tracked file and leave every
# output it writes ignored by .gitignore, so none ends up in a commit.
- name: Build bundles and check they stay out of git
id: build
run: |
npm run --silent build
changed="$(git status --porcelain --untracked-files=all -- ../package)"
if [ -n "$changed" ]; then
echo "$changed"
echo "::error::The committed bundles are out of date or the build left new files. Run 'npm run build' in web/ and commit the result."
echo "::error::The build changed a tracked file under package/ or wrote one .gitignore does not cover."
exit 1
fi
@@ -88,6 +102,8 @@ jobs:
echo "|---|---|"
echo "| Formatting | ${{ steps.format.outcome }} |"
echo "| Types | ${{ steps.types.outcome }} |"
echo "| Lint | ${{ steps.lint.outcome }} |"
echo "| Unused code | ${{ steps.knip.outcome }} |"
echo "| Translations | ${{ steps.i18n.outcome }} |"
echo "| Tests | ${{ steps.tests.outcome }} |"
echo "| Bundles | ${{ steps.build.outcome }} |"
@@ -98,7 +114,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -127,7 +143,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
@@ -174,7 +190,7 @@ jobs:
release: ['24.10', '25.12']
steps:
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+3
View File
@@ -2,3 +2,6 @@ node_modules/
dist/
.DS_Store
web/coverage/
# The web bundles: web/ builds them (npm run build), CI before packaging.
package/luci-app-dawnline/htdocs/luci-static/resources/dawnline/
package/luci-app-dawnline/root/usr/share/dawnline/portal/assets/
+3 -2
View File
@@ -9,6 +9,7 @@ Guidance for coding agents working in this repository (`tickcount/luci-app-dawnl
- `rules/frontend.md` — TypeScript admin UI and portal: layout of `web/src`, pollers and the live revision.
- `rules/shell.md` — install, uninstall, init and CI scripts.
- `rules/ui-design.md` — how the admin UI and the portal look: modern product quality, mock first from the real CSS and components, verified in the browser.
- `DESIGN.md` — the personal portal's design system: tokens, components, layout and motion, measured on the live page. Read it before any work on the portal (`web/src/portal`, and what it uses from `web/src/shared`); a change to how the portal looks or moves updates it in the same change.
- `rules/i18n.md` — translations: every visible string and backend message wrapped, the catalogs, the Russian style guide and glossary. Anything added to the admin UI or the portal is localized in the same change; anything removed takes its catalog entries with it.
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
@@ -16,7 +17,7 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
## Layout
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`. `web/i18n/` — the string catalogs' tools (`extract.ts`, `po.ts`, `lmo.ts`).
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; `npm run build` writes the bundles under `package/` (git-ignored: CI builds them before packaging). `web/i18n/` — the string catalogs' tools (`extract.ts`, `po.ts`, `lmo.ts`).
- `package/luci-app-dawnline/po/` — the admin's catalog (`templates/dawnline.pot`, `ru/dawnline.po`): luci.mk builds the `luci-i18n-dawnline-ru` package from it. The portal's catalog is `web/src/portal/i18n/ru.po`, bundled into the portal.
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
@@ -26,7 +27,7 @@ This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its r
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run i18n:check` (after changing visible text: `npm run i18n`, translate the new entries in each `ru.po`), `npm test`, `npm run build` — and commit the rebuilt bundles and the catalogs (CI fails on a changed or new file under `package/`).
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm run lint` (oxlint), `npm run knip` (unused exports and dependencies), `npm run i18n:check` (after changing visible text: `npm run i18n`, translate the new entries in each `ru.po`), `npm test`, `npm run build` — and commit the catalogs (the bundles stay out of git; CI fails when the build leaves a file under `package/` that `.gitignore` does not cover).
- `shellcheck -S warning` for the shell scripts (CI finds them by shebang).
- A tag builds only after CI passes on it (`build.yml` calls `ci.yml`).
+1500
View File
File diff suppressed because it is too large. Load diff
+20 -8
View File
@@ -64,7 +64,7 @@ follows a modern design.
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
2. **Set up** in LuCI: <kbd>Services</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.
@@ -109,7 +109,7 @@ follows a modern design.
<tr>
<td valign="top">
<h3>🏠 Internet like a home device</h3>
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
<p>Turn it on and people's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too. Off by default: it costs speed.</p>
</td>
<td valign="top">
<h3>🗺️ Overview and places</h3>
@@ -315,8 +315,10 @@ By hand: <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>
<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
AmneziaVPN or AmneziaWG on phones and computers, V2RayTun on Android (its
`awg://` link; not with the Maximum disguise, which it cannot
run yet),
and plain WireGuard when the disguise is off. The portal shows each person the app for their system and how
to add the connection in it.
</details>
@@ -378,6 +380,14 @@ are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access
changes reach the tunnel with `awg syncconf`, without restarting the interface;
`dawnline log` on the router shows the service log.
Everything service-related also goes to the router's system log, one line per
event with its syslog priority: `logread -e dawnline` shows
`[info] [service] starting`, `[info] [apply] configuration applied in 310 ms · …`,
tunnels and the portal going down and back, crashes with what syslog knew about
them, every settings change (`admin changed settings · domain: lan → home`) and
people's and devices' changes. Settings → Logs & history → System log picks the
level: errors, warnings, normal or verbose (each step of a start and an apply).
## 🧰 Development
```
@@ -400,19 +410,21 @@ scripts/ build, deploy and check scripts
cd web
npm ci
npm run format # Prettier
npm run ci # format check, types, catalogs, tests, minified bundles
npm run ci # format check, types, lint, unused code, catalogs, tests, minified bundles
npm run i18n # collect new strings into the catalogs (then translate them in ru.po)
scripts/lint-ucode.py # static ucode checks
scripts/check-ucode.sh root@router # compile every ucode file on a router
scripts/deploy.sh root@router # install the working tree (backs up configs first)
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
scripts/capture-screenshots.mjs --demo # the admin's README screenshots from a router, a demo cast in place of its people
scripts/capture-portal.mjs # the portal's from its demo, in English and Russian
scripts/frame-screenshots.py # frame them for this README
```
The web bundles and the catalogs are committed: CI fails when they are out of
date or a string is untranslated (`rules/i18n.md`). Pushing a tag `vX.Y.Z`
The web bundles are built, not committed (`npm run build` before
`scripts/build-packages.sh`); the catalogs are committed, and CI fails when they
are out of date or a string is untranslated (`rules/i18n.md`). Pushing a tag `vX.Y.Z`
(matching `PKG_VERSION`) builds the packages and their translations with the
OpenWrt SDK and publishes a release with `sha256sums.txt`.
+25 -12
View File
@@ -33,7 +33,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
**на какой срок, сколько трафика и в какие часы**.
<p align="center">
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
<a href="https://dawnline-demo.vercel.app"><img src="docs/screenshots/portal-ru.png" alt="Личный портал: устройства и доступ, добавление телефона в три шага" width="860"></a>
<br>
<sub>Личная страница человека: его устройства и доступ. Телефон добавляется в три шага, и страница видит, когда он подключился.
<a href="https://dawnline-demo.vercel.app"><b>Попробуйте в демо</b></a>: ничего не устанавливается и никуда не подключается.</sub>
@@ -65,7 +65,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
2. **Настройте** в LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, дальше по
2. **Настройте** в LuCI: <kbd>Services</kbd> › <kbd>Dawnline</kbd>, дальше по
мастеру. Он предложит порт, публичный адрес и сети.
3. **Пригласите** человека: <kbd>Добавить человека</kbd>, затем отправьте ему
ссылку или карточку приглашения с QR-кодом. Остальное он сделает сам.
@@ -110,7 +110,7 @@ Dawnline запускает сервер [AmneziaWG] на вашем роуте
<tr>
<td valign="top">
<h3>🏠 Интернет как у домашних устройств</h3>
<p>Устройства людей выходят в интернет так же, как домашние, поэтому ваши прокси, фильтры рекламы и DNS работают и для них.</p>
<p>Включите, и устройства людей выйдут в интернет так же, как домашние: ваши прокси, фильтры рекламы и DNS сработают и для них. По умолчанию выключено: это стоит скорости.</p>
</td>
<td valign="top">
<h3>🗺️ Обзор и места</h3>
@@ -161,7 +161,7 @@ flowchart LR
## 📸 Как это выглядит
<p align="center">
<img src="docs/screenshots/overview.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
<img src="docs/screenshots/overview-ru.png" alt="Обзор: кто в сети, скорость, последние 30 дней и откуда подключаются" width="720">
<br>
<sub><b>Обзор</b>: кто в сети, скорость сейчас, последние 30 дней и карта, откуда подключаются.</sub>
</p>
@@ -169,11 +169,11 @@ flowchart LR
<table>
<tr>
<td width="50%" valign="top">
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people.png">
<img alt="Люди: все на сервере, с устройствами, трафиком и состоянием" src="docs/screenshots/people-ru.png">
<p align="center"><sub><b>Люди</b>: в сети, доступ скоро закончится, сверх лимита, вне часов доступа, на паузе.</sub></p>
</td>
<td width="50%" valign="top">
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person.png">
<img alt="Человек: его устройства, трафик, места и лимиты" src="docs/screenshots/person-ru.png">
<p align="center"><sub><b>Человек</b>: его устройства, трафик, места и лимиты.</sub></p>
</td>
</tr>
@@ -318,8 +318,10 @@ sh /tmp/dawnline-uninstall.sh --dry-run
<br>
AmneziaVPN или AmneziaWG на телефонах и компьютерах, а обычный WireGuard, если
маскировка выключена. Портал показывает каждому приложение для его системы и
AmneziaVPN или AmneziaWG на телефонах и компьютерах, V2RayTun на Android (по
ссылке `awg://`; кроме максимальной маскировки, её он пока не
умеет), а
обычный WireGuard, если маскировка выключена. Портал показывает каждому приложение для его системы и
как добавить в нём подключение.
</details>
@@ -382,6 +384,15 @@ AmneziaVPN или AmneziaWG на телефонах и компьютерах,
чаще раза в час. Изменения доступа доходят до туннеля через `awg syncconf`, без
перезапуска интерфейса; `dawnline log` на роутере показывает журнал служб.
Всё, что касается служб, попадает и в системный журнал роутера, строкой на
событие с приоритетом syslog: `logread -e dawnline` покажет
`[info] [service] starting`, `[info] [apply] configuration applied in 310 ms · …`,
падения и восстановление туннелей и портала, сбои с тем, что о них знал syslog,
каждое изменение настроек (`admin changed settings · domain: lan → home`) и
изменения людей и устройств. Уровень выбирается в «Настройки → Журналы и
история → Системный журнал»: ошибки, предупреждения, обычный или подробный
(каждый шаг запуска и применения настроек).
## 🧰 Разработка
```
@@ -404,19 +415,21 @@ scripts/ скрипты сборки, деплоя и
cd web
npm ci
npm run format # Prettier
npm run ci # форматирование, типы, каталоги, тесты, минифицированные бандлы
npm run ci # форматирование, типы, линтер, неиспользуемый код, каталоги, тесты, бандлы
npm run i18n # собрать новые строки в каталоги (затем перевести их в ru.po)
scripts/lint-ucode.py # статические проверки ucode
scripts/check-ucode.sh root@router # скомпилировать все файлы ucode на роутере
scripts/deploy.sh root@router # поставить рабочую копию (сначала сохраняет конфиги)
scripts/build-packages.sh all # .ipk и .apk в OpenWrt SDK в Docker
scripts/capture-screenshots.mjs --demo # скриншоты для README с роутера, с демо-людьми вместо настоящих
scripts/capture-screenshots.mjs --demo # скриншоты админки для README с роутера, с демо-людьми вместо настоящих
scripts/capture-portal.mjs # скриншоты портала для README из его демо, на английском и русском
scripts/frame-screenshots.py # оформить их для README
```
Бандлы и каталоги лежат в репозитории: CI падает, если они устарели или строка
не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
Бандлы не лежат в репозитории, они собираются (`npm run build` перед
`scripts/build-packages.sh`); каталоги лежат, и CI падает, если они устарели или
строка не переведена (`rules/i18n.md`). Тег `vX.Y.Z` (совпадающий с `PKG_VERSION`)
собирает пакеты и переводы в OpenWrt SDK и публикует релиз с `sha256sums.txt`.
---
+2 -2
View File
@@ -1,7 +1,7 @@
# Builds luci-app-dawnline with the OpenWrt SDK.
# docker build -f build/Dockerfile --build-arg SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6 .
# The web bundles (htdocs/.../app.js, portal assets) are built by npm first and
# committed; the SDK only packs files, so the package is the same on every arch.
# The web bundles (htdocs/.../app.js, portal assets) are built by npm first
# (not committed); the SDK only packs files, so the package is the same on every arch.
ARG SDK_IMAGE=itdoginfo/openwrt-sdk-ipk:24.10.6
FROM ${SDK_IMAGE}
Binary file not shown.

After

Width:  |  Height:  |  Size: 446 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 419 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 436 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 363 KiB

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 395 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 187 KiB

After

Width:  |  Height:  |  Size: 186 KiB

+33 -15
View File
@@ -487,18 +487,19 @@ check_tools() {
# ---------- downloads ----------
# fetch_once URL FILE [SECONDS]
# fetch_once URL FILE [SECONDS] [ACCEPT]
fetch_once() {
_fu="$1"
_fd="$2"
_ft="${3:-$DOWNLOAD_TIMEOUT}"
_fa="${4:-}"
rm -f "$_fd"
case "$FETCHER" in
curl)
run_logged download curl -fsSL --connect-timeout "$CONNECT_TIMEOUT" --max-time "$_ft" \
--speed-limit 1024 --speed-time 30 -o "$_fd" "$_fu"
--speed-limit 1024 --speed-time 30 ${_fa:+-H "Accept: $_fa"} -o "$_fd" "$_fu"
;;
*) run_logged download "$FETCHER" -q -T "$CONNECT_TIMEOUT" -O "$_fd" "$_fu" ;;
*) run_logged download "$FETCHER" -q -T "$CONNECT_TIMEOUT" ${_fa:+--header="Accept: $_fa"} -O "$_fd" "$_fu" ;;
esac
_frc=$?
[ "$_frc" -eq 0 ] && [ -s "$_fd" ] && return 0
@@ -531,16 +532,29 @@ asset_digest() {
jsonfilter -i "$1" -e "@.assets[@.name='$2'].digest" 2>/dev/null | head -n 1 | sed -n 's/^sha256:\([0-9a-f]\{64\}\)$/\1/p'
}
# download URL FILE LABEL [SHA256]: direct, then (only when the sha256 is
# known) two mirrors, then direct again. A file whose sha256 doesn't match is
# thrown away and the next source is tried; without a sha256 only GitHub
# itself is used.
# A release file's URL in the GitHub API, from release JSON (empty if unknown).
# Asked for application/octet-stream, it answers with the file itself.
asset_api_url() {
[ -s "$1" ] || return 0
jsonfilter -i "$1" -e "@.assets[@.name='$2'].url" 2>/dev/null | head -n 1 |
sed -n 's#^\(https://api\.github\.com/repos/[^/]*/[^/]*/releases/assets/[0-9][0-9]*\)$#\1#p'
}
# download URL FILE LABEL [SHA256] [API_URL]: without curl the API's URL
# first (github.com's redirect carries a Content-Security-Policy header that
# can outgrow uclient-fetch's 4 KB line buffer, and it stalls there), then
# direct, then (only when the sha256 is known) two mirrors, then direct again.
# A file whose sha256 doesn't match is thrown away and the next source is
# tried; without a sha256 only GitHub itself is used.
download() {
_du="$1"
_dd="$2"
_dl="$3"
_dw="${4:-}"
_da="${5:-}"
[ "$FETCHER" != curl ] || _da=""
set -- "$_du"
[ -z "$_da" ] || set -- "$_da" "$_du"
if [ -n "$_dw" ]; then
for _m in $MIRRORS; do set -- "$@" "$_m$_du"; done
fi
@@ -555,7 +569,9 @@ download() {
sleep 2
msg "Downloading $_dl via $(host_of "$_try") (attempt $_n/$_total)"
fi
if fetch_once "$_try" "$_dd"; then
_acc=""
[ "$_try" != "$_da" ] || _acc="application/octet-stream"
if fetch_once "$_try" "$_dd" "" "$_acc"; then
if [ -n "$_dw" ] && [ "$(sha256sum "$_dd" 2>/dev/null | awk '{ print $1 }')" != "$_dw" ]; then
warn "$(host_of "$_try") sent a file that doesn't match GitHub's sha256: discarded"
rm -f "$_dd"
@@ -1118,10 +1134,11 @@ confirm() {
download_release_file() {
_name="$1"
_sums="$TMP_DIR/sha256sums.txt"
# 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.
_want="$(asset_digest "$TMP_DIR/release.json" "$_name")"
if [ -z "$_want" ]; then
[ -s "$_sums" ] || download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt || {
[ -s "$_sums" ] || download "$ASSET_BASE/sha256sums.txt" "$_sums" sha256sums.txt "" \
"$(asset_api_url "$TMP_DIR/release.json" sha256sums.txt)" || {
err "Download failed: sha256sums.txt (does release $VERSION exist?)"
return 1
}
@@ -1131,7 +1148,7 @@ download_release_file() {
return 1
}
fi
download "$ASSET_BASE/$_name" "$TMP_DIR/$_name" "$_name" "$_want" || {
download "$ASSET_BASE/$_name" "$TMP_DIR/$_name" "$_name" "$_want" "$(asset_api_url "$TMP_DIR/release.json" "$_name")" || {
err "Download failed: $_name"
return 1
}
@@ -1158,7 +1175,8 @@ download_awg() {
_f="$TMP_DIR/$_p$_pf"
# Verified when GitHub publishes the file's sha256 (then mirrors may serve it).
_want="$(asset_digest "$TMP_DIR/awg-$_s.json" "$_p$_pf")"
if download "https://github.com/$_repo/releases/download/v$OWRT_RELEASE/$_p$_pf" "$_f" "$_p ($_repo)" "$_want" &&
if download "https://github.com/$_repo/releases/download/v$OWRT_RELEASE/$_p$_pf" "$_f" "$_p ($_repo)" "$_want" \
"$(asset_api_url "$TMP_DIR/awg-$_s.json" "$_p$_pf")" &&
verify_archive "$_f"; then
_files="$_files $_f"
else
@@ -1425,7 +1443,7 @@ on_pipe() {
lan_url() {
_ip="$(uci -q get network.lan.ipaddr 2>/dev/null | cut -d/ -f1 | awk '{ print $1 }')"
[ -n "$_ip" ] || _ip="192.168.1.1"
printf 'http://%s/cgi-bin/luci/admin/network/dawnline/server' "$_ip"
printf 'http://%s/cgi-bin/luci/admin/services/dawnline/server' "$_ip"
}
main() {
@@ -1495,9 +1513,9 @@ main() {
msg "Log: $LOG_FILE"
msg "Recovery snapshot: $SNAPSHOT_DIR"
if [ "$MODE" = install ]; then
msg "Open LuCI → Network → Dawnline and run the setup wizard:"
msg "Open LuCI → Services → Dawnline and run the setup wizard:"
else
msg "Open LuCI → Network → Dawnline:"
msg "Open LuCI → Services → Dawnline:"
fi
msg " $(lan_url)"
awg_netifd_restart
+1 -1
View File
@@ -6,7 +6,7 @@
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.12.1
PKG_VERSION:=0.18.0
PKG_RELEASE:=1
PKG_LICENSE:=MIT
# po/<lang>/dawnline.po becomes luci-i18n-dawnline-<lang> (luci.mk), released
@@ -1,31 +0,0 @@
// Generated from dawnline/web — do not edit by hand.
'use strict';
'require baseclass';
'require dom';
'require poll';
'require rpc';
'require ui';
var Ha=Object.create;var Go=Object.defineProperty;var za=Object.getOwnPropertyDescriptor;var Ra=Object.getOwnPropertyNames;var Ia=Object.getPrototypeOf,Ba=Object.prototype.hasOwnProperty;var Oa=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ja=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ra(e))!Ba.call(n,r)&&r!==o&&Go(n,r,{get:()=>e[r],enumerable:!(s=za(e,r))||s.enumerable});return n};var Ua=(n,e,o)=>(o=n!=null?Ha(Ia(n)):{},ja(e||!n||!n.__esModule?Go(o,"default",{value:n,enumerable:!0}):o,n));var os=Oa((ts,ns)=>{"use strict";var es=(function(){var n=function(S,$){var b=236,C=17,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 P%2&&R>0?Be.substring(0,Be.length-P-1)+Array(P+1).join("▀"):Be.substring(0,Be.length-1)};return I.createASCII=function(R,O){if(R=R||1,R<2)return ve(O);R-=1,O=typeof O>"u"?R*2:O;var P=I.getModuleCount()*R+O*2,U=O,D=P-O,G,ee,X,be,Le=Array(R+1).join("██"),re=Array(R+1).join(" "),Ie="",Be="";for(G=0;G<P;G+=1){for(X=Math.floor((G-U)/R),Be="",ee=0;ee<P;ee+=1)be=1,U<=ee&&ee<D&&U<=G&&G<D&&I.isDark(X,Math.floor((ee-U)/R))&&(be=0),Be+=be?Le:re;for(X=0;X<R;X+=1)Ie+=Be+`
`}return Ie.substring(0,Ie.length-1)},I.renderTo2dContext=function(R,O){O=O||2;for(var P=I.getModuleCount(),U=0;U<P;U++)for(var D=0;D<P;D++)R.fillStyle=I.isDark(U,D)?"black":"white",R.fillRect(U*O,D*O,O,O)},I};n.stringToBytesFuncs={default:function(S){for(var $=[],b=0;b<S.length;b+=1){var C=S.charCodeAt(b);$.push(C&255)}return $}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(S,$){var b=(function(){for(var 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 hi(n){let e=new Map(n.people.map(s=>[s.id,s.name])),o=new Map(n.people.flatMap(s=>s.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Qe(n,e,o,s="",r=[]){let a=hi(n),i=[...e.map(u=>({ts:u.ts,category:qt(u.type),type:u.type,person:u.person?a.people.get(u.person)??u.pname??u.person:"",device:u.device?a.devices.get(u.device)??u.dname??u.device:"",detail:u.detail??"",where:u.where??"",by:Ve(u)??""})),...r.map(u=>({ts:u.ts,category:"system",type:`${u.src}.${u.level}`,person:"",device:"",detail:`${u.who?`${u.who} `:""}${u.msg}${u.detail?`
${u.detail}`:""}`,where:Ft(u.src),by:""}))].sort((u,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: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(`
`),d=t("div",{class:"dl-pgrid"},[r(_("Junk packets"),"zap",a?m(N_(a,"%s random packet of %s–%s bytes before each handshake.","%s random packets of %s–%s bytes before each handshake."),K(a),n.jmin,n.jmax):_("No junk packets."),["jc","jmin","jmax"]),r(_("Padding"),"archive",_("Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard."),["s1","s2","s3","s4"]),r(_("Packet types"),"key",_("The values that replace WireGuard’s recognisable message types."),["h1","h2","h3","h4"]),r(_("Signatures"),"globe",i,["i1","i2","i3","i4","i5"]),r(_("Protection"),"lock",_("AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets."),["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r(_("Timing"),"clock",_("Handshake and key timers vary within these ranges instead of WireGuard’s fixed values."),["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},_("Current parameters")),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),xe(l,_("Parameters copied"))}},_("Copy as config"))]),d])}function Hs(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let s=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",s&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Li(n){let e=!1,o=t("pre",{class:"dl-conf"}),s=()=>dom.content(o,n.conf.split(`
`).flatMap((i,l)=>l?[`
`,Hs(i,e)]:[Hs(i,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?_("Hide key"):_("Show key")]),s()}},[v("key"),_("Show key")]);s();let a=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${W(a,"%s byte","%s bytes")}`)]),A([v("download")," ",_("Download")],()=>Ne(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},_("Configuration")),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:i=>{i.preventDefault(),xe(n.conf,_("Configuration copied"))}},[v("copy"),_("Copy")])]),o])])}function ho(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([s,r])=>r==null||r===""||r===(o[s]??"0"))}async function Mi(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},_("This device generated its own keys in the browser, so its full configuration only exists on that device."));let o=await mo(n,n.server),s={qr:()=>t("div",{class:"dl-qr-pane"},[un(n.conf),t("span",{class:"dl-sub"},ho(n)?_("Scan with AmneziaVPN or any WireGuard app on the device."):_("Scan with AmneziaVPN or AmneziaWG on the device."))]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),A(_("Copy"),()=>xe(o,_("Key copied")))]),t("span",{class:"dl-sub"},m(_("AmneziaVPN → %s. Keep it private."),["+",_("Insert","AmneziaVPN app"),_("Continue","AmneziaVPN app")].join(" → ")))]),file:()=>Li(n)},r=t("div",{class:"dl-connect-body"}),a=t("div",{class:"dl-seg"}),i=l=>{a.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(r,s[l]())};for(let[l,d]of[["file",_("File")],["key",_("Key")],["qr",_("QR code")]])a.appendChild(t("button",{type:"button","data-id":l,click:()=>i(l)},d));return i(e),t("div",{class:"dl-stack gap12"},[a,r])}async function Ei(n,e,o,s){let r=Kt(o),i=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await me(s?_("Generate new disguise values?"):m(_("Switch to %s?"),r.title),[W(i,"%s AmneziaWG device stops connecting until it imports its configuration again (from their personal link or from you).","%s AmneziaWG devices stop connecting until they import their configuration again (from their personal link or from you)."),o==="max"?_("They need an app with AmneziaWG 3.1."):o==="balanced"?_("They need an app with AmneziaWG 2.0 or newer."):"",n.st.servers.length===1&&i?_("To keep the old disguise for some people, add a second server and move them there."):""].filter(Boolean).join(" "),s?_("Generate and apply"):_("Switch and apply"),!0)&&await F(()=>N.serverObfuscation(e.id,o),s?_("New values applied"):m(_("%s applied"),r.title))&&(q(_("Devices are marked “Update config” until they import again."),"info",6e3),await n.refresh())}function Ti(n,e){let o=n.st,s=he(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=he(e.mtu?String(e.mtu):"",{placeholder:_("Auto"),inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=he(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=Kt(e.preset)?e.preset:void 0,l=i??wn(o.awg),d=A("",()=>Ei(n,e,l,l===i),"neutral"),c=()=>dom.content(d,l===i?[v("reset")," ",_("Generate new values")]:[m(_("Switch to %s"),Kt(l).title)]);c();let p=o.awg_state?.tools!==!1,u=[],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"),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(`
`),T&&(p.scrollTop=p.scrollHeight)}if(l.textContent=_r(x,e.version??""),!l.isConnected&&l.textContent&&i.after(l),c.textContent=kr((x.finished??C.now)-x.started),x.state==="running"){d.hidden=!x.phase,d.textContent=x.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent=_("No answer"),dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},_("The router stopped answering. The job may still finish: reopen Components in a minute."))])),g([h()]),e.onDone?.(C),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent=_("Failed"),dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},(E.error??_("Operation failed")).replace(/\.$/,"")),r?"":`. ${_("Nothing else was changed.")}`])])),g([A(_("Copy log"),()=>xe(M.join(`
`),_("Log copied"))),h(!0)]),q(`${Dn(s)??_("Update","noun")}: ${E.error??_("failed")}`,"error"),e.onDone?.(C),E;if(d.className="dl-pill ok",d.textContent=_("Finished"),r&&C){let x=Cr(C,s);if(dom.content(u,t("div",{class:`dl-comp-status ${x.tone}`},[v(x.tone==="ok"?"check":x.tone==="warn"?"alert":"download"),t("span",{},x.text)])),q(x.text,x.tone==="warn"?"warning":"success"),e.onDone?.(C),x.update&&e.onUpdate){let T=C;g([h(),A(m(_("Update to %s"),x.update),()=>e.onUpdate(T),"positive")])}else g([h()]),x.tone==="ok"&&setTimeout(()=>u.isConnected&&ce(),1200);return E}let z=/^app:(lang:|nolang$)/.exec(E.component??"");if(z){let x=()=>{ui.menu?.flushCache(),location.reload()};return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},z[1]==="nolang"?_("The translation is removed."):_("The translation is installed."))," ",_("Reloading the page…")])])),g([h(),A(_("Reload now"),x,"positive")]),await $o(4e3),u.isConnected&&x(),E}if(s==="app"&&E.to){let x=E.to,T=t("span",{},_("Waiting for the router to restart its services…"));dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},m(_("Dawnline %s is installed."),x))," ",T])]));let I=()=>{ui.menu?.flushCache(),location.reload()};g([h(),A(_("Reload now"),I,"positive")]),q(m(_("Dawnline updated to %s"),x),"success",6e3);for(let 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
`).map(e=>At(e)).join(`
`);function Hn(n,e,o,s){let r=n.by==="admin",a=At(n.msg),i=t("div",{class:`dl-row dl-slog-row ${r?"dl-ev-by-admin":`dl-ev-by-system ${dl[n.level]??""}`}${n.detail?" has-detail":""}`},[r?t("span",{class:"dl-ev-tile",title:_("Done by you in LuCI")},v("admin")):t("span",{class:"dl-ev-tile sys",title:pl(n.level)},v(cl[n.src]??"zap")),t("span",{class:"dl-row-main"},r?[...ul(n),n.note?t("span",{class:"dl-muted"},` · ${Ms(n.note)}`):"",n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]:[n.src==="awg"&&n.who&&n.who!=="AmneziaWG"?t("span",{class:"dl-ev-kind"},`${_("Server")} `):"",t("b",{class:"dl-sys-src",title:Ft(n.src)},n.who?n.src==="awg"?n.who:At(n.who):Ft(n.src)),/^[:,]/.test(a)?"":" ",t("span",{class:"dl-muted"},a),n.detail?t("span",{class:`dl-slog-more${e?" open":""}`},v("chevron")):"",n.detail&&e?t("pre",{class:"dl-slog-detail"},Sr(n.detail)):""]),t("span",{class:"dl-faint dl-nowrap",title:new Date(n.ts*1e3).toLocaleString(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
`)){let d=l.trimEnd();if(a){/^```/.test(d.trim())?(e.push(t("pre",{},a.join(`
`))),a=null):a.push(l);continue}if(/^```/.test(d.trim())){i(),a=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(i(),e.push(t("h5",{},o(c[2])))):p?(r.length&&i(),s||(s=t("ul",{}),e.push(s)),s.appendChild(t("li",{},o(p[1])))):d.trim()?(s&&(s=null),r.push(d.trim())):i()}return a&&e.push(t("pre",{},a.join(`
`))),i(),e}function Kr(n){let e=[],o=!1;for(let s of n.replace(/\r/g,"").split(`
`)){let r=/^#{1,6}\s+(.*)$/.exec(s);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(s)&&(o=!1);o||e.push(s)}return e.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function sn(n,e,o,s){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},_("Loading release notes…"))),a=t("div",{class:"dl-op-head"}),i="";de(o,[a,r],[A([v("copy")," ",_("Copy")],()=>xe(i,_("Release notes copied")))," ",ue(_("Close"))],"wide");try{let l=await N.updatesNotes(n,e,s??"");i=Kr(l.body||"");let d=qr(l.url);dom.content(a,[l.published?t("span",{class:"dl-pill"},Oe(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},_("Pre-release")):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},[_("On GitHub")," ",v("open")]):""]),dom.content(r,i.trim()?Fr(i):t("p",{class:"dl-muted"},_("This release has no notes.")))}catch(l){dom.content(r,t("p",{class:"dl-muted"},Ce(l)))}}function yl(n){let e={"6h":_("checks every 6 h"),"12h":_("checks every 12 h"),"1d":_("checks daily"),"7d":_("checks weekly")};return e[n]??e["1d"]}var Ro=n=>n?Oe(n):"";function kl(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Vr(n,e){let o=n.st,s=o.policy,r=o.kept?.app,a=e?.update&&e.tag?e.tag:o.version,i=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);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+=c-1}let i=A([v("more")],()=>Se(i,[{label:_("Export CSV"),icon:v("download"),run:()=>Qe(o,s,"csv",e.id)},{label:_("Export JSON"),icon:v("download"),run:()=>Qe(o,s,"json",e.id)},null,{label:m(_("Clear %s's activity"),e.name),icon:v("trash"),danger:!0,run:()=>lt(m(_("Clear %s's activity"),e.name),m(_("Removes events about %s and their devices."),e.name),{person:e.id},()=>n.refresh())}]),"neutral",{title:_("Export or clear"),class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},_("Activity")),t("span",{class:"dl-sub"},s.length>10?m(_("latest 10 of %s"),K(s.length)):""),t("span",{class:"dl-spacer"}),i]),r.length?r:t("div",{class:"dl-row dl-muted"},_("Nothing yet."))])}var Gn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,s,r]=await Promise.all([N.status(30),e?N.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?N.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:s?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(i=>i.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},_("Person not found")),t("p",{},_("They may have been removed.")),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},_("Back to Servers"))]);this.p=o;for(let i of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[i]=t("div",{});this.parts.devices.className="dl-person-devices";let s=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),a=r.get("device")&&o.devices.find(i=>i.id===r.get("device"));return a?setTimeout(()=>Je(this.p,a,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>ct(this.p,this.deviceOpts()),50),this.poller=pt({fetch:i=>{let l=i||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>s.isConnected,apply:(i,l)=>this.apply(i,l)}),s}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let s=this.st.people.find(r=>r.id===this.id);if(!s){o||(location.href=It(this.p?.server));return}this.p=s,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var a;this.poller?.claim();let s=await F(()=>N.personUpdate(this.p.id,e),o);if(!s)return!1;this.poller?.claim();let r=this.st.people.findIndex(i=>i.id===this.p.id);return(a=s.person).rate??(a.rate=this.p.rate),r>=0&&(this.st.people[r]=s.person),this.p=s.person,this.paint(),!0}get today(){return Ge(this.series.length?this.series:this.st.series)}get core(){return zt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":_("Breadcrumb")},[t("a",{href:It(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??_("Servers")),t("span",{},"/"),t("a",{href:It(e.server)},_("People")),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Ae(this.parts.crumbs,this.crumbs(),e),Ae(this.parts.head,aa(this),e),Ae(this.parts.traffic,ia(this),e),Ae(this.parts.devices,la(this),e),Ae(this.parts.limits,fa(this),e),this.paintPlaces(e),Ae(this.parts.activity,va(this),e)}paintPlaces(e=!1){let o=ga(this);o&&Ae(this.parts.places,o,e&&!this.mapOpen)}};var zl={ok:"check",warn:"alert",error:"x",skip:"pause"},qn=class{constructor(e,o,s,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=s,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,s)}async run(e){let o=e?await In(e):await N.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},_("Checks"))]),t("p",{class:"dl-muted dl-loading"},_("Running checks…"))]);return}let o=e.filter(i=>i.status==="error").length,s=e.filter(i=>i.status==="warn").length;dom.content(this.summary,o?bt("error",W Line truncated
`);function Aa(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=td,n}function yt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async s=>{let r=await e.render(s),a=document.createElement("div");return a.className="dl-root",a.append(Aa(),r),a},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Jb=yt(on),Zb=yt(wt),Qb=yt(on),Xb=yt(On),e0=yt(Gn),t0=yt(Yn),n0=yt(Wn);function Na(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var o0=Na(""),s0=Na("log");return baseclass.extend({ activity: s0, diagnostics: t0, health: o0, overview: Jb, people: Zb, person: e0, server: Qb, settings: Xb, updates: n0 });
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -8,15 +8,33 @@ USE_PROCD=1
PORTAL_ROOT=/usr/share/dawnline/portal/www
# A line in syslog as dawnline.util syslog() writes them: "dawnline: [info] [service] …" at the
# matching priority, when the admin's level (settings.log_level: error|warn|info|debug) takes it.
log() {
local lvl="$1" want rank prio
shift
want="$(uci -q get dawnline.settings.log_level)"
case "$lvl" in error) rank=0 prio=err ;; warn) rank=1 prio=warning ;; debug) rank=3 prio=debug ;; *) rank=2 prio=info ;; esac
case "$want" in error) want=0 ;; warn) want=1 ;; debug) want=3 ;; *) want=2 ;; esac
[ "$rank" -le "$want" ] || return 0
logger -t dawnline -p "daemon.$prio" "[$lvl] [service] $*"
}
start_portal() {
local enabled port certs cert key hport http
config_get_bool enabled settings portal_enabled 0
[ "$enabled" = 1 ] || return 0
if [ "$enabled" != 1 ]; then
log info "personal portal is off"
return 0
fi
config_get port settings portal_port 8443
certs="$(/usr/bin/dawnline portal-cert 2>/dev/null)"
cert="${certs% *}"
key="${certs#* }"
[ -f "$cert" ] && [ -f "$key" ] || return 0
if ! [ -f "$cert" ] || ! [ -f "$key" ]; then
log warn "personal portal not started: no certificate (${cert:-none}): choose one in Settings, or save the portal settings again"
return 0
fi
# IP addresses in links get plain HTTP on the next port (names stay HTTPS-only).
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
@@ -34,23 +52,30 @@ start_portal() {
procd_set_param file "$cert"
procd_set_param respawn 3600 5 0
procd_close_instance
log info "personal portal on port $port (HTTPS${hport:+, plain HTTP on $hport for links with an IP address}) · certificate $cert$(openssl x509 -enddate -noout -in "$cert" 2>/dev/null | sed 's/^notAfter=/ until /') · $procs processes"
}
# Plain DNS for Home-only tunnel devices (config written by `dawnline apply`).
start_resolver() {
[ -f /var/etc/dawnline-dns.conf ] || return 0
if ! [ -f /var/etc/dawnline-dns.conf ]; then
log debug "no DNS for Home-only devices (nobody needs it)"
return 0
fi
procd_open_instance dns
procd_set_param command /usr/libexec/dawnline/resolver
procd_set_param file /var/etc/dawnline-dns.conf
# A new config kills it (dawnline.resolver): back within a second, not five.
procd_set_param respawn 3600 1 0
procd_close_instance
log info "DNS for Home-only devices started (/var/etc/dawnline-dns.conf)"
}
start_service() {
config_load dawnline
mkdir -p /var/run/dawnline
/usr/bin/dawnline apply >/dev/null 2>&1
log info "starting"
# The apply writes its own lines: what it came to and how long it took (each step at debug).
/usr/bin/dawnline apply >/dev/null 2>&1 || log error "applying the configuration failed: run \"dawnline apply\" to see why"
procd_open_instance agent
procd_set_param command /usr/libexec/dawnline/agent
@@ -60,10 +85,12 @@ start_service() {
start_portal
start_resolver
log info "started"
}
# Noted for the service log: the next agent start is a restart, not a crash or a boot.
stop_service() {
log info "stopping"
mkdir -p /var/run/dawnline
date +%s > /var/run/dawnline/agent.stopped
# Copies procd doesn't know about (started by hand, or left by an older version) go too.
@@ -71,10 +98,15 @@ stop_service() {
}
reload_service() {
/usr/bin/dawnline apply >/dev/null 2>&1
log info "reloading: settings changed"
/usr/bin/dawnline apply >/dev/null 2>&1 || log error "applying the configuration failed: run \"dawnline apply\" to see why"
start
}
service_triggers() {
procd_add_reload_trigger dawnline
# The portal's uhttpd reads its certificate once: an issued or renewed one needs a
# reload (procd restarts the portal alone, its cert file having changed).
procd_add_raw_trigger acme.issue 5000 /etc/init.d/dawnline reload
procd_add_raw_trigger acme.renew 5000 /etc/init.d/dawnline reload
}
@@ -15,7 +15,7 @@ import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import { L_ } from 'dawnline.i18n';
import {
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
VERSION, slog, syslog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util';
/** Options that take no value. */
@@ -338,5 +338,7 @@ try {
}
catch (e) {
warn(`dawnline: ${e.message}\n`);
// Run from the init script or cron, stderr goes nowhere: syslog keeps why.
syslog('error', 'cli', `dawnline ${cmd} failed: ${e.message}`);
exit(1);
}
@@ -2,7 +2,11 @@
// Dawnline agent (procd instance). Every second its watcher reads the tunnels
// and, the moment a device connects, its session expires or it roams, logs
// it, folds the counters, locates the new address and moves the revision the
// admin UI polls (presence.json, see dawnline.live). Every minute it:
// admin UI polls (presence.json, see dawnline.live). The same read tells when
// a device's link fails in a named way (link.json, dawnline.link), what it does
// right now for the portal's set-up sheet (setup.json) and the live meter's
// last two minutes, written out while someone looks (meter.json, dawnline.meter).
// Every minute it:
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
// * saves the activity log to flash as often as Settings says (or never)
// * keeps the "like a home device" path and the Home-only resolver up
@@ -13,7 +17,7 @@
import * as uloop from 'uloop';
import { open, readfile, writefile, stat, unlink } from 'fs';
import {
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, syslog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
@@ -26,6 +30,9 @@ import * as net from 'dawnline.net';
import * as store from 'dawnline.store';
import * as upd from 'dawnline.updates';
import * as awg from 'dawnline.awg';
import * as builds from 'dawnline.awg_builds';
import * as link from 'dawnline.link';
import * as meter from 'dawnline.meter';
import { L_ } from 'dawnline.i18n';
const TICK = 60 * 1000;
@@ -55,6 +62,12 @@ let last_states = null;
// Who was online, kept in tmpfs so an agent restart (update, reload) does not
// swallow connects that happened in between.
let presence = read_json(live.PRESENCE, {});
// What a link showed comes from the watcher's memory, which starts empty: a
// state shows again once it held (link.HOLD), a set-up state with the next
// read that tells it. The meter's points start again too, written at the next look.
write_json(live.LINK, {}, 0o600);
write_json(live.SETUP, {}, 0o600);
meter.stop();
let last_online = presence.online ?? {};
let last_endpoint = presence.endpoint ?? {};
let rev = +(presence.rev ?? 0);
@@ -123,6 +136,8 @@ function record_rate(m) {
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
}
let last_sync = 0;
// Per server, how the agent's last sync of its devices went (dawnline.awg.sync_peers).
let last_peers = {};
let conf_mtime = null;
let cert_mtime = null;
@@ -166,22 +181,104 @@ function named(e) {
/* ---------- the watcher ---------- */
// Per device: its latest real handshake, kept when apply re-adds the peer
// (its counters and handshake restart from zero, or it is briefly missing).
let last_hs = {};
// The model, read again only when the config file changes (the watcher runs every second).
let wm = null, wm_sig = null;
// (its counters and handshake restart from zero, or it is briefly missing),
// and the public key it was seen with: new keys (Reconnect, New keys) end
// the old session, whatever its handshake said.
let last_hs = {}, last_key = {};
// The model, read again only when the config file changes (the watcher runs
// every second), the tunnels it reads (live.tunnel_ifnames: a regex per
// server, compiled each time it runs, so not every second), each device's
// online window (live.online_windows: its keep-alive's, from the model) and
// the largest keepalive its server's disguise makes (link.keepalive_sizes).
let wm = null, wm_sig = null, wm_ifnames = [], wm_windows = {}, wm_ka = {};
// netifd deletes and adds a tunnel's link each time it sets it up (a new
// ifindex): the devices come back only with the sync its hotplug starts, and
// then with no handshake until each one makes a new one. For this long after
// the link changed, a device missing from it keeps what was known of it,
// rather than a burst of disconnects and connects for everyone online.
const RESTART_GRACE = 45;
// Per tunnel: the link last seen (null while it is down), and until when its grace lasts.
let links = {}, grace = {};
/** A file's mtime and inode ('-' when it is missing): what the cached model depends on. */
function file_sig(path) {
let st = stat(path);
return st ? `${st.mtime}/${st.inode}` : '-';
}
function watch_model() {
// uci commits replace the file: a new inode even within the same second.
let st = stat(CONFIG_FILE);
let sig = st ? `${st.mtime}/${st.inode}` : null;
// Which servers are kept down (core.BLOCKED, written by apply) is in the
// model too: their interface names may be someone else's tunnels.
let sig = `${file_sig(CONFIG_FILE)} ${file_sig(core.BLOCKED)}`;
if (wm == null || sig != wm_sig) {
wm = core.load();
wm_sig = sig;
wm_ifnames = live.tunnel_ifnames(wm);
wm_windows = live.online_windows(wm);
wm_ka = link.keepalive_sizes(wm);
}
return wm;
}
// Per device: how its link behaves (dawnline.link: a few recent events and
// what is shown), and whether what is shown (link.json) or the set-up states
// (setup.json) changed since they were written.
let link_hist = {}, link_dirty = false, setup_dirty = false;
/**
* A device's read into its link history: its set-up state follows at once
* (link.setup, a few compares unless something happened); it is classified
* again when something happened or link.CHECK_EVERY passed (its spans age).
* Returns the change in what is shown (link.settle: { from, to }), or null.
*/
function watch_link(id, dev, peer, now, on) {
let h = link_hist[id] ??= link.fresh(now);
let moved = false;
if (peer)
moved = link.observe(h, peer, now, wm_ka[id] ?? link.KEEPALIVE);
else
link.gone(h);
if (link.setup(h, now, on, moved))
setup_dirty = true;
if (!moved && now - h.checked < link.CHECK_EVERY)
return null;
h.checked = now;
link.prune(h, now);
h.raw = link.classify(h, now, on);
let change = link.settle(h, h.raw, now, on);
if (change)
link_dirty = true;
return change;
}
// The live meter: the last sample and the last two minutes of points
// ([ ts, JSON ], newest last, meter.keep), kept whether anyone looks or not so
// that a look gets them at once; whether meter.json is out for a look now.
let meter_prev = null, meter_ring = [], meter_out = false;
/**
* A meter point a second from this read, kept; meter.json written while
* someone looks (meter.wanted): all the points the first second of a look,
* then with each new one. Once nobody does, the file goes; the points stay.
*/
function watch_meter(m, d, now) {
let s = meter.sample(m, d, now);
let p = meter_prev ? meter.point(meter_prev, s) : null;
meter_prev = s;
if (p)
meter.keep(meter_ring, p);
if (!meter.wanted(now)) {
if (meter_out)
meter.stop();
meter_out = false;
return;
}
if (p || !meter_out)
meter.save(meter_ring);
meter_out = true;
}
/** Move the revisions (all, and these people's) and save who is online. */
function save_presence(people) {
rev++;
@@ -303,43 +400,89 @@ function place_of(ip) {
/*
* One look at the tunnels. Connects (a new handshake from a device that was
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
* a phone asleep looks the same as one switched off, so silence alone is not
* enough) and roaming (a new address) are acted on at
* once: the log, the counters and the map, then the revision the UI polls.
* Only from a complete read: a failed one says nothing about anyone.
* away), disconnects (its session expired: no handshake within its online
* window, live.online_window; a phone asleep looks the same as one switched
* off, so silence alone is not enough) and roaming (a new address) are acted
* on at once: the log, the counters and the map, then the revision the UI polls.
* Only Dawnline's own tunnels are read, each on its own (one process with a
* single server): a tunnel that could not be read says nothing about its
* devices, which stay as they were.
*/
function watch() {
let d = awg.dump();
if (!d.ok)
return;
let m = watch_model();
let d = awg.dump(wm_ifnames);
let now = time();
let events = [], people = {}, ips = [];
for (let ifn, r in d.reads) {
if (r == 'error')
continue;
let ix = d.ifaces[ifn]?.ifindex;
if (ifn in links && links[ifn] != ix)
grace[ifn] = now + RESTART_GRACE;
links[ifn] = ix;
}
for (let ifn in keys(links))
if (!(ifn in d.reads)) {
delete links[ifn];
delete grace[ifn];
}
let events = [], people = {}, ips = [], failing = [];
for (let id, dev in m.devices) {
let ifn = m.servers[m.people[dev.person]?.server]?.ifname;
if (d.reads[ifn] == 'error')
continue;
let peer = d.peers[dev.public_key];
let ep = '';
// New keys: offline until they shake hands, and a new link history. The
// old one's set-up session (its no data, or its data flowing) and its
// answers would otherwise be taken for the new configuration's.
if (last_key[id] != dev.public_key) {
if (last_key[id] != null) {
last_hs[id] = 0;
let h = link_hist[id];
if (h?.state != null) {
link_dirty = true;
people[dev.person] = true;
}
if (h?.setup != null)
setup_dirty = true;
delete link_hist[id];
}
last_key[id] = dev.public_key;
}
if (peer) {
last_hs[id] = max(last_hs[id] ?? 0, peer.handshake);
ep = live.endpoint_ip(peer.endpoint);
}
// Not in the tunnel (turned off, paused, out of time or data): offline now, and online
// again only with a new handshake, not the one remembered from before.
else
// again only with a new handshake, not the one remembered from before. Unless its
// tunnel was just set up again and the sync has not brought it back yet.
else if (!(grace[ifn] > now))
last_hs[id] = 0;
let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
let on = last_hs[id] > 0 && now - last_hs[id] < (wm_windows[id] ?? live.ONLINE_WINDOW);
let was = last_online[id];
// What is shown changed: the person's pages read it again (link.json), also
// when it cleared without an event (the device stopped trying, or was paused).
let change = watch_link(id, dev, peer, now, on);
if (change) {
people[dev.person] = true;
let le = link.event_for(change, dev, on);
if (le)
push(failing, le);
}
// One configuration on two devices: its address goes back and forth all
// the time, which is no roaming (nor a reason to move the revision).
let flapping = link_hist[id].raw == 'shared' || link_hist[id].state == 'shared';
if (on && !was) {
push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
push(ips, ep);
}
else if (!on && was)
push(events, { type: 'disconnect', person: dev.person, device: id });
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) {
else if (on && ep && last_endpoint[id] && ep != last_endpoint[id] && !flapping) {
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
push(ips, ep);
}
if (on != !!was || (ep && ep != last_endpoint[id]))
if (on != !!was || (ep && ep != last_endpoint[id] && !flapping))
people[dev.person] = true;
last_online[id] = on;
if (ep)
@@ -350,7 +493,29 @@ function watch() {
delete last_online[id];
delete last_endpoint[id];
delete last_hs[id];
delete last_key[id];
}
for (let id in keys(link_hist))
if (!m.devices[id]) {
if (link_hist[id].state != null)
link_dirty = true;
if (link_hist[id].setup != null)
setup_dirty = true;
delete link_hist[id];
}
if (link_dirty) {
write_json(live.LINK, link.shown(link_hist), 0o600);
link_dirty = false;
}
// The portal's set-up sheet polls for it: no revision moves with it.
if (setup_dirty) {
write_json(live.SETUP, link.setups(link_hist), 0o600);
setup_dirty = false;
}
// Merged per device for an hour: a link that keeps failing and coming back is one line.
for (let e in failing)
live.add_event_merged(e, 3600);
watch_meter(m, d, now);
if (!length(keys(people)))
return;
save_presence(keys(people));
@@ -476,8 +641,9 @@ function nightly_backup() {
let st = read_json(`${DATA_DIR}/backup-state.json`, {});
if (sum && sum != st.auto) {
try {
backup.backup_create('auto');
let b = backup.backup_create('auto');
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
syslog('info', 'backup', `nightly backup saved${b ? ': ' + b : ''}`);
}
catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
@@ -515,8 +681,9 @@ function check_usage_reset(m) {
* Push devices and access rules when people's states changed, the config
* file was written (by anyone: rpcd, the portal, the CLI, a restore), the
* access table is gone (a flushed ruleset: the firewall alone would let every
* device reach everything, so the sync unloads them until it is back), or
* every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
* device reach everything, so the sync unloads them until it is back), a
* running tunnel holds other devices than it should (check_peers), or every
* RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
*/
function sync_runtime(t) {
// uci commits replace the file: a new inode even within the same second.
@@ -525,13 +692,32 @@ function sync_runtime(t) {
let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
(conf_mtime != null && mt != conf_mtime);
if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
apply.sync(t.m, usage);
last_peers = apply.sync(t.m, usage).peers ?? {};
last_sync = time();
}
conf_mtime = mt;
last_states = t.states;
}
/*
* A running tunnel without all of its devices, or with ones it should not
* have (set up again before its hotplug sync ran, an `awg set` by hand): the
* sync runs on this tick, not up to RESYNC_EVERY later. By the same choice
* of devices the sync makes (and Health compares); only where the agent's
* last sync took: a server that refuses its devices has said so in the
* service log and keeps the slower pace.
*/
function check_peers(t) {
for (let id, srv in t.m.servers) {
let last = last_peers[id] ?? 'ok';
if (t.dmp?.reads?.[srv.ifname] != 'read' || (last != 'ok' && last != 'down'))
continue;
let diff = awg.peer_diff(awg.tunnel_devices(t.m, id, t.states), t.dmp, srv.ifname);
if (diff.missing || diff.extra)
last_sync = 0;
}
}
/*
* The router's network changed under us: re-derive everything. Only a change
* seen on two ticks in a row (a bridge recreated or an interface restarting
@@ -568,7 +754,8 @@ const STEPS = [
} },
{ who: L_('Traffic'), run: (t) => {
t.reset = check_usage_reset(t.m);
live.collect(t.m, usage, live.dump(t.m));
t.dmp = live.dump(t.m);
live.collect(t.m, usage, t.dmp);
} },
{ who: L_('Speed'), quiet: true, run: (t) => record_rate(t.m) },
{ who: L_('People'), run: (t) => {
@@ -577,7 +764,9 @@ const STEPS = [
check_expiry(t.m, t.events);
} },
{ who: L_('Access rules'), run: (t) => {
if (t.states)
if (!t.states)
return;
check_peers(t);
sync_runtime(t);
} },
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
@@ -606,9 +795,11 @@ function step(i, s, fn) {
delete step_err[i];
}
catch (e) {
system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
// A new error goes to the service log (and from there to syslog); a repeat, or a quiet step's, to syslog alone.
if (!s.quiet && step_err[i] != e.message)
slog('dawnline', 'error', sprintf(L_('failed: %s'), e.message), e.stacktrace?.[0]?.context, s.who);
else
syslog('error', 'agent', `${s.who}: ${e.message}`);
step_err[i] = e.message;
}
}
@@ -624,7 +815,7 @@ function tick() {
}
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
let t = { m: null, pol: null, reset: false, events: [] };
let t = { m: null, pol: null, reset: false, events: [], dmp: null };
for (let i, s in STEPS)
if (i == 0 || t.m)
step(i, s, () => s.run(t));
@@ -647,11 +838,20 @@ function tick() {
});
}
// Once: a signal ends the loop and calls it, and so does the line after uloop.run().
let stopping = false;
function shutdown() {
if (stopping)
return;
stopping = true;
syslog('info', 'agent', 'stopping · saving the counters and the logs');
live.save_usage(usage, true);
live.persist_events();
geo.flush();
slog_trim(true);
// The live meter's file goes with it: a stopped agent's points are no speed now.
meter.stop();
// A clean stop: the next start is not a crash.
unlink(watchdog.BEAT);
}
@@ -686,6 +886,10 @@ else if (live.uptime() < 600)
slog('dawnline', 'info', sprintf(L_('started with the router · version %s'), VERSION), null, 'Dawnline');
else
slog('dawnline', 'info', sprintf(L_('started · version %s'), VERSION), null, 'Dawnline');
syslog('debug', 'agent', sprintf('watching connections every %d ms, checking the rest every %d ms', WATCH, TICK));
// A module Dawnline did not install has no record of its kernel: without one
// Health cannot tell a firmware upgrade from a missing module.
builds.adopt();
uloop.init();
@@ -29,4 +29,4 @@ else detail="It never completed a check."; fi
msg="stopped responding — restarted"
mkdir -p /var/run/dawnline
printf '{"ts":%s,"src":"dawnline","level":"repair","who":"Dawnline","msg":"%s","detail":"%s"}\n' "$now" "$msg" "$detail" >> /var/run/dawnline/service.log
logger -t dawnline "Dawnline $msg"
logger -t dawnline -p daemon.warning "[warn] [agent] Dawnline $msg - $detail"
@@ -31,13 +31,13 @@ while [ "$i" -lt 12 ]; do
up && exit 0
done
logger -t dawnline "update to $to failed its check: luci.dawnline or the agent is not up"
logger -t dawnline -p daemon.err "[error] [update] update to $to failed its check: luci.dawnline or the agent is not up"
set --
for f in "$KEEP"/*.ipk "$KEEP"/*.apk; do
[ -f "$f" ] && set -- "$@" "$f"
done
if [ "$#" -eq 0 ]; then
logger -t dawnline "no previous version is kept: nothing to roll back to"
logger -t dawnline -p daemon.err "[error] [update] no previous version is kept: nothing to roll back to"
exit 1
fi
if command -v apk >/dev/null 2>&1; then
@@ -50,5 +50,5 @@ fi
mkdir -p "$RUN"
# The restored agent reports it in the service log on its start.
echo "$to" > "$RUN/update-rolled-back"
logger -t dawnline "rolled back from $to to the kept version"
logger -t dawnline -p daemon.warning "[warn] [update] rolled back from $to to the kept version"
exit 0
@@ -24,6 +24,25 @@ import * as pkgs from 'dawnline.upd_pkgs';
import * as i18n from 'dawnline.i18n';
import { _, L_ } from 'dawnline.i18n';
const USAGE = `Usage:
updater check [app|amneziawg|packages]
updater install app | app@<tag> | app:reinstall | app:rollback
updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
updater install pkgs:<name,…>
updater auto
`;
// No command, one it doesn't know, or an install of nothing: the usage and exit, before anything is read or
// written (no job for Components, no history, nothing in the service log). Asked for help: the same, on stdout.
if (index([ '-h', '--help', 'help' ], ARGV[0]) >= 0) {
print(USAGE);
exit(0);
}
if (index([ 'check', 'install', 'auto' ], ARGV[0]) < 0 || (ARGV[0] == 'install' && !length(ARGV[1] ?? ''))) {
warn(USAGE);
exit(2);
}
// The phases and errors of a job LuCI started are in the admin's language (rpc/updates.uc hands it over).
i18n.use(getenv('DAWNLINE_LANG'));
@@ -313,7 +332,7 @@ function main() {
else if (job.action == 'auto')
auto();
else
die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
die(USAGE);
job.state = 'done';
phase(_('Finished'));
}
@@ -341,7 +360,7 @@ let LOCK = null;
for (let i = 0; i < 10 && !LOCK; i++) {
LOCK = upd.try_lock();
if (!LOCK)
system('usleep 100000 2>/dev/null || sleep 1');
sleep(100);
}
if (!LOCK)
exit(0);
@@ -1,3 +0,0 @@
Geist and Geist Mono are licensed under the SIL Open Font License, Version 1.1.
Copyright (c) 2023 Vercel, in collaboration with basement.studio.
https://github.com/vercel/geist-font/blob/main/OFL.txt
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><style>.t{fill:#0a0a0a}.g{fill:#fff}@media (prefers-color-scheme:dark){.t{fill:#fff}.g{fill:#0a0a0a}}</style><rect class="t" width="64" height="64" rx="16"/><path class="g" d="M14 38a18 18 0 0 1 36 0z"/><rect class="g" x="12" y="43" width="40" height="4" rx="2" opacity=".5"/></svg>

Before

Width:  |  Height:  |  Size: 343 B

@@ -1 +0,0 @@
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
@@ -1,6 +0,0 @@
"use strict";(()=>{var 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 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 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: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((x,b)=>b?[`
`,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 = {};
for (let k in [ 'REQUEST_METHOD', 'REQUEST_URI', 'REMOTE_ADDR', 'HTTPS', 'CONTENT_LENGTH', 'CONTENT_TYPE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE',
'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_USER_AGENT', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
@@ -1,10 +1,10 @@
{
"admin/network/dawnline": {
"admin/services/dawnline": {
"title": "Dawnline",
"order": 65,
"action": {
"type": "alias",
"path": "admin/network/dawnline/server"
"path": "admin/services/dawnline/server"
},
"depends": {
"acl": [
@@ -15,31 +15,31 @@
}
}
},
"admin/network/dawnline/overview": {
"admin/services/dawnline/overview": {
"action": {
"type": "view",
"path": "dawnline/server"
}
},
"admin/network/dawnline/people": {
"admin/services/dawnline/people": {
"action": {
"type": "view",
"path": "dawnline/people"
}
},
"admin/network/dawnline/activity": {
"admin/services/dawnline/activity": {
"action": {
"type": "view",
"path": "dawnline/activity"
}
},
"admin/network/dawnline/person": {
"admin/services/dawnline/person": {
"action": {
"type": "view",
"path": "dawnline/person"
}
},
"admin/network/dawnline/server": {
"admin/services/dawnline/server": {
"title": "Servers",
"order": 10,
"action": {
@@ -47,7 +47,7 @@
"path": "dawnline/server"
}
},
"admin/network/dawnline/diagnostics": {
"admin/services/dawnline/diagnostics": {
"title": "Diagnostics",
"order": 40,
"action": {
@@ -55,13 +55,13 @@
"path": "dawnline/diagnostics"
}
},
"admin/network/dawnline/health": {
"admin/services/dawnline/health": {
"action": {
"type": "view",
"path": "dawnline/health"
}
},
"admin/network/dawnline/settings": {
"admin/services/dawnline/settings": {
"title": "Settings",
"order": 60,
"action": {
@@ -69,7 +69,7 @@
"path": "dawnline/settings"
}
},
"admin/network/dawnline/updates": {
"admin/services/dawnline/updates": {
"title": "Components",
"order": 70,
"action": {
@@ -6,6 +6,7 @@
"luci.dawnline": [
"rev",
"status",
"meter",
"setup_defaults",
"health",
"service_log",
@@ -115,9 +115,9 @@ function peer_of(dmp, d) {
return dmp.peers[d.public_key];
}
/** What the device sends to the router: its configuration's AllowedIPs. */
/** What the device sends to the router: its configuration's AllowedIPs (its own, with lan_bypass). */
function routed(m, srv, p, d) {
return awg.allowed_ips(m, srv, p);
return awg.allowed_ips(m, srv, p, d);
}
/** The home network (interface) of a server that holds an address. */
@@ -204,6 +204,12 @@ function from_device(m, d, t, states, dmp, snap) {
return steps;
}
// A device that keeps its own local network out of the tunnel (lan_bypass;
// Home only is the same either way) sends a private address there, router
// or home address alike: it never reaches this router's rules.
if (d.lan_bypass && p.access != 'lan' && !in_nets(t.ip, allowed))
return stop(steps, via(t.ip));
// The router itself.
if (index(router_addrs(snap), t.ip) >= 0) {
let portal = m.settings.portal_enabled && (t.port == m.settings.portal_port || (core.portal_http(m) && t.port == core.portal_http_port(m)));
@@ -301,17 +307,20 @@ function to_device(m, ip, d, states, dmp, snap) {
return steps;
}
/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */
export function check(m, from, to) {
/**
* `from` and `to`: a device id, or an IPv4 address (optionally :port).
* `ctx` = { states, dmp, snap } (a test's own); read from the router when not
* given. Returns { ok, steps: [{ ok, title, detail }] }.
*/
export function check(m, from, to, ctx) {
let a = parse_target(m, from), b = parse_target(m, to);
if (!a)
die(sprintf(_('"%s" is not a device or an IPv4 address.'), from));
if (!b)
die(sprintf(_('"%s" is not a device or an IPv4 address.'), to));
let usage = core.load_usage();
let states = view.states(m, usage);
let dmp = live.dump(m);
let snap = net.snapshot(true);
let states = ctx?.states ?? view.states(m, core.load_usage());
let dmp = ctx?.dmp ?? live.dump(m);
let snap = ctx?.snap ?? net.snapshot(true);
let steps;
if (a.dev)
steps = from_device(m, a.dev, b, states, dmp, snap);
@@ -13,7 +13,7 @@
// (dawnline.store) is never taken while 'apply' is held.
import { readfile, writefile, stat, unlink } from 'fs';
import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util';
import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, syslog, log_on, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
@@ -54,8 +54,10 @@ export function sync_hosts(m) {
let body = length(lines) ? join('\n', lines) + '\n' : '';
// dnsmasq runs as its own user; rpcd's umask would leave the file 0600.
let readable = ((stat(HOSTS_FILE)?.perm?.other_read) ?? false);
if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable))
if ((readfile(HOSTS_FILE) ?? '') == body && (body == '' || readable)) {
syslog('debug', 'dns', `${HOSTS_FILE}: unchanged · ${length(lines)} names`);
return false;
}
ensure_dir('/tmp/hosts');
if (body == '')
unlink(HOSTS_FILE);
@@ -63,6 +65,7 @@ export function sync_hosts(m) {
writefile(HOSTS_FILE, body);
system(`chmod 644 ${HOSTS_FILE}`);
}
syslog('info', 'dns', body == '' ? `${HOSTS_FILE}: removed (no device names)` : `${HOSTS_FILE}: ${length(lines)} names written (*.${m.settings.domain}) · killall -HUP dnsmasq`);
system('killall -HUP dnsmasq 2>/dev/null');
return true;
};
@@ -154,6 +157,21 @@ function sync_warning(m, table, peers) {
return length(out) ? join(' ', [ ...out, _('Open Diagnostics → Health.') ]) : null;
}
/**
* The same as sync_warning for syslog: in English whatever the admin's
* language (a log is read by anyone, searched and sent on), with what nft or
* awg said. Null when all went in.
*/
function sync_facts(m, table, peers) {
let out = [];
if (table != null)
push(out, `access rules ${nft.present() ? 'not updated, the previous ones stay' : 'not loaded, no device loaded'}: ${table}`);
for (let id, r in peers)
if (r != 'ok' && r != 'down')
push(out, `${m.servers[id]?.name ?? id}: devices not loaded: ${r}`);
return length(out) ? join(' · ', out) : null;
}
/*
* With the lock held: access sets first, then devices into the tunnels.
* Fail closed: without the table the firewall would let every loaded device
@@ -226,24 +244,60 @@ export function sync_loop(m, usage, force) {
/* ---------- entry points ---------- */
/** Full reconcile: router configuration + runtime state. */
/** Milliseconds on the monotonic clock, for how long an apply's steps take. */
function ms() {
let c = clock(true);
return c[0] * 1000 + c[1] / 1000000;
}
/**
* Full reconcile: router configuration + runtime state. In syslog: what it
* came to, with how long it took (info; warn when it did not fully take), and
* each step with its result at the debug level.
*/
export function apply(opts) {
opts ??= {};
let t0 = ms();
let debug = log_on('debug');
// One step, timed; `show` picks what of its result goes in the line (never the model: it holds keys).
let step = (name, fn, show) => {
let t = ms();
let out = fn();
let what = show ? show(out) : out;
if (debug)
syslog('debug', 'apply', sprintf('%s done in %d ms%s', name, ms() - t,
what == null ? '' : ` · ${type(what) == 'string' ? what : sprintf('%J', what)}`));
return out;
};
if (debug)
syslog('debug', 'apply', 'applying the configuration');
migrate.run();
let r = with_lock('apply', () => {
let m = core.load();
let usage = core.load_usage();
let network = netifd.sync(m);
let firewall = fw.sync(m);
let lp = loop.ensure(m, true);
loop.sync_resolver(m);
fw.sync_reply_routes(m);
let s = locked_sync(m, usage, true);
let changed = (x) => x ? 'changed' : 'unchanged';
let network = step('network (netifd)', () => netifd.sync(m), changed);
let firewall = step('firewall (fw4)', () => fw.sync(m), changed);
let lp = step('internet like a home device', () => loop.ensure(m, true));
step('resolver for Home-only devices', () => { loop.sync_resolver(m); });
step('reply routes', () => { fw.sync_reply_routes(m); });
let s = step('access rules and devices', () => locked_sync(m, usage, true), (x) => ({ table: x.table, peers: x.peers }));
ensure_dir(RUN_DIR);
write_file(NET_SIG, net_signature(m), 0o644);
return { network, firewall, lp, peers: s.peers, warning: s.warning };
return { network, firewall, lp, peers: s.peers, warning: s.warning, facts: sync_facts(m, s.table, s.peers),
counts: [ length(keys(m.servers)), length(keys(m.people)), length(keys(m.devices)) ] };
});
loop.remember(r.lp);
let n = (k, one, many) => `${k} ${k == 1 ? one : many}`;
let took = sprintf('configuration applied in %d ms · %s, %s, %s', ms() - t0,
n(r.counts[0], 'server', 'servers'), n(r.counts[1], 'person', 'people'), n(r.counts[2], 'device', 'devices'));
// Syslog in English (sync_facts, loop.error_note); the admin's answer carries the words in their language.
if (r.facts)
syslog('warn', 'apply', `${took} · ${r.facts}`);
else
syslog('info', 'apply', took);
if (r.lp.error)
syslog('warn', 'apply', `internet like a home device: ${type(r.lp.error) == 'object' ? loop.error_note(r.lp.error) : r.lp.error}`);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: loop.error_text(r.lp.error) } : !r.lp.off, peers: r.peers, warning: r.warning };
};
@@ -1,16 +1,18 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters, the words for
// why a tunnel is kept down (blocked_text) and what the watchdog and Health
// check about it. Plain WireGuard is AmneziaWG with the disguise off.
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation) and the values
// AmneziaWG refuses, client configurations (.conf, AmneziaVPN key), the
// netifd options of a server's tunnel, its peers (`awg syncconf`, no
// restart), live counters, the words for why a tunnel is kept down
// (blocked_text) and what the watchdog and Health check about it. Plain
// WireGuard is AmneziaWG with the disguise off.
import { readfile, stat, unlink } from 'fs';
import {
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, tunnel_name, ensure_dir, write_file, read_json, write_json, lock, unlock,
slog, iface_status, DATA_DIR, RUN_DIR
slog, syslog, some_of, iface_status, DATA_DIR, RUN_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import { ipv6_groups } from 'dawnline.schema';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
import { _, L_ } from 'dawnline.i18n';
@@ -28,6 +30,9 @@ export const OBF_CONF = {
const TOOL = '/usr/bin/awg', PROTO = '/lib/netifd/proto/amneziawg.sh';
/** The packages AmneziaWG comes in (the Components tab installs them). */
const PACKAGES = [ 'kmod-amneziawg', 'amneziawg-tools' ];
// A module constant, compiled once (a literal is compiled each time it runs):
// dump() checks it on every line of each tunnel's `awg show <ifname> dump`, every second.
const DIGITS = /^[0-9]+$/;
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
function proto_handler() {
@@ -135,7 +140,9 @@ function rand_h(used) {
}
}
// caps() answers from here while the tool, the protocol script and the module file are the same.
// caps() answers from here while the tool, the protocol script, the module
// file, the install record and the loaded module are the same (tmpfs: a
// reboot starts over).
const CAPS = `${RUN_DIR}/awg-caps.json`;
/**
@@ -143,15 +150,20 @@ const CAPS = `${RUN_DIR}/awg-caps.json`;
* options it passes on) and the `awg` tool (the keys it accepts) say what the
* tools know, the kernel module's package version what the kernel runs, and
* a feature counts only when both have it (tools 3.1 over a 2.0 module would
* configure header protection that the kernel silently lacks):
* configure header protection that the kernel silently lacks). While an
* update waits for a reboot (its old module stayed loaded) the kernel runs
* the generation from before it, as the install recorded it:
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
* tools / kmod — their generations ('1.0', '2.0', '3.1'; null unknown)
* mismatch — the two differ
* pending — an installed module waits for a reboot (dawnline.awg_builds)
*/
export function caps() {
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}`;
let core = builds.module_core();
let key = `${stat(`/lib/modules/${rel}/amneziawg.ko`)?.mtime ?? 0}/${stat(TOOL)?.mtime ?? 0}/${stat(PROTO)?.mtime ?? 0}` +
`/${stat(builds.RECORD)?.mtime ?? 0}/${core ?? 0}`;
let cached = read_json(CAPS, null);
if (cached?.key == key && cached.caps)
return cached.caps;
@@ -160,12 +172,15 @@ export function caps() {
let t2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0;
let t3 = t2 && index(script, 'awg_header_protection_key') >= 0 && tool != '';
let tools = !stat(TOOL) ? null : t3 ? '3.1' : t2 ? '2.0' : '1.0';
// A module installed by hand has no package: then the tools are believed.
let kmod = builds.gen(pkg.version('kmod-amneziawg'));
// A module installed by hand has no package, so no generation (also when
// a pending update replaces it): then the tools are believed.
let rec = read_json(builds.RECORD, null), boot = builds.boot_id();
let kmod = builds.running_gen(rec, boot, core, pkg.version('kmod-amneziawg'));
let out = {
v2: t2 && (kmod == null || kmod != '1.0'),
v3: t3 && (kmod == null || kmod == '3.1'),
tools, kmod, mismatch: tools != null && kmod != null && tools != kmod,
pending: builds.pending(rec, boot, core),
};
ensure_dir(RUN_DIR);
write_json(CAPS, { key, caps: out }, 0o644);
@@ -238,18 +253,24 @@ function dns_answer() {
* offers Balanced or Maximum instead.
*/
export function obf_preset(name) {
if (name == 'max')
if (name == 'max') {
// 32 random bytes, as `awg genkey` makes them (no process). Without
// one the server would come up with weak or no header protection.
let hpk = genpsk();
if (!valid_key(hpk))
die(_('Key generation failed (no random data).'));
return {
jc: `${rand_int(4, 6)}`, jmin: '10', jmax: '50',
s1: '12', s2: '12', s3: '12', s4: '12',
h1: '1', h2: '2', h3: '3', h4: '4',
i1: dns_query(), i2: dns_answer(),
header_protection_key: sh_out('awg genkey'),
header_protection_key: hpk,
content_padding_addition: '10-100',
rekey_after_time: '100-120', rekey_timeout: '3-7', reject_after_time: '150-180',
keepalive_timeout: '5-15', max_handshake_attempts: '15-20',
random_trailers: 'on', disable_cookies: 'on',
};
}
if (name == 'off')
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
let o = {};
@@ -275,38 +296,222 @@ export function obf_preset(name) {
return o;
};
/* ---------- disguise values AmneziaWG refuses ---------- */
export function obf_errors(o) {
// Checked with ltrim, not regexes: this module loads with every portal request.
const DEC = '0123456789', HEX = '0123456789abcdefABCDEF';
/** A whole number in digits up to `top`, or null (no spaces: callers trim where the tools drop them). */
function uint(v, top) {
let s = `${v}`;
if (s == '' || length(s) > 10 || ltrim(s, DEC) != '')
return null;
return +s <= top ? +s : null;
}
/** A number or a range as AmneziaWG writes them ("5", "5-15"), each end up to `top`: [ lo, hi ], or null. */
function uint_range(v, top) {
let p = split(trim(`${v}`), '-');
let lo = length(p) <= 2 ? uint(p[0], top) : null;
let hi = length(p) == 2 ? uint(p[1], top) : lo;
return lo != null && hi != null && lo <= hi ? [ lo, hi ] : null;
}
/** Value `k` of disguise values `o` is set. */
function given(o, k) {
return o[k] != null && o[k] != '';
}
/**
* Packet types H1-H4: a number or a range each, apart from the others (the
* kernel refuses an overlap). One not given keeps WireGuard's own type, 1-4.
*/
function headers_unsafe(o, errs) {
let hs = [];
for (let i = 1; i <= 4; i++) {
let r = given(o, `h${i}`) ? uint_range(o[`h${i}`], 4294967295) : [ i, i ];
if (!r)
push(errs, sprintf(_('%s must be a number or a range like 100-200, up to 4294967295.'), OBF_CONF[`h${i}`]));
push(hs, r);
}
for (let i = 0; i < 4; i++)
for (let j = i + 1; j < 4; j++)
if (hs[i] && hs[j] && hs[i][0] <= hs[j][1] && hs[j][0] <= hs[i][1])
push(errs, sprintf(_('%s and %s overlap: each packet type needs values of its own.'), OBF_CONF[`h${i + 1}`], OBF_CONF[`h${j + 1}`]));
}
/**
* One tag of a signature packet as both the kernel and amneziawg-go read it:
* <b 0x..> fixed bytes (an even number of hex digits), <r N>, <rc N>, <rd N>
* (N random bytes, letters, digits; a negative N writes past the packet in
* the kernel, kmod #267) or <t> (the time). <c> is the kernel's alone and
* <d>, <ds>, <dz> amneziawg-go's: devices on the other refuse them.
*/
function itag_ok(tag) {
if (tag == 't')
return true;
let sp = index(tag, ' ');
if (sp < 0)
return false;
let key = substr(tag, 0, sp), val = substr(tag, sp + 1);
if (key == 'b')
return length(val) > 2 && length(val) % 2 == 0 && substr(val, 0, 2) == '0x' && ltrim(substr(val, 2), HEX) == '';
if (key == 'r' || key == 'rc' || key == 'rd')
return (uint(val, 1000) ?? 0) >= 1;
return false;
}
/** What is wrong with signature packet `name` (I1-I5) holding `s`, as a sentence; null when nothing. */
function itag_error(name, s) {
// In a .conf file `#` starts a comment and a line break ends the line: the rest would be lost.
if (index(s, '#') >= 0 || index(s, '\n') >= 0 || index(s, '\r') >= 0)
return sprintf(_('%s may not contain # or a line break.'), name);
// Text between tags is skipped by both parsers.
for (let a = index(s, '<'); a >= 0; a = index(s, '<')) {
let b = index(substr(s, a), '>');
if (b < 0)
return sprintf(_('%s has a tag that is not closed with >.'), name);
let tag = substr(s, a + 1, b - 1);
if (!itag_ok(tag))
return sprintf(_('%s: <%s> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.'),
name, length(tag) > 24 ? `${substr(tag, 0, 24)}…` : tag);
s = substr(s, a + b + 1);
}
return null;
}
/** Signature packets I1-I5: their tags, and all of them in one device's configuration (one QR code). */
function itags_unsafe(o, errs) {
let total = 0;
for (let k in [ 'i1', 'i2', 'i3', 'i4', 'i5' ]) {
if (!given(o, k))
continue;
total += length(`${o[k]}`);
let e = itag_error(OBF_CONF[k], `${o[k]}`);
if (e)
push(errs, e);
}
if (total > 2000)
push(errs, sprintf(_('I1-I5 together must be at most 2000 characters, not %d.'), total));
}
/**
* What in disguise values `o` AmneziaWG would refuse, crash on or break
* devices with: what an import, a restore or a hand edit in uci must never
* hand to the kernel (dawnline.backup, dawnline.netifd). Only those rules,
* none of Dawnline's own bounds (obf_errors): a backup the kernel takes stays
* usable. Sentences in the reader's language; [] when the values are safe.
*/
export function obf_unsafe(o) {
o ??= {};
let errs = [];
for (let k, r in OBF_SPEC) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+$/) || +v < r[0] || +v > r[1])
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
let num = (k) => given(o, k) ? uint(trim(`${o[k]}`), 65535) : 0;
// 16-bit numbers for the tools; Jmin above Jmax sizes junk past its buffer (kmod #225).
for (let k in [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4' ])
if (num(k) == null)
push(errs, sprintf(_('%s must be a whole number from 0 to 65535.'), OBF_CONF[k]));
if (given(o, 'jmin') && given(o, 'jmax') && num('jmin') != null && num('jmax') != null && num('jmin') > num('jmax'))
push(errs, _('Jmin must not be larger than Jmax.'));
headers_unsafe(o, errs);
// Header protection: a 32-byte key, and every padding at least the 12 bytes of its nonce (the kernel checks).
if (given(o, 'header_protection_key')) {
if (!valid_key(o.header_protection_key))
push(errs, _('The header protection key is not a key.'));
for (let k in [ 's1', 's2', 's3', 's4' ])
if (num(k) != null && num(k) < 12)
push(errs, sprintf(_('%s must be at least 12 with header protection.'), OBF_CONF[k]));
}
if (o.jmin != null && o.jmax != null && +o.jmin > +o.jmax)
push(errs, 'jmin > jmax');
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, 's1 + 56 = s2');
let hs = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ]) {
let v = o[k];
if (v == null || v == '')
continue;
if (!match(v, /^[0-9]+(-[0-9]+)?$/))
push(errs, sprintf(_('%s must be a number or range'), k));
else if (hs[v])
push(errs, _('h1-h4 must be distinct'));
hs[v] = true;
// 3.1 timers and counts: 0 alone is the kernel's default; a 0 in a range
// would fire at once. Keys are dropped after 180 seconds whatever is set.
for (let k in [ 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'keepalive_timeout', 'max_handshake_attempts' ]) {
let r = given(o, k) ? uint_range(o[k], 65535) : [ 0, 0 ];
if (!r || (r[0] == 0 && r[1] > 0))
push(errs, sprintf(_('%s must be a number or a range like 5-15, from 1 to 65535.'), OBF_CONF[k]));
else if (k == 'reject_after_time' && r[1] > 180)
push(errs, _('RejectAfterTime must be at most 180 seconds.'));
}
if (given(o, 'content_padding_addition') && !uint_range(o.content_padding_addition, 65535))
push(errs, sprintf(_('%s must be a number or a range like 10-100, up to 65535.'), OBF_CONF.content_padding_addition));
// What both netifd and the .conf parser read as a switch.
for (let k in [ 'random_trailers', 'disable_cookies' ])
if (given(o, k) && index([ 'on', 'off', '1', '0' ], `${o[k]}`) < 0)
push(errs, sprintf(_('%s must be on or off.'), OBF_CONF[k]));
itags_unsafe(o, errs);
return errs;
};
/**
* What is wrong with the disguise values of a server Dawnline sets up: what
* AmneziaWG refuses (obf_unsafe), and Dawnline's own bounds on top (junk that
* stays under the path MTU, a handshake initiation and response that never
* share a size). Its presets pass it. Sentences in the reader's language; []
* when the values are fine.
*/
export function obf_errors(o) {
o ??= {};
let errs = obf_unsafe(o);
for (let k, r in OBF_SPEC) {
let n = given(o, k) ? uint(trim(`${o[k]}`), 65535) : null;
if (n != null && (n < r[0] || n > r[1]))
push(errs, sprintf(_('%s must be from %d to %d.'), OBF_CONF[k], r[0], r[1]));
}
if (o.s1 != null && o.s2 != null && +o.s1 + 56 == +o.s2)
push(errs, _('S2 must not be S1 + 56: the handshake initiation and response would have the same size.'));
return errs;
};
/**
* Disguise values `o` as anyone who may read the status sees them: all but
* the header protection key, a secret every device of the server shares
* (with it and the server's public key, captured traffic can be unmasked).
* Devices get it in their own configuration (client_config).
*/
export function obf_public(o) {
let out = { ...(o ?? {}) };
delete out.header_protection_key;
return out;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
/*
* Everything but a device's own local network, for a device whose local
* network stays outside the tunnel (lan_bypass): every IPv4 address outside
* the private ranges the access table drops for internet people anyway
* (dawnline.nft PRIVATE4: 10/8, 172.16/12, 192.168/16, 100.64/10,
* 169.254/16, 224/3), and every IPv6 address outside fc00::/7, fe80::/10
* and ff00::/8. Fixed lists (tests/ucode/awg.test.uc proves each is exactly
* that complement); what of the private ranges goes through the tunnel after
* all (DNS, home) is added to them.
*/
export const BYPASS4 = [
'0.0.0.0/5', '8.0.0.0/7', '11.0.0.0/8', '12.0.0.0/6', '16.0.0.0/4', '32.0.0.0/3', '64.0.0.0/3', '96.0.0.0/6',
'100.0.0.0/10', '100.128.0.0/9', '101.0.0.0/8', '102.0.0.0/7', '104.0.0.0/5', '112.0.0.0/4', '128.0.0.0/3', '160.0.0.0/5',
'168.0.0.0/8', '169.0.0.0/9', '169.128.0.0/10', '169.192.0.0/11', '169.224.0.0/12', '169.240.0.0/13', '169.248.0.0/14',
'169.252.0.0/15', '169.255.0.0/16', '170.0.0.0/7', '172.0.0.0/12', '172.32.0.0/11', '172.64.0.0/10', '172.128.0.0/9',
'173.0.0.0/8', '174.0.0.0/7', '176.0.0.0/4', '192.0.0.0/9', '192.128.0.0/11', '192.160.0.0/13', '192.169.0.0/16',
'192.170.0.0/15', '192.172.0.0/14', '192.176.0.0/12', '192.192.0.0/10', '193.0.0.0/8', '194.0.0.0/7', '196.0.0.0/6',
'200.0.0.0/5', '208.0.0.0/4',
];
export const BYPASS6 = [ '::/1', '8000::/2', 'c000::/3', 'e000::/4', 'f000::/5', 'f800::/6', 'fe00::/9', 'fec0::/10' ];
/** An IPv6 address BYPASS6 leaves out: in fc00::/7, fe80::/10 or ff00::/8 (the first 16 bits decide). False for anything else. */
function private6(a) {
let g = ipv6_groups(a)?.[0];
return g != null && ((g & 0xfe00) == 0xfc00 || (g & 0xffc0) == 0xfe80 || (g & 0xff00) == 0xff00);
}
/**
* What a device sends into the tunnel (its AllowedIPs; the server's peer
* line stays its address/32). Home only: the person's home networks, the
* tunnel network or the router's address, and the DNS. Internet: everything,
* or with `dev.lan_bypass` everything but the device's own local network
* (BYPASS4, BYPASS6), every DNS server it is given (IPv4 and IPv6) and for
* home access what Home only gets. Without `dev`, as for a device without
* lan_bypass.
*/
export function allowed_ips(m, srv, p, dev) {
if (p.access != 'lan' && !dev?.lan_bypass)
return [ '0.0.0.0/0', '::/0' ];
let home = () => {
let nets = core.person_home(srv, p).nets;
// With devices reaching each other, the whole tunnel network (the router's
// address is in it); otherwise only the router's own address.
@@ -315,13 +520,27 @@ export function allowed_ips(m, srv, p) {
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
return nets;
};
let dns = core.client_dns(m, srv, p);
if (p.access == 'lan') {
// The resolver address must be reachable through the tunnel too (not the fallback).
let dns = core.client_dns(m, srv, p)[0];
if (dns)
push(nets, `${dns}/32`);
let nets = home();
if (dns[0])
push(nets, `${dns[0]}/32`);
return net.collapse(nets);
}
return [ '0.0.0.0/0', '::/0' ];
// Every DNS server stays in the tunnel: a private one left out would be
// asked on whatever network the device is on (a public one is in the rest).
let nets = [ ...BYPASS4 ], nets6 = [];
for (let a in dns)
if (ip2int(a) != null)
push(nets, `${a}/32`);
else if (private6(a))
push(nets6, `${a}/128`);
if (p.access == 'both')
push(nets, ...home());
return [ ...net.collapse(nets), ...BYPASS6, ...uniq(nets6) ];
};
@@ -369,14 +588,56 @@ function client_obf(srv, dev) {
return o;
}
/**
* The keep-alive `dev` gets (its own or the server's, core.device_keepalive)
* as [ lo, hi ] seconds; null when it is off (0). With 3.1 (header
* protection: its apps take ranges) jittered over ten seconds like the other
* timers, since a fixed beat would be the one regular thing left. The online
* window follows its upper end (dawnline.live).
*/
export function keepalive_range(srv, dev) {
let k = core.device_keepalive(srv, dev);
if (!(k > 0))
return null;
return srv.obf?.header_protection_key ? [ k, k + 10 ] : [ k, k ];
};
/**
* The longest an idle device goes between two handshakes, in seconds; null
* when its keep-alive is off (an idle device then sends nothing at all). Its
* keep-alive packets are what it sends, and the first one after its key's
* rekey time (RekeyAfterTime, WireGuard's 120 s; past 180 s the key is
* refused anyway) starts a handshake (kmod send.c keep_key_fresh): up to one
* keep-alive past that time, or each keep-alive once they are further apart.
*/
export function idle_handshake(srv, dev) {
let ka = keepalive_range(srv, dev);
if (!ka)
return null;
let rekey = min(uint_range(srv.obf?.rekey_after_time ?? '', 65535)?.[1] || 120, 180);
return ka[0] > rekey ? ka[1] : rekey + ka[1];
};
/**
* keepalive_range() as the apps write it ("25-35", "25"); null when off. The
* .conf and the AmneziaVPN key carry the same text (AmneziaVPN hands it on as
* written, ranges included).
*/
function keepalive_text(srv, dev) {
let r = keepalive_range(srv, dev);
if (!r)
return null;
return r[0] == r[1] ? `${r[0]}` : `${r[0]}-${r[1]}`;
}
export function client_config(m, dev) {
let p = m.people[dev.person];
let srv = p ? m.servers[p.server] : null;
if (!srv)
return null;
let host = core.endpoint_host(m, srv);
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let ep = index(host, ':') >= 0 && substr(host, 0, 1) != '[' ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p, dev);
let dns = core.client_dns(m, srv, p);
let mtu = core.device_mtu(srv, dev);
let lines = [ '[Interface]' ];
@@ -398,10 +659,9 @@ export function client_config(m, dev) {
push(lines, `PresharedKey = ${dev.preshared_key}`);
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
push(lines, `Endpoint = ${ep}:${srv.port}`);
// With 3.1 (its apps take ranges) the keep-alive is jittered like the
// other timers; a fixed beat would be the one regular thing left.
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.obf.header_protection_key ? `${srv.keepalive}-${srv.keepalive + 10}` : srv.keepalive}`);
let keepalive = keepalive_text(srv, dev);
if (keepalive)
push(lines, `PersistentKeepalive = ${keepalive}`);
return {
name: dev.name,
person: p.name,
@@ -421,7 +681,7 @@ export function client_config(m, dev) {
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
persistent_keep_alive: keepalive ?? '0',
obfuscation: obf,
},
};
@@ -445,82 +705,196 @@ export function netifd_options(srv) {
};
for (let k in core.OBF_KEYS)
o[`awg_${k}`] = srv.obf[k];
// DisableCookies is the devices' alone (their .conf and key keep it): on
// the server it would turn off WireGuard's own defence against a flood of
// handshakes (cookie replies and a per-address limit, only ever under
// load), and anyone who held a configuration could keep both cores busy.
// Null takes it off an interface that had it.
o.awg_disable_cookies = null;
return o;
};
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
/**
* The devices sync_peers() loads into server `sid`'s tunnel, in the model's
* order (an empty list when none). Pure: the model and the people's states
* (apply.states_for). Health and the agent compare a running tunnel with it.
*/
export function tunnel_devices(m, sid, states) {
let out = [];
let own = m.servers?.[sid]?.public_key;
for (let did, d in m.devices) {
let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it), and so does one with the
// server's own key, which the kernel silently ignores (it would look
// missing for ever). Over the data limit or outside the allowed hours the
// tunnel stays: the access table blocks everything but the portal, which
// says why (a silent handshake failure would look like a broken VPN).
if (p && p.server == sid && !d.disabled && index(SOFT_STATES, states[p.id]) >= 0 && valid_key(d.public_key) && ip2int(d.address) != null &&
(!own || d.public_key != own))
push(out, d);
}
return out;
};
/**
* How the peers dump() read on `ifname` differ from the devices that belong
* there (tunnel_devices): { loaded, missing, extra }, counted by key, not by
* number (a stale peer standing in for a missing one would make the numbers
* match). Pure.
*/
export function peer_diff(devs, dmp, ifname) {
let want = {};
for (let d in devs)
want[d.public_key] = true;
let loaded = 0, extra = 0, found = 0;
for (let k, p in dmp.peers)
if (p.ifname == ifname) {
loaded++;
if (want[k])
found++;
else
extra++;
}
return { loaded, missing: length(keys(want)) - found, extra };
};
/** Push the peer list of every server to the kernel without restarting it. */
// Each tunnel's peers as last loaded ({ ifname: [ "Person · Device (address)" ] }), so a log line can say who came and went.
const PEERS_SEEN = `${RUN_DIR}/peers-seen.json`;
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
let res = {};
let seen = read_json(PEERS_SEEN, {}), now = {};
for (let id, srv in m.servers) {
// Only Dawnline's own interfaces: never another tunnel of the same name (core.tunnels).
if (!srv.enabled || !length(core.tunnels(srv)))
continue;
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
res[id] = 'down';
syslog('debug', 'awg', `interface ${srv.ifname} (${srv.name}): down, no devices to load`);
continue;
}
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
for (let did, d in m.devices) {
let p = m.people[d.person];
// One malformed line makes syncconf refuse the whole server: such a device
// stays out (Health's Data check names it). Over the data limit or
// outside the allowed hours the tunnel stays: the access table blocks
// everything but the portal, which says why (a silent handshake failure
// would look like a broken VPN).
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
continue;
let who = [];
for (let d in tunnel_devices(m, id, states)) {
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
push(lines, `AllowedIPs = ${d.address}/32`, '');
push(who, `${m.people[d.person]?.name ?? d.person} · ${d.name} (${d.address})`);
}
let f = `${RUN_DIR}/${srv.ifname}.conf`;
write_file(f, join('\n', lines));
let r = sh(`awg syncconf ${q(srv.ifname)} ${f}`);
unlink(f);
res[id] = r.code == 0 ? 'ok' : trim(r.out);
if (r.code != 0)
if (r.code != 0) {
slog('awg', 'error', L_("couldn't load devices into the tunnel"), trim(r.out), srv.name);
continue;
}
// Who came in and who left since the last load: info; the same peers: debug.
now[srv.ifname] = who;
let was = seen[srv.ifname];
let head = `interface ${srv.ifname} (${srv.name}): awg syncconf · listen port ${srv.port} · ${length(who)} ${length(who) == 1 ? 'peer' : 'peers'}`;
// The first load since the router started (or since the tunnel came up): how many, the names at debug.
if (was == null) {
syslog('info', 'awg', `${head} loaded`);
syslog('debug', 'awg', `interface ${srv.ifname}: ${join(', ', who)}`);
continue;
}
let add = filter(who, (x) => index(was, x) < 0), del = filter(was, (x) => index(who, x) < 0);
if (length(add) || length(del))
syslog('info', 'awg', `${head}${length(add) ? ' · added ' + some_of(add) : ''}${length(del) ? ' · removed ' + some_of(del) : ''}`);
else
syslog('debug', 'awg', `${head}, unchanged`);
}
if (sprintf('%J', now) != sprintf('%J', seen))
write_json(PEERS_SEEN, now, 0o600);
return res;
};
/**
* Parse `awg show all dump`. Returns { ok, ifaces: { ifname: {...} }, peers: { pubkey: {...} } }.
* Lines are told apart by their shape, not their length (each AmneziaWG
* generation adds fields to the interface line): an interface line carries
* its private and public key and a port, a peer line the peer's key, a
* preshared key or "(none)" and an endpoint. The tool fails when any one
* interface can't be read, but still prints the others: with `wanted` (the
* ifnames that matter) `ok` means those were all read, so another tunnel's
* trouble is not ours.
/** The interface's index while it exists (a new one each time netifd sets the tunnel up), else null. */
function ifindex(ifname) {
let s = trim(readfile(`/sys/class/net/${ifname}/ifindex`) ?? '');
return s != '' ? +s : null;
}
/*
* One interface's `awg show <ifname> dump` into `out` (see dump()). Lines are
* told apart by their shape, not their length (each AmneziaWG generation adds
* fields to the interface line): an interface line carries its private and
* public key and a port, a peer line the peer's key, a preshared key or
* "(none)" and an endpoint. Unlike `show all`, the lines have no ifname.
*/
export function dump(wanted) {
let r = sh('awg show all dump');
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
function read_iface(out, ifname) {
// Read around the call: a link set up again in between gave counters of either one.
let before = ifindex(ifname);
// Not there (a tunnel netifd could not bring up, AmneziaWG gone after an
// upgrade): no process to learn it. One that appears is read next time.
if (before == null) {
out.reads[ifname] = 'down';
return;
}
let r = sh(`awg show ${q(ifname)} dump`);
let ix = ifindex(ifname);
let iface = null, peers = {};
if (r.code == 0)
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) < 5 || !valid_key(f[1]))
if (length(f) < 4 || !valid_key(f[0]))
continue;
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
endpoint: ep,
handshake: +f[5],
rx: +f[6],
tx: +f[7],
let key2 = valid_key(f[1]);
if (key2 && match(f[2], DIGITS))
iface = { public_key: f[1], port: +f[2], ifindex: ix };
else if (length(f) >= 8 && (key2 || f[1] == '(none)'))
peers[f[0]] = {
ifname,
endpoint: f[2] == '(none)' ? '' : f[2],
handshake: +f[4],
rx: +f[5],
tx: +f[6],
};
}
let read = iface != null;
// Gone during the read: its peers and their counters are gone with it.
if (ix == null) {
out.reads[ifname] = 'down';
return;
}
if (!out.ok && type(wanted) == 'array')
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
if (!read || ix != before) {
out.reads[ifname] = 'error';
out.ok = false;
return;
}
out.reads[ifname] = 'read';
out.ifaces[ifname] = iface;
for (let k, p in peers)
out.peers[k] = p;
}
/**
* Dawnline's own tunnels, one `awg show <ifname> dump` each for `ifnames`
* (live.tunnel_ifnames): never `all`, so another AmneziaWG interface on the
* router (a client tunnel with long I1-I5, say) neither slows the 1-second
* watcher down nor has its keys read. Returns { ok, reads: { ifname: 'read' |
* 'down' | 'error' }, ifaces: { ifname: { public_key, port, ifindex } },
* peers: { pubkey: { ifname, endpoint, handshake, rx, tx } } }, with only
* what was read in `ifaces` and `peers`:
* down the interface does not exist (/sys/class/net has no such link;
* no process is started for it): its peers and counters are gone
* error it exists but could not be read (or was set up again during the
* read): that says nothing about its peers
* `ok` is false when any of them is 'error' (true for an empty list).
*/
export function dump(ifnames) {
let out = { ok: true, reads: {}, ifaces: {}, peers: {} };
for (let ifn in ifnames ?? [])
read_iface(out, ifn);
return out;
};
@@ -540,6 +914,8 @@ export function server_state(srv) {
* { code: 'ifname', ifname } the interface name is invalid
* { code: 'taken', ifname } network.<ifname> exists and isn't Dawnline's
* { code: 'disguise', need, installed } obf_unsupported()
* { code: 'disguise_invalid' } obf_unsafe() finds values AmneziaWG refuses
* (said again from the server's values when read)
* Files written by older versions hold the English fragment ("has an invalid
* interface name …"), shown as it is.
*/
@@ -555,9 +931,20 @@ export function blocked_note(r) {
if (r.code == 'disguise')
return r.installed ? sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: %s)'), r.need, r.installed)
: sprintf(L_('is kept down: its disguise needs AmneziaWG %s (installed: none)'), r.need);
if (r.code == 'disguise_invalid')
return L_('is kept down: its disguise has values AmneziaWG cannot take');
return L_('is kept down');
};
/** What to do about a reason (blocked_note), for the service log's details. */
export function blocked_fix(r) {
if (r?.code == 'disguise')
return L_('Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
if (r?.code == 'disguise_invalid')
return L_('Choose a disguise on the Server page: it replaces the values set by hand.');
return L_('Choose another interface name in the server settings.');
};
/**
* Why the server's tunnel is kept down (`srv.blocked`), as a sentence with
* its name in the reader's language: what the admin UI shows. Null when it
@@ -577,6 +964,9 @@ export function blocked_text(srv) {
return r.installed
? sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: %s).'), srv.name, r.need, r.installed)
: sprintf(_('%s is kept down: its disguise needs AmneziaWG %s (installed: none).'), srv.name, r.need);
// Which values, from the server's own (the reason is kept as a code).
if (r.code == 'disguise_invalid')
return trim(sprintf(_('%s is kept down: its disguise has values AmneziaWG cannot take. %s'), srv.name, join(' ', obf_unsafe(srv.obf))));
return sprintf(_('%s is kept down.'), srv.name);
};
@@ -633,7 +1023,7 @@ export function probes(m, ctx) {
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: blocked_note(why), back: L_('AmneziaWG is running again'),
detail: () => L_('Choose another interface name in the server settings.'),
detail: () => blocked_fix(why),
});
continue;
}
@@ -654,6 +1044,9 @@ export function probes(m, ctx) {
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
// The lines a fingerprint leaves out. A module constant, compiled once, not
// for each line of each device's configuration.
const DEVICE_OWN = /^(PrivateKey|Jc|Jmin|Jmax) /;
function fnv32(str) {
let h = 2166136261;
@@ -670,7 +1063,7 @@ function fnv32(str) {
*/
export function config_fingerprint(m, dev) {
let c = dev ? client_config(m, dev) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, /^(PrivateKey|Jc|Jmin|Jmax) /)))) : null;
return c ? fnv32(join('\n', filter(split(c.conf, '\n'), (l) => !match(l, DEVICE_OWN)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
@@ -1,8 +1,12 @@
// Dawnline — where AmneziaWG comes from: the awg-openwrt projects publish
// builds per OpenWrt release and target (the kernel module must match the
// firmware). Used by the updater and the Components RPCs.
// firmware), and the record of what was installed on which kernel and boot
// (an update whose module could not be swapped starts with the next boot:
// until then caps() and Health go by the module that still runs). Used by
// the updater, the Components RPCs, dawnline.awg and Health. Installing
// itself is dawnline.upd_awg.
import { readfile } from 'fs';
import { readfile, stat } from 'fs';
import { connect } from 'ubus';
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
import * as pkg from 'dawnline.pkg';
@@ -36,19 +40,52 @@ export function firmware() {
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
export const RECORD = `${DATA_DIR}/awg.json`;
/** This boot (a new one loads the module on disk), or null when the kernel does not say. */
export function boot_id() {
return trim(readfile('/proc/sys/kernel/random/boot_id') ?? '') || null;
};
/**
* The size in memory of the loaded kernel module, or null when none is
* loaded. sysfs has no version for it, but builds differ in size: a module
* reloaded by hand ends a wait for a reboot (pending()).
*/
export function module_core() {
let n = int(trim(readfile('/sys/module/amneziawg/coresize') ?? ''));
return n > 0 ? n : null;
};
/**
* Remember which build was installed on which kernel. After a firmware
* upgrade the module is gone (it was built for that kernel): Health can then
* say so and offer the build for the new one (dawnline.health).
* say so and offer the build for the new one (dawnline.health). `run` comes
* from an install: prev_gen and prev_core, the module that ran before it
* (module_now()), and reloaded, false while that one stays loaded until the
* next boot. null for a module Dawnline did not install (adopt()).
*/
export function record(source, tag, packages) {
export function record(source, tag, packages, run) {
ensure_dir(DATA_DIR, 0o700);
write_json(RECORD, {
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
source, tag, packages, installed: time(),
source, tag, packages, installed: time(), boot: boot_id(),
prev_gen: run?.prev_gen ?? null, prev_core: run?.prev_core ?? null, reloaded: run?.reloaded ?? null,
}, 0o600);
};
/**
* A record for a module Dawnline did not install (install.sh, by hand, or
* before Dawnline kept records), so kernel_changed() notices the next
* firmware upgrade: the kernel it is for, source null, `installed` the time
* Dawnline first saw it. Only when there is no record and the module is
* loaded or on disk for the running kernel. The agent calls it when it starts.
*/
export function adopt() {
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
if (stat(RECORD) || (!stat('/sys/module/amneziawg') && (rel == '' || !stat(`/lib/modules/${rel}/amneziawg.ko`))))
return;
record(null, null, null, null);
};
/**
* The firmware the recorded AmneziaWG build was for, when it is not this one
* (and the module is gone): { was, now, tag, source }, else null.
@@ -88,6 +125,42 @@ export function gen(version) {
return '2.0';
};
/**
* An installed update that waits for a reboot: the install could not swap
* the kernel module (the old one stayed loaded), this is still the boot it
* ran in, and the module loaded is still the one from before it (core:
* module_core() now). Pure: rec is the record or null.
*/
export function pending(rec, boot, core) {
return rec?.reloaded === false && rec.boot != null && rec.boot == boot && core != null && rec.prev_core == core;
};
/**
* The AmneziaWG generation of the kernel module that runs: the one from
* before the install while it waits for a reboot (pending(); null when that
* module had no package), else the installed package's version (gen()).
* Pure, with the record, this boot and module_core() passed in.
*/
export function running_gen(rec, boot, core, version) {
return pending(rec, boot, core) ? rec.prev_gen : gen(version);
};
/**
* The kernel module loaded now, taken before an install changes packages:
* { core, gen, pending }. core is null when none is loaded; gen is what it
* runs (running_gen(), from `version`, the kmod-amneziawg package installed
* now); pending, an earlier update that still waits for a reboot.
*/
export function module_now(version) {
let rec = read_json(RECORD, null), boot = boot_id(), core = module_core();
return { core, gen: core == null ? null : running_gen(rec, boot, core, version), pending: pending(rec, boot, core) };
};
/** The installed AmneziaWG update waits for a reboot (pending(), for Health and Components). */
export function waits_for_reboot() {
return pending(read_json(RECORD, null), boot_id(), module_core());
};
/** The installed AmneziaWG packages: { name: version | null }. */
export function installed() {
let r = {};
@@ -1,7 +1,8 @@
// Dawnline — backups (tar.gz of the config and its data files), restoring
// them, and the JSON export / import. Whatever comes back in is checked first:
// only Dawnline's own regular files, and servers that cannot take over one of
// the router's own interfaces or networks.
// the router's own interfaces or networks, or hand the kernel disguise values
// AmneziaWG refuses.
import { readfile, stat, unlink, lsdir, rename } from 'fs';
import { cursor } from 'uci';
@@ -9,6 +10,7 @@ import {
q, sh, ensure_dir, read_json, write_json, write_file, file_exists, rand_hex, lock, unlock, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
@@ -39,9 +41,10 @@ const MAX_UNPACKED = 16 * 1024 * 1024;
/**
* What is wrong with a configuration about to replace the current one
* (cursor `c` holds it): each server must have a valid, unique interface
* name that is not one of the router's own interfaces, a free subnet and a
* unique port, and the people and devices must be consistent
* (core.model_errors). [] when it can be used.
* name that is not one of the router's own interfaces, a free subnet, a
* unique port and disguise values AmneziaWG takes (awg.obf_unsafe), and the
* people and devices must be consistent (core.model_errors). [] when it can
* be used.
*/
export function config_errors(c) {
let m = core.load(c);
@@ -52,7 +55,7 @@ export function config_errors(c) {
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
for (let e in [ ...core.server_errors(m, srv, [ ...foreign, ...subnets ]), ...awg.obf_unsafe(srv.obf) ])
push(errs, sprintf(_('Server %s: %s'), srv.name, e));
if (ifnames[srv.ifname])
push(errs, sprintf(_('Server %s: interface %s is also used by %s.'), srv.name, srv.ifname, ifnames[srv.ifname]));
@@ -4,7 +4,7 @@
import { cursor } from 'uci';
import {
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
valid_name, valid_device_name, DEVICE_NAME_MAX, valid_key, valid_host, valid_iface, valid_date, slugify, host_label, ucut, name_rule, parse_cidr, cidr_overlaps, int2ip, ip2int,
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util';
import { _, N_ } from 'dawnline.i18n';
@@ -90,6 +90,8 @@ export function load(c) {
hostnames: g('hostnames'),
domain: g('domain'),
log_connections: g('log_connections'),
// What goes to syslog (dawnline.util syslog).
log_level: g('log_level'),
// Repair tunnels and services on its own (the agent, every minute).
watchdog: g('watchdog'),
// Second DNS for "home names" devices, used by the device when the tunnel is down.
@@ -199,6 +201,13 @@ export function load(c) {
created: toint(r.created, 0),
created_by: r.created_by ?? 'admin',
disabled: bool(r.disabled, false),
// The device's own link values (admin only): 0 / null = the server's
// (device_mtu, device_keepalive). Out of range is kept as read, so
// model_errors can name it; the configuration then uses the server's.
mtu: toint(r.mtu, 0),
keepalive: r.keepalive == null || r.keepalive == '' ? null : toint(r.keepalive, null),
// Its own local network stays outside the tunnel (awg.allowed_ips).
lan_bypass: bool(r.lan_bypass, false),
};
m.devices[id] = d;
if (m.people[d.person])
@@ -367,18 +376,40 @@ export function alloc_address(m, srv) {
*/
const AUTO_MTU = 1380;
const MOBILE_MTU = 1280;
/** What an MTU set by hand may be (the server's and a device's alike). */
export const MTU_RANGE = [ 1280, 1500 ];
/** What a keep-alive set by hand may be, in seconds (0 = off). */
export const KEEPALIVE_RANGE = [ 0, 600 ];
function in_range(n, r) {
return type(n) == 'int' && n >= r[0] && n <= r[1];
}
/** The server's tunnel MTU: the one set, or automatic for its disguise. */
export function tunnel_mtu(srv) {
return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
};
/** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
/**
* The MTU a device's configuration carries: the device's own when the admin
* set one, else the tunnel's, at most 1280 for phones and tablets.
*/
export function device_mtu(srv, dev) {
if (in_range(dev.mtu, MTU_RANGE))
return dev.mtu;
let mtu = tunnel_mtu(srv);
return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
};
/**
* The keep-alive a device's configuration carries, in seconds (0 = off): the
* device's own when the admin set one, else the server's. Both ends never
* have to agree on it (the server's peers carry none), so it is the device's.
*/
export function device_keepalive(srv, dev) {
return in_range(dev?.keepalive, KEEPALIVE_RANGE) ? dev.keepalive : srv.keepalive;
};
export function endpoint_host(m, srv) {
return srv.endpoint || m.settings.portal_host || '';
};
@@ -635,7 +666,7 @@ export function update_person(c, m, id, a) {
c.delete(CONFIG, id, 'home_net');
}
if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), valid_iface));
if (length(nets))
c.set(CONFIG, id, 'home_net', nets);
else
@@ -649,6 +680,8 @@ export function update_person(c, m, id, a) {
* Add a device for a person. `opts.keys` = { private_key?, public_key,
* preshared_key } from dawnline.awg (or a public key the browser generated).
* `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
* `opts.lan_bypass` true keeps the device's own local network outside the
* tunnel (awg.allowed_ips).
*/
export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {};
@@ -659,8 +692,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
if (!srv)
fail(_('The person has no server.'));
name = trim(name ?? '');
if (!valid_name(name))
fail(_('Enter a device name (up to 48 characters).'));
if (!valid_device_name(name))
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
if (index(KINDS, kind) < 0)
kind = 'other';
if (opts.by == 'portal' && length(p.devices) >= p.device_limit)
@@ -677,10 +710,15 @@ export function create_device(c, m, person_id, name, kind, opts) {
for (let o, d in m.devices)
if (d.public_key == k.public_key)
fail(_('This key is already in use.'));
// A server's own key (it is in every configuration): the kernel would silently ignore such a peer.
for (let sid, s in m.servers)
if (s.public_key == k.public_key)
fail(_('This key is already in use.'));
let id = `d_${rand_hex(4)}`;
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false,
mtu: 0, keepalive: null, lan_bypass: opts.lan_bypass === true };
c.set(CONFIG, id, 'device');
c.set(CONFIG, id, 'person', person_id);
c.set(CONFIG, id, 'name', name);
@@ -691,6 +729,8 @@ export function create_device(c, m, person_id, name, kind, opts) {
c.set(CONFIG, id, f, dev[f]);
c.set(CONFIG, id, 'created', `${dev.created}`);
c.set(CONFIG, id, 'created_by', dev.created_by);
if (dev.lan_bypass)
c.set(CONFIG, id, 'lan_bypass', '1');
// Keep the in-memory model consistent for callers that continue.
m.devices[id] = dev;
@@ -703,8 +743,8 @@ export function rename_device(c, m, id, name) {
if (!d)
fail(_('Unknown device.'));
name = trim(name ?? '');
if (!valid_name(name))
fail(_('Enter a device name (up to 48 characters).'));
if (!valid_device_name(name))
fail(sprintf(_('Enter a device name: up to %d letters, digits, spaces and - _ .'), DEVICE_NAME_MAX));
for (let o in m.people[d.person]?.devices ?? [])
if (o != id && lc(m.devices[o].name) == lc(name))
fail(sprintf(_('"%s" already exists.'), name));
@@ -712,6 +752,63 @@ export function rename_device(c, m, id, name) {
d.name = name;
};
/**
* The admin's link settings of a device: `a` = { mtu?, keepalive?,
* lan_bypass? }, only keys present change; '' takes a number back to the
* server's (0 is a keep-alive of its own: off). Each is in the device's
* configuration alone (the server's peers carry neither), so a change asks
* that device to import again and touches nothing on the router. Returns the
* names of the options that changed.
*/
export function set_device_link(c, m, id, a) {
let d = m.devices[id];
if (!d)
fail(_('Unknown device.'));
let changed = [];
let put = (k, v, was) => {
if (v == was)
return;
if (v == null)
c.delete(CONFIG, id, k);
else
c.set(CONFIG, id, k, `${v}`);
push(changed, k);
};
let number = (v, r, msg) => {
let s = trim(`${v}`);
if (s == '')
return null;
if (!match(s, /^[0-9]{1,4}$/) || +s < r[0] || +s > r[1])
fail(msg);
return +s;
};
if (a.mtu != null)
put('mtu', number(a.mtu, MTU_RANGE, _('MTU must be 1280-1500.')), d.mtu || null);
if (a.keepalive != null)
put('keepalive', number(a.keepalive, KEEPALIVE_RANGE, _('Keep-alive must be 0-600 seconds.')), d.keepalive);
if (a.lan_bypass != null)
put('lan_bypass', a.lan_bypass === true ? 1 : null, d.lan_bypass ? 1 : null);
return changed;
};
/**
* Change what a device is (one of KINDS): true when it changed, false when it
* already was. Its configuration follows (device_mtu: phones and tablets take
* smaller packets); nothing on the router changes.
*/
export function set_device_kind(c, m, id, kind) {
let d = m.devices[id];
if (!d)
fail(_('Unknown device.'));
if (index(KINDS, kind) < 0)
fail(_('Unknown device type.'));
if (kind == d.kind)
return false;
c.set(CONFIG, id, 'kind', kind);
d.kind = kind;
return true;
};
export function delete_device(c, m, id) {
let d = m.devices[id];
if (!d)
@@ -781,10 +878,12 @@ export function server_errors(m, srv, others_subnets) {
* an address outside their server's subnet, the server's own address, a
* prefix on it or one shared with another device (the access sets are keyed
* by address, and one bad peer line makes `awg syncconf` refuse the whole
* server), malformed keys, people and devices pointing at servers, people,
* circles or services that do not exist, and two people with one link. [] when
* it is consistent. Import, restore and Health check it; the runtime sync
* skips what it would reject (dawnline.awg, dawnline.nft).
* server), malformed keys, an MTU or keep-alive of their own out of range,
* people and devices pointing at servers, people, circles or services that do
* not exist, and two people with one link. [] when it is consistent. Import,
* restore and Health check it; the runtime sync skips what it would reject
* (dawnline.awg, dawnline.nft), and a configuration takes the server's value
* for a link value out of range (device_mtu, device_keepalive).
*/
export function model_errors(m) {
let errs = [];
@@ -816,6 +915,11 @@ export function model_errors(m) {
say(_('Device %s of %s: the private key is not a key.'));
if (d.preshared_key != '' && !valid_key(d.preshared_key))
say(_('Device %s of %s: the preshared key is not a key.'));
// Its own link values (0 / null: the server's); one out of range is never used.
if (d.mtu && !in_range(d.mtu, MTU_RANGE))
say(_('Device %s of %s: MTU %d is not between 1280 and 1500.'), d.mtu);
if (d.keepalive != null && !in_range(d.keepalive, KEEPALIVE_RANGE))
say(_('Device %s of %s: keep-alive %d is not between 0 and 600 seconds.'), d.keepalive);
let n = ip2int(d.address);
if (n == null) {
if (d.address)
@@ -825,6 +929,9 @@ export function model_errors(m) {
continue;
}
let srv = m.servers[p.server];
// AmneziaWG ignores a peer with the interface's own key (dawnline.awg tunnel_devices leaves it out).
if (srv?.public_key && d.public_key == srv.public_key)
say(_("Device %s of %s: the public key is the server's own."));
let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last))
say(_("Device %s of %s: address %s is outside %s's tunnel %s."), d.address, srv.name, srv.subnet);
@@ -895,7 +1002,7 @@ export function wan_forwards(zone, proto) {
c.load('firewall');
let out = [];
c.foreach('firewall', 'redirect', (r) => {
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
if (substr(r['.name'], 0, 9) == 'dawnline_' || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT' || r.src != zone)
return;
// fw4's default is "tcp udp".
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
@@ -29,6 +29,22 @@ export function need_awg() {
}
};
/**
* What a device_changed event says changed: each option with its new value
* ("lan_bypass=on", "mtu=1400", "keepalive=auto": '' is the server's again,
* "kind=phone"), so the activity log can say what it became.
*/
function change_detail(names, ch) {
return join(', ', map(names, (k) => {
if (k == 'lan_bypass')
return `lan_bypass=${ch.lan_bypass === true ? 'on' : 'off'}`;
if (k == 'kind')
return `kind=${ch.kind}`;
let v = trim(`${ch[k] ?? ''}`);
return `${k}=${v == '' ? 'auto' : v}`;
}));
}
/** The device `id` as `opts` may touch it (inside a transaction's model). */
function own(m, id, opts) {
let d = m.devices[id];
@@ -39,11 +55,15 @@ function own(m, id, opts) {
return d;
}
/** New device with fresh keys (or the browser's public key): { id, config }. */
/**
* New device with fresh keys (or the browser's public key): { id, config }.
* `opts.lan_bypass` true keeps its own local network outside the tunnel.
*/
export function add(person, name, kind, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind, { by, keys: awg.new_keys(opts.public_key || null) }));
let id = store.transact((c, m) => core.create_device(c, m, person, name, kind,
{ by, keys: awg.new_keys(opts.public_key || null), lan_bypass: opts.lan_bypass === true }));
let s = apply.sync();
let m = core.load();
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
@@ -52,14 +72,23 @@ export function add(person, name, kind, opts) {
};
/**
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
* the admin turns devices off. Returns the runtime sync.
* Rename and/or turn a device off or on, or change how it connects (`ch` =
* { name?, disabled?, mtu?, keepalive?, lan_bypass? }, see
* core.set_device_link); only the admin turns devices off or sets the MTU and
* keep-alive, the portal may switch LAN Bypass (the device then takes its
* updated configuration, keys unchanged). Returns the runtime sync ({} after a
* change of the link values alone: they are in the device's configuration,
* nothing on the router changes).
*/
export function update(id, ch, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
if (ch.disabled != null && by != 'admin')
die(_('Only the admin can turn devices off.'));
let link = ch.mtu != null || ch.keepalive != null || ch.lan_bypass != null;
if ((ch.mtu != null || ch.keepalive != null) && by != 'admin')
die(_('Only the admin can change how a device connects.'));
let linked = [];
let d0 = store.transact((c, m) => {
let d = own(m, id, opts);
let was = { ...d };
@@ -71,24 +100,43 @@ export function update(id, ch, opts) {
else
c.delete(core.CONFIG, id, 'disabled');
}
if (link)
linked = core.set_device_link(c, m, id, ch);
return was;
});
let r = apply.sync();
let r = ch.name != null || ch.disabled != null ? apply.sync() : {};
if (ch.disabled != null && !!ch.disabled != !!d0.disabled)
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: ch.disabled ? 'turned off' : 'turned on', by });
else if (ch.name != null && ch.name != d0.name)
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: `renamed from ${d0.name}`, by });
// The options with what they became (change_detail).
if (length(linked))
live.add_event({ type: 'device_changed', person: d0.person, device: id, detail: change_detail(linked, ch), by });
return r;
};
/** New keys for a device: returns its new configuration. */
export function rotate(id, opts) {
/*
* New keys for a device: returns its new configuration, marked as issued (it
* goes to the set-up sheet; the device then waits for it as "Not set up yet",
* not as "settings changed"). Only through reconnect: new keys always mean
* setting the device up again.
*/
function rotate(id, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
store.transact((c, m) => {
own(m, id, opts);
let changed = [];
let person = store.transact((c, m) => {
let d = own(m, id, opts);
if (opts.kind != null && core.set_device_kind(c, m, id, opts.kind))
push(changed, 'kind');
if (opts.lan_bypass != null)
push(changed, ...core.set_device_link(c, m, id, { lan_bypass: opts.lan_bypass === true }));
core.rotate_device(c, m, id, awg.new_keys());
return d.person;
});
if (length(changed))
live.add_event({ type: 'device_changed', person, device: id, by,
detail: change_detail(changed, { kind: opts.kind, lan_bypass: opts.lan_bypass === true }) });
// The device a portal page came through would lose its tunnel before the
// answer gets out: load the new key a moment after answering.
let s = null;
@@ -104,14 +152,17 @@ export function rotate(id, opts) {
if (s?.warning)
cfg.warning = s.warning;
return cfg;
};
}
/**
* Set a device up from scratch (a new phone, the app reinstalled, settings
* the admin changed): new keys, so the configuration it holds stops working
* with the sync, and it counts as not set up until it connects with the new
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
* it. Returns the new configuration, as rotate.
* the admin changed; the portal's Reconnect and the admin's New keys): new
* keys, so the configuration it holds stops working with the sync, and it
* counts as not set up until it connects with the new one. The usage keeps
* the old keys' last handshake: awg.handshake_since hides it. `opts.kind` and
* `opts.lan_bypass` (the portal's Reconnect: what it is, LAN Bypass) change
* with the keys, in the same write. Returns the new configuration (with
* `warning` when the sync did not fully take).
*/
export function reconnect(id, opts) {
opts ??= {};
@@ -5,7 +5,7 @@
// named dawnline_* are ever changed.
import { readfile, unlink } from 'fs';
import { q, sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, RUN_DIR } from 'dawnline.util';
import { sh, sh_out, uniq, in_nets, uci_put, uci_section, ack_config, write_file, syslog, opts_text, RUN_DIR } from 'dawnline.util';
import { cursor } from 'uci';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
@@ -33,12 +33,21 @@ export function sync(m, dry) {
let c = cursor();
c.load('firewall');
let changed = false, want = {};
// What changed, section by section, for syslog once it is saved (a dry run says nothing).
let notes = [];
let sec = (name, stype, opts) => {
want[name] = true;
changed = uci_section(c, 'firewall', name, stype) || changed;
let created = uci_section(c, 'firewall', name, stype), diff = {};
for (let k, v in opts)
changed = uci_put(c, 'firewall', name, k, v) || changed;
if (uci_put(c, 'firewall', name, k, v))
diff[k] = v;
if (created || length(keys(diff))) {
changed = true;
push(notes, [ 'info', `${stype} ${name}: ${created ? 'created' : 'updated'} · ${opts_text(created ? opts : diff)}` ]);
}
else
push(notes, [ 'debug', `${stype} ${name}: unchanged` ]);
};
let snap = net.snapshot(true);
@@ -126,21 +135,24 @@ export function sync(m, dry) {
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
if (substr(s['.name'], 0, 9) == 'dawnline_' && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
push(notes, [ 'info', `${c.get('firewall', s) ?? 'section'} ${s}: removed` ]);
c.delete('firewall', s);
changed = true;
}
if (dry)
return changed;
for (let n in notes)
syslog(n[0], 'firewall', n[1]);
if (changed) {
c.commit('firewall');
ack_config([ 'firewall' ]);
syslog('info', 'firewall', 'fw4 -q reload');
system('fw4 -q reload');
system("logger -t dawnline 'firewall updated'");
}
return changed;
};
@@ -170,6 +182,9 @@ export function drift(m) {
};
const MARK_ALL = 0xffffffff;
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff". A module
// constant, compiled once, not for each rule.
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/;
function hx(n) {
return sprintf('0x%x', n);
@@ -184,8 +199,7 @@ export function proxy_diverts() {
let out = [], seen = {};
for (let fam in [ '-4', '-6' ])
for (let line in split(sh_out(`ip ${fam} rule show 2>/dev/null`) ?? '', '\n')) {
// "1000: from all fwmark 0x1 lookup 100", or "fwmark 0x1/0xff".
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x([0-9a-f]+))?.* lookup (\S+)/);
let mm = match(line, MARK_RULE);
if (!mm || +mm[1] >= 32766)
continue;
let d = { pref: +mm[1], mark: hex(mm[2]), mask: mm[4] ? hex(mm[4]) : MARK_ALL, table: mm[5] };
@@ -266,18 +280,24 @@ export function sync_reply_routes(m) {
}
let s = reply_script(m, proxy_diverts());
if (s == '') {
if (reply_loaded())
if (reply_loaded()) {
syslog('info', 'nftables', `table inet ${REPLY_TABLE}: removed (no proxy to keep Dawnline's answers out of)`);
system(`nft delete table inet ${REPLY_TABLE} 2>/dev/null`);
}
unlink(REPLY_SIG);
return;
}
if (s == readfile(REPLY_SIG) && reply_loaded())
if (s == readfile(REPLY_SIG) && reply_loaded()) {
syslog('debug', 'nftables', `table inet ${REPLY_TABLE}: unchanged`);
return;
}
let err = nft.load(`table inet ${REPLY_TABLE}\ndelete table inet ${REPLY_TABLE}\n${s}`);
if (err) {
unlink(REPLY_SIG);
system(`logger -t dawnline -p user.err ${q('reply table: ' + err)}`);
syslog('error', 'nftables', `table inet ${REPLY_TABLE}: loading failed · ${err}`);
return;
}
syslog('info', 'nftables', `table inet ${REPLY_TABLE}: loaded · ${length(match(s, /\n/g) ?? []) + 1} lines (Dawnline's own answers kept out of proxies)`);
syslog('debug', 'nftables', `table inet ${REPLY_TABLE}: ${s}`);
write_file(REPLY_SIG, s, 0o644);
};
@@ -79,14 +79,17 @@ function cached(key, ttl, fn) {
/* ---------- releases ---------- */
function slim(x) {
let digests = {};
for (let a in x.assets ?? [])
let digests = {}, ids = {};
for (let a in x.assets ?? []) {
if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/))
digests[a.name] = substr(a.digest, 7);
if (type(a.id) == 'int' && a.id > 0)
ids[a.name] = a.id;
}
return {
tag: x.tag_name, name: x.name ?? x.tag_name, published: x.published_at ?? null,
prerelease: !!x.prerelease, url: x.html_url ?? null, body: substr(x.body ?? '', 0, 12000),
assets: map(x.assets ?? [], (a) => a.name), digests,
assets: map(x.assets ?? [], (a) => a.name), digests, ids,
};
}
@@ -194,6 +197,25 @@ export function sha256(path) {
return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1];
};
/** A release file's URL on github.com in parts: { repo, tag, name }, or null for any other URL. */
export function release_file(url) {
let m = match(url ?? '', /^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/releases\/download\/([^\/?#]+)\/([^\/?#]+)$/);
return m ? { repo: m[1], tag: m[2], name: m[3] } : null;
};
/** The same file through the API (api.github.com), when its release is known; else null. */
function asset_api_url(url) {
let f = release_file(url);
if (!f)
return null;
let id = null;
try {
id = release(f.repo, f.tag)?.ids?.[f.name];
}
catch (e) {}
return id ? `https://api.github.com/repos/${f.repo}/releases/assets/${id}` : null;
}
/**
* Download to a file. o: { sha256, mirrors, log }. Direct first; mirrors
* only when the sha256 is known (from the API) and mirrors are allowed. A
@@ -203,24 +225,32 @@ export function sha256(path) {
export function download(url, dest, o) {
o ??= {};
let want = o.sha256 ? lc(o.sha256) : null;
let tries = [ url ];
let curl = have_curl();
let tries = [];
// Without curl a release file comes through the API first: github.com's redirect to it carries a
// Content-Security-Policy header that can outgrow uclient-fetch's 4 KB line buffer, and it stalls there.
let api = curl ? null : asset_api_url(url);
if (api)
push(tries, { u: api, accept: 'application/octet-stream' });
push(tries, { u: url });
let direct = length(tries);
if (want && o.mirrors && match(url, /^https:\/\/(github\.com|raw\.githubusercontent\.com)\//))
for (let m in MIRRORS)
push(tries, m + url);
for (let i, u in tries) {
let host = replace(u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (i > 0)
push(tries, { u: m + url, mirror: true });
for (let i, t in tries) {
let host = replace(t.u, /^https:\/\/([^\/]+)\/.*$/, '$1');
if (t.mirror)
o.log?.(sprintf(_('Trying mirror %s'), host));
let r = have_curl()
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
let r = curl
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(t.u)}`)
: run(`uclient-fetch -q -T 30 ${t.accept ? `--header=${q('Accept: ' + t.accept)} ` : ''}-O ${q(dest)} ${q(t.u)}`);
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
if (!want || sha256(dest) == want)
return u;
return t.u;
o.log?.(sprintf(_("Warning: %s sent a file that does not match GitHub's sha256, discarded"), host));
}
system(`rm -f ${q(dest)}`);
if (i == 0 && length(tries) > 1)
if (i == direct - 1 && length(tries) > direct)
o.log?.(_('GitHub did not answer, trying mirrors'));
}
return null;
@@ -45,19 +45,27 @@ export function needs() {
};
};
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
// A module constant, compiled once: a literal in the loop would be compiled
// again for every socket (0.12 ms each on the WR3000P, some 90 sockets a call).
const UDP_UNCONNECTED = /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /;
/** UDP ports an unconnected socket is bound to (IPv4 and IPv6): nothing else can listen there. */
export function udp_bound() {
let out = {};
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
for (let line in split(readfile(f) ?? '', '\n')) {
// " 12: 00000000:1194 00000000:0000 07 …": local address, then the remote one (none).
let m = match(line, /^ *[0-9]+: [0-9A-F]+:([0-9A-F]{4}) [0-9A-F]+:0000 /);
let m = match(line, UDP_UNCONNECTED);
if (m)
out[hex(m[1])] = true;
}
return map(keys(out), (k) => +k);
};
// netstat's columns and the port of "0.0.0.0:53" / ":::53". Module constants,
// compiled once, not for each socket.
const BLANKS = /[ \t]+/, PORT_SUFFIX = /:([0-9]+)$/;
/**
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
* Kernel sockets (a tunnel's) have no name.
@@ -65,10 +73,10 @@ export function udp_bound() {
function port_programs(proto) {
let out = {};
for (let line in split(sh_out(`netstat -ln${proto == 'tcp' ? 't' : 'u'}p 2>/dev/null`) ?? '', '\n')) {
let f = split(trim(line), /[ \t]+/);
let f = split(trim(line), BLANKS);
if (f[0] != proto && f[0] != `${proto}6`)
continue;
let m = match(f[3] ?? '', /:([0-9]+)$/);
let m = match(f[3] ?? '', PORT_SUFFIX);
let owner = split(f[length(f) - 1], '/');
if (!m || !owner[1] || out[m[1]])
continue;
@@ -215,23 +223,138 @@ export function wan_kind(wan) {
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
};
const HEX = '0123456789abcdef';
// An IPv6 address as its 32 hex digits, so two spellings of one address
// compare equal (2001:DB8::1, 2001:db8:0::1, as typed or as a tool prints
// it); null when it is none. No regex: the router's addresses and a name's
// AAAA records go through it on every look.
function ip6_full(s) {
if (type(s) != 'string')
return null;
let halves = split(lc(s), '::');
if (length(halves) > 2)
return null;
let head = halves[0] != '' ? split(halves[0], ':') : [];
let tail = length(halves) == 2 && halves[1] != '' ? split(halves[1], ':') : [];
let gap = 8 - length(head) - length(tail);
if (length(halves) == 2 ? gap < 1 : gap != 0)
return null;
let groups = [ ...head ];
for (let i = 0; i < gap; i++)
push(groups, '0');
push(groups, ...tail);
let out = '';
for (let g in groups) {
if (length(g) < 1 || length(g) > 4 || ltrim(g, HEX) != '')
return null;
out += substr(`0000${g}`, length(g));
}
return out;
}
/**
* The router's public IPv6 addresses in `ip -6 -j addr show scope global`
* output (`links`), on any interface: a DDNS client may publish the LAN's
* address from the delegated prefix, which reaches the router too. Unique
* local addresses (fc00::/7: OpenWrt gives the LAN one even without IPv6
* from the ISP) and failed duplicates do not count: nothing reaches them from
* outside. [] when there is none.
*/
export function own_ipv6(links) {
let out = [];
for (let l in (type(links) == 'array' ? links : []))
for (let a in l?.addr_info ?? []) {
let k = ip6_full(a?.local);
if (k && a.family == 'inet6' && !a.dadfailed && substr(k, 0, 2) != 'fc' && substr(k, 0, 2) != 'fd')
push(out, a.local);
}
return out;
};
// The router's public IPv6 addresses (own_ipv6), or null when `ip` could not tell.
function router_ipv6() {
let out = sh_out('ip -6 -j addr show scope global');
if (out == null)
return null;
try {
let links = json(out || '[]');
return type(links) == 'array' ? own_ipv6(links) : null;
}
catch (e) {
// No JSON (an `ip` without -j): unknown, so the AAAA records get no verdict.
return null;
}
}
// What the facts are made from, read on the router.
function endpoint_reads(srv, host) {
let ips = host ? lookup.resolve(host) : [];
// The router's IPv6 only when the name has some to compare with.
return {
ips, wan: srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan'),
router6: length(filter(ips, (a) => ip2int(a) == null)) ? router_ipv6() : null,
};
}
/**
* What a public address points at, for Health and the "as you type" check on
* the server page: { host, ips, ips4, ips6, wan, kind (wan_kind), cloudflare,
* here (an IPv4 of it is this router's WAN), v6_only }.
* here (an IPv4 of it is this router's WAN), v6_only, router6 (the router's
* public IPv6 addresses, own_ipv6; null when unknown, or not read because the
* name has no IPv6), foreign6 (its IPv6 addresses that are none of those, all
* of them when the router has none; null while router6 is), here6 (it has
* IPv6 addresses and each is one of the router's) }. `reads` (a test's)
* stands for what is read on the router: { ips, wan, router6 }.
*/
export function endpoint_facts(srv, host) {
let ips = host ? lookup.resolve(host) : [];
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
export function endpoint_facts(srv, host, reads) {
let r = reads ?? endpoint_reads(srv, host);
let ips = r.ips ?? [], wan = r.wan ?? null;
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
let own = r.router6 != null ? map(r.router6, ip6_full) : null;
let foreign6 = own != null ? filter(ips6, (a) => index(own, ip6_full(a)) < 0) : null;
return {
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
host, ips, ips4, ips6, wan, kind: wan_kind(wan),
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
here: wan != null && index(ips4, wan) >= 0,
v6_only: !length(ips4) && length(ips6) > 0,
router6: r.router6 ?? null, foreign6,
here6: foreign6 != null && length(ips6) > 0 && !length(foreign6),
};
};
/*
* The name's IPv6 addresses that do not reach this router from outside, in
* words, or null (each is a public one of the router, or those are unknown).
* A name with IPv4 too: devices that prefer IPv6 take these and fail, the
* others connect.
*/
function aaaa_words(f) {
let bad = f.foreign6 ?? [], n = length(bad);
if (!n)
return null;
if (!length(f.router6))
return sprintf(N_(n, '%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove this AAAA record or set up IPv6 on the router.',
'%s AAAA → %s, but this router has no public IPv6 address: devices that prefer IPv6 will fail to connect. Remove these AAAA records or set up IPv6 on the router.'),
f.host, join(', ', bad));
return sprintf(N_(n, '%s AAAA → %s is not a public address of this router: devices that prefer IPv6 will fail to connect. Fix or remove this AAAA record.',
'%s AAAA → %s are not public addresses of this router: devices that prefer IPv6 will fail to connect. Fix or remove these AAAA records.'),
f.host, join(', ', bad));
}
// An IPv6-only name none of whose addresses is a public one of the router: no device connects. Null otherwise.
function v6_only_unreached(f) {
let n = length(f.foreign6 ?? []);
if (!n || n < length(f.ips6))
return null;
if (!length(f.router6))
return sprintf(_('%s → %s: IPv6 only, but this router has no public IPv6 address: no device can connect. Check your DNS / DDNS, or set up IPv6 on the router.'),
f.host, join(', ', f.ips6));
return sprintf(N_(n, '%s → %s: IPv6 only, and not a public address of this router: no device can connect. Check your DNS / DDNS.',
'%s → %s: IPv6 only, and not public addresses of this router: no device can connect. Check your DNS / DDNS.'),
f.host, join(', ', f.ips6));
}
/**
* The facts in words, in the language of the call: { status: ok|warn|error, text }
* (text a whole sentence). `proto_note` names what must get through ("UDP 4500").
@@ -244,18 +367,28 @@ export function endpoint_words(f, proto_note) {
if (f.cloudflare)
return { status: 'error', text: sprintf(_("%s → %s (Cloudflare). %s reaches the router only if this name is DNS-only there, or use the router's IP."),
f.host, join(', ', f.ips), proto_note) };
if (f.v6_only)
let v6 = aaaa_words(f);
if (f.v6_only) {
let none = v6_only_unreached(f);
if (none != null || v6 != null)
return { status: 'warn', text: none ?? v6 };
return { status: f.kind == 'public' ? 'warn' : 'ok', text: f.kind == 'public'
? sprintf(_("%s → %s: IPv6 only, so only devices with IPv6 connect (the router's IPv4 %s has no name)."), f.host, join(', ', f.ips6), f.wan)
: sprintf(_('%s → %s: IPv6 only, so only devices with IPv6 connect.'), f.host, join(', ', f.ips6)) };
}
let v4 = null;
if (f.kind == 'cgnat' || f.kind == 'private')
return { status: 'warn', text: f.kind == 'cgnat'
v4 = f.kind == 'cgnat'
? sprintf(_('The WAN address %s is CGNAT (shared by the ISP): %s cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.'), f.wan, proto_note)
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note) };
if (f.wan && !f.here)
return { status: 'warn', text: sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan) };
: sprintf(_('The WAN address %s is private: this router is behind another one. Forward %s on it, or devices cannot connect.'), f.wan, proto_note);
else if (f.wan && !f.here)
v4 = sprintf(_('%s points at %s, not this router (WAN %s). Check your DNS / DDNS.'), f.host, join(', ', f.ips4), f.wan);
// Two separate facts, each a sentence of its own: the IPv4 one first.
if (v4 != null || v6 != null)
return { status: 'warn', text: join(' ', filter([ v4, v6 ], (x) => x != null)) };
// Without the router's WAN address only the facts: names and addresses, no words.
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, f.wan) : `${f.host} → ${join(', ', f.ips)}` };
return { status: 'ok', text: f.here ? sprintf(_('%s points at this router (%s).'), f.host, join(', ', [ f.wan, ...(f.here6 ? f.ips6 : []) ]))
: `${f.host} → ${join(', ', f.ips)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
@@ -264,6 +397,9 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
return check(id, title, w.status, w.text, null, problem);
}
// "1000: from all fwmark 0x1 lookup 100". A module constant, compiled once, not for each rule.
const MARK_RULE = /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/;
/**
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
* Dawnline's (pref < 5205) whose table has a default route of its own sends
@@ -273,7 +409,7 @@ function endpoint_check(id, title, problem, srv, host, proto_note) {
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
let mm = match(line, MARK_RULE);
if (!mm || +mm[1] >= 5205)
continue;
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
@@ -321,9 +457,53 @@ function awg_check() {
}
if (!st.handler)
return check('awg', title, 'error', no_proto(), 'netrestart', _('The network doesn’t know AmneziaWG yet'));
// The install could not swap the loaded module: the old one runs until the next boot (dawnline.awg_builds).
if (builds.waits_for_reboot())
return check('awg', title, 'warn', _('The AmneziaWG update is installed and starts after a reboot.'), null,
_('The AmneziaWG update waits for a reboot'));
return check('awg', title, 'ok', _('Kernel module, awg tool and the netifd protocol are present.'));
}
/**
* The /24s home routers come with out of the box. A home network on one of
* them is very likely the same as the network a person connects from, and
* home access then takes those addresses into the tunnel: their own printer or
* TV is out of reach while connected, LAN Bypass or not.
*/
const COMMON_HOME = [
'192.168.0.0/24', '192.168.1.0/24', '192.168.2.0/24', '192.168.3.0/24', '192.168.8.0/24', '192.168.10.0/24',
'192.168.31.0/24', '192.168.50.0/24', '192.168.88.0/24', '192.168.100.0/24', '192.168.178.0/24',
'10.0.0.0/24', '10.1.1.0/24',
];
/** The home networks in `nets` that overlap a common out-of-the-box subnet. */
export function common_home(nets) {
return filter(nets ?? [], (n) => {
let a = parse_cidr(n);
return a && length(filter(COMMON_HOME, (c) => cidr_overlaps(a, parse_cidr(c))));
});
};
/**
* Whether the server's home networks are on a common subnet, while anyone on
* it has home access (otherwise nothing of home goes into the tunnel). A
* warning on Health only: advice, not a fault, so no notice elsewhere.
*/
function home_check(m, id, srv, label) {
let reach = filter(values(m.people), (p) => p.server == id && (p.access == 'lan' || p.access == 'both'));
let nets = net.server_net(srv).nets;
if (!length(reach) || !length(nets))
return null;
let bad = common_home(nets);
let c = check(`homenet_${id}`, _('Home network addresses') + label, length(bad) ? 'warn' : 'ok',
length(bad)
? sprintf(_('%s is one of the most common home subnets. On a network with the same addresses, people with home access reach your home instead of their own: their printer or TV there is out of reach while connected, with LAN Bypass too. A rarer subnet for your home network avoids it, for example 10.37.12.0/24.'), join(', ', bad))
: sprintf(_('%s is not a common home subnet: the networks people connect from rarely use the same addresses.'), join(', ', nets)),
null);
c.problem = null;
return c;
}
/** Checks of a server's AmneziaWG tunnel. */
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let out = [];
@@ -339,26 +519,15 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
!st ? sprintf(_('%s does not exist.'), srv.ifname) :
length(codes) ? sprintf(_('%s is down: %s.'), srv.ifname, join(', ', codes)) : sprintf(_('%s is down.'), srv.ifname),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply'), down));
if (up) {
// By key, not by count: a stale peer standing in for a missing one would
// make the numbers match.
let states = apply.states_for(m, core.load_usage());
let wanted = {}, expected = 0;
for (let did, d in m.devices) {
let p = m.people[d.person];
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
wanted[d.public_key] = true;
expected++;
}
}
let loaded = {}, actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname) {
loaded[k] = true;
actual++;
}
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
// The devices the sync loads, by the same choice the agent compares with every minute.
if (up && dmp.reads[srv.ifname] == 'error')
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, 'warn',
_('The tunnel could not be read, so its devices could not be checked.'), null,
_('The devices in AmneziaWG could not be checked') + label));
else if (up) {
let devs = awg.tunnel_devices(m, id, apply.states_for(m, core.load_usage()));
let diff = awg.peer_diff(devs, dmp, srv.ifname);
let expected = length(devs), missing = diff.missing, extra = diff.extra, actual = diff.loaded;
let same = !missing && !extra;
push(out, check(`peers_${id}`, _('AmneziaWG devices loaded') + label, same ? 'ok' : 'warn',
same ? sprintf(N_(actual, '%d device is loaded in the tunnel.', '%d devices are loaded in the tunnel.'), actual) :
@@ -395,6 +564,9 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
push(out, check(`subnet_${id}`, _('AmneziaWG subnet is unique') + label, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? sprintf(_('%s overlaps %s.'), srv.subnet, join(', ', overlaps)) : sprintf(_('%s does not overlap other networks.'), srv.subnet),
null, _('AmneziaWG subnet overlaps another network') + label));
let home = home_check(m, id, srv, label);
if (home)
push(out, home);
return out;
}
@@ -0,0 +1,433 @@
// Dawnline — how each device's link behaves, from the counters the agent's
// watcher reads every second (dawnline.awg.dump): a device that knocks but
// never finishes connecting, one whose configuration is in use on two devices,
// one whose traffic the router drops, one whose connection keeps breaking.
//
// The agent keeps one history per device in memory (fresh(), observe(): a few
// events of the last HISTORY seconds, not one entry per tick), classifies it
// (classify(), pure) and shows a state only once it held HOLD seconds
// (settle()). It writes what is shown to dawnline.live.LINK on a change; the
// read side (live.dump's `link`, view.device_view) is dawnline.live's, so the
// portal never loads this module. Who is online stays live.PRESENCE's.
//
// The same history tells the set-up sheet, at once and without HOLD, what a
// device that is being set up does right now (setup_state(), setup()): it
// knocks without finishing, data flows, or it connected but nothing it sends
// comes through. The agent writes that to dawnline.live.SETUP on a change.
//
// What the counters mean (kmod 3.1, receive.c and send.c):
// * an accepted handshake initiation adds exactly INITIATION bytes to the
// peer's rx: the S1 prefix and any trailer are cut off and the header
// protection is undone in place before update_rx_stats(skb->len). The
// router answers it; its own handshake time moves only when the first
// packet under the new keys arrives.
// * a keepalive adds KEEPALIVE plus its content padding; a handshake
// response (the router initiated) RESPONSE; data 32 + its padded length.
// Plain data is a multiple of 16, so 148, 296 and 444 never are data.
// * a data packet the router then drops (its source is not the device's
// address: an old configuration after renumbering; this is what moves
// the interface's rx_frame_errors) adds nothing to rx, but the router
// still answers it with a keepalive within KeepaliveTimeout (about 10 s).
/** Seconds of events kept per device. */
export const HISTORY = 600;
/** A state is shown once it held this long (a flapping mobile link passes). */
export const HOLD = 180;
/** A device is classified at least this often when nothing happened (its spans age). */
export const CHECK_EVERY = 15;
/** Bytes an accepted initiation adds to rx (sizeof(struct message_handshake_initiation)). */
export const INITIATION = 148;
/** Bytes a handshake response adds to rx (the router initiated). */
export const RESPONSE = 92;
/** Bytes an empty data packet adds to rx, before content padding. */
export const KEEPALIVE = 32;
// Random trailers without content padding: a keepalive grows up to a full packet.
const TRAILER_MAX = 1500;
// Initiations a device sends at most in one second (retries are 5 s apart).
const KNOCKS_PER_TICK = 3;
/** trying: at least TRY_KNOCKS accepted initiations within TRY_SPAN seconds while not online. */
export const TRY_SPAN = 120;
export const TRY_KNOCKS = 3;
/*
* Churning: at least CHURN_COUNT handshakes within CHURN_SPAN seconds, with
* CHURN_COUNT - 1 of the gaps under CHURN_GAP seconds. A device that is
* there renews its keys every 100-120 s (RekeyAfterTime), more only when
* its packets get nothing back (KeepaliveTimeout + RekeyTimeout, ~15 s).
*/
export const CHURN_SPAN = 300;
export const CHURN_COUNT = 4;
export const CHURN_GAP = 45;
/** shared: while churning, the endpoint (ip:port) went back to an earlier one this often. */
export const SHARE_RETURNS = 2;
/*
* dropped: online with a handshake within DROP_HS seconds, nothing but
* handshakes and keepalives received for DROP_SPAN seconds, and the router
* sent something at least DROP_ANSWERS times in that span with nothing
* coming in (its keepalives answering packets it dropped), under DROP_TX
* bytes in all (a real download is far more).
*/
export const DROP_SPAN = 180;
export const DROP_HS = 240;
export const DROP_ANSWERS = 6;
export const DROP_TX = 65536;
/** Every state classify() can give. */
export const STATES = [ 'trying', 'shared', 'dropped', 'unstable' ];
/*
* The set-up sheet's trying: at least SETUP_KNOCKS accepted initiations
* within SETUP_SPAN seconds, none of them followed by a handshake. A device
* retries every 5 s, so it shows with the second (5-6 s in) and goes about
* 15 s after the last.
*/
export const SETUP_SPAN = 20;
export const SETUP_KNOCKS = 2;
/*
* nodata: online for SETUP_QUIET seconds since the handshake its session
* began with, nothing but handshakes and keepalives in since, and the router
* answered at least once with nothing coming in (a keepalive for data it
* dropped, about 10 s after it: an old address in the configuration). An
* idle device gets no answers, so it never shows.
*/
export const SETUP_QUIET = 15;
// Per list, the newest entries kept (a device whose endpoint flips every second).
const KEEP = 64;
function keep(list, entry) {
push(list, entry);
if (length(list) > KEEP)
shift(list);
}
/**
* A new, empty history for a device first seen at `now`. Fields: rx, tx
* (the counters last read, null before the first read), hs (the newest
* handshake), ep (the endpoint), data (when rx last carried data), hsev
* (handshake times), epev ([ ts, ip:port, the one before ] endpoint
* changes), knocks (times
* of accepted initiations), ans ([ ts, bytes ] the router sent with nothing
* received), state/since (what is shown), pend (a state waiting for HOLD),
* raw (the last classification), checked (when it was made); for the set-up
* sheet (setup()): on (online at the last read), sess (the handshake its
* online stretch began with, 0 while away), setup ({ state, since } or null)
* and due (when setup_state() may change with time alone, 0 for never).
*/
export function fresh(now) {
return {
start: now, rx: null, tx: null, hs: 0, ep: null, data: 0,
hsev: [], epev: [], knocks: [], ans: [],
state: null, since: 0, pend: null, raw: null, checked: 0,
on: false, sess: 0, setup: null, due: 0,
};
};
/**
* The largest rx a keepalive adds for a server's disguise: KEEPALIVE plus
* the top of its ContentPaddingAddition, or a full packet with random
* trailers and no content padding (the apps get the server's values).
*/
export function keepalive_max(srv) {
let o = srv?.obf ?? {};
let cpa = split(`${o.content_padding_addition ?? ''}`, '-');
let hi = +(cpa[length(cpa) - 1]);
if (o.content_padding_addition != null && o.content_padding_addition != '' && hi > 0)
return KEEPALIVE + hi;
if (o.random_trailers == 'on' || o.random_trailers == '1')
return KEEPALIVE + TRAILER_MAX;
return KEEPALIVE;
};
/** keepalive_max() for each device's server: { device id: bytes }. */
export function keepalive_sizes(m) {
let out = {};
for (let id, d in m.devices)
out[id] = keepalive_max(m.servers[m.people[d.person]?.server]);
return out;
};
/** An rx increment made of accepted initiations only. */
export function knock(drx) {
return drx > 0 && drx % INITIATION == 0 && drx <= KNOCKS_PER_TICK * INITIATION;
};
/**
* An rx increment that carried no data: nothing, or one keepalive of up to
* `ka` bytes (keepalive_max); in the second a handshake completed (`shook`)
* also the handshake messages that came with it. Outside that second a
* handshake message is never counted in: with a padded keepalive their
* sums would cover every small packet (a DNS query, an ACK) up to some
* 670 bytes, and a device with light traffic would look like one whose
* data never comes through.
*/
export function bare(drx, ka, shook) {
if (drx <= 0)
return true;
if (!shook)
return drx >= KEEPALIVE && drx <= ka;
if (drx > KNOCKS_PER_TICK * INITIATION + RESPONSE + ka)
return false;
for (let k = 0; k <= KNOCKS_PER_TICK; k++)
for (let r = 0; r <= 1; r++) {
let rest = drx - k * INITIATION - r * RESPONSE;
if (rest == 0 || (rest >= KEEPALIVE && rest <= ka))
return true;
}
return false;
};
/**
* Fold one read of the device's peer ({ endpoint, handshake, rx, tx } from
* awg.dump) at `now` into its history `h`; `ka` is its keepalive_max().
* Returns true when something worth classifying again happened (a
* handshake, a new endpoint, a knock, an answer, data after a quiet span).
* Counters that went down (the peer re-added, its tunnel set up again)
* start a new baseline.
*/
export function observe(h, peer, now, ka) {
let changed = false;
let shook = peer.handshake > h.hs;
if (shook) {
keep(h.hsev, peer.handshake);
h.hs = peer.handshake;
changed = true;
}
if (peer.endpoint != h.ep) {
if (h.ep != null && peer.endpoint != '') {
keep(h.epev, [ now, peer.endpoint, h.ep ]);
changed = true;
}
h.ep = peer.endpoint;
}
if (h.rx == null || peer.rx < h.rx || peer.tx < h.tx) {
h.rx = peer.rx;
h.tx = peer.tx;
return changed;
}
let drx = peer.rx - h.rx, dtx = peer.tx - h.tx;
h.rx = peer.rx;
h.tx = peer.tx;
if (drx > 0) {
if (!shook && knock(drx)) {
keep(h.knocks, now);
changed = true;
}
else if (!bare(drx, ka, shook)) {
if (now - h.data >= DROP_SPAN)
changed = true;
h.data = now;
}
}
else if (dtx > 0) {
keep(h.ans, [ now, dtx ]);
changed = true;
}
return changed;
};
/** The device's peer is not in its tunnel: the next read starts a new baseline. */
export function gone(h) {
h.rx = null;
h.tx = null;
};
/** Forget events older than HISTORY seconds. */
export function prune(h, now) {
let cut = now - HISTORY;
h.hsev = filter(h.hsev, (t) => t > cut);
h.knocks = filter(h.knocks, (t) => t > cut);
h.epev = filter(h.epev, (e) => e[0] > cut);
h.ans = filter(h.ans, (e) => e[0] > cut);
};
/** Endpoint changes within the span that went back to an endpoint seen before in it (A → B → A → B: 2). */
function returns(h, now) {
let seen = null, n = 0;
for (let e in h.epev)
if (now - e[0] < CHURN_SPAN) {
if (seen == null) {
seen = {};
seen[e[2]] = true;
}
if (seen[e[1]])
n++;
seen[e[1]] = true;
}
return n;
}
function churning(h, now) {
let hs = filter(h.hsev, (t) => now - t < CHURN_SPAN);
if (length(hs) < CHURN_COUNT)
return false;
let short = 0;
for (let i = 1; i < length(hs); i++)
if (hs[i] - hs[i - 1] < CHURN_GAP)
short++;
return short >= CHURN_COUNT - 1;
}
function dropped(h, now) {
if (now - h.start < DROP_SPAN || now - h.data < DROP_SPAN || !(h.hs > 0 && now - h.hs < DROP_HS))
return false;
let n = 0, bytes = 0;
for (let a in h.ans)
if (now - a[0] < DROP_SPAN) {
n++;
bytes += a[1];
}
return n >= DROP_ANSWERS && bytes < DROP_TX;
}
/**
* What the history says about the device at `now` (`on`: it is online, as
* the watcher decides it): null (nothing wrong, or nothing to tell), or
* 'trying' not online, but its initiations reach the router and are
* answered, and it never finishes connecting (the network
* may block it, or its configuration is out of date: a
* stale preshared key looks the same)
* 'shared' connecting over and over from two or more alternating
* endpoints (ip:port): one configuration on two devices
* 'unstable' connecting over and over from one place: the connection
* keeps breaking
* 'dropped' connected, but nothing it sends gets through: the router
* drops it (an old address in its configuration)
*/
export function classify(h, now, on) {
if (!on) {
let n = 0;
for (let t in h.knocks)
if (now - t < TRY_SPAN)
n++;
return n >= TRY_KNOCKS ? 'trying' : null;
}
if (churning(h, now))
return returns(h, now) >= SHARE_RETURNS ? 'shared' : 'unstable';
return dropped(h, now) ? 'dropped' : null;
};
/**
* Turn a classification into what is shown (h.state, h.since): a state, or
* a change of state, shows once classify() gave it for HOLD seconds (since
* = when it began); nothing wrong shows at once when the device is online
* (it works), else after HOLD as well. Returns the change, { from, to }
* (either may be null), or null when what is shown stays.
*/
export function settle(h, raw, now, on) {
if (raw == h.state) {
h.pend = null;
return null;
}
let since = now;
if (raw != null || !on) {
if (h.pend == null || h.pend.state != raw) {
h.pend = { state: raw, since: now };
return null;
}
if (now - h.pend.since < HOLD)
return null;
since = h.pend.since;
}
let from = h.state;
h.state = raw;
h.since = raw != null ? since : 0;
h.pend = null;
return { from, to: raw };
};
/**
* What the device's link does at `now` for the set-up sheet (pure; `on`: it
* is online, as the watcher decides it): { state, due }. state is
* 'trying' its initiations reach the router and are answered, and no
* handshake follows (SETUP_KNOCKS within SETUP_SPAN): the
* network blocks the answers, or the configuration is not this
* device's any more
* 'flowing' online, and data came in during this session (since h.sess)
* 'nodata' online for SETUP_QUIET seconds, nothing but handshakes and
* keepalives came in, and the router answered packets it
* dropped: an old address in the configuration
* null none of these (waiting, idle, or away)
* due: when the state may change with time alone (a knock ages out, the
* quiet span ends), 0 for never: anything else comes with a read.
*/
export function setup_state(h, now, on) {
let n = 0;
for (let i = length(h.knocks) - 1; i >= 0; i--) {
let t = h.knocks[i];
if (t <= h.hs || now - t >= SETUP_SPAN)
break;
if (++n == SETUP_KNOCKS)
return { state: 'trying', due: t + SETUP_SPAN };
}
if (!on || !h.sess)
return { state: null, due: 0 };
if (h.data >= h.sess)
return { state: 'flowing', due: 0 };
if (now - h.sess < SETUP_QUIET)
return { state: null, due: h.sess + SETUP_QUIET };
let a = h.ans[length(h.ans) - 1];
return { state: a != null && a[0] >= h.sess ? 'nodata' : null, due: 0 };
};
/**
* Bring h.setup to setup_state() after a read at `now` (`moved`: what
* observe() returned). Most reads cost a few compares: the state is worked
* out again only when something happened, the device came or went, data
* came in while it is not 'flowing', or its `due` time came. Returns true
* when h.setup changed ({ state, since: when it began } or null).
*/
export function setup(h, now, on, moved) {
// A session begins with the handshake that brought the device online.
if (!on)
h.sess = 0;
else if (!h.sess)
h.sess = h.hs;
let came = on != h.on;
h.on = on;
let cur = h.setup?.state;
if (!moved && !came && !(h.due && now >= h.due) && !(h.data == now && cur != 'flowing'))
return false;
let s = setup_state(h, now, on);
h.due = s.due;
if (s.state == cur)
return false;
h.setup = s.state != null ? { state: s.state, since: now } : null;
return true;
};
/** setup() of every device: { device id: { state, since } }, devices with none left out. */
export function setups(hist) {
let out = {};
for (let id, h in hist)
if (h.setup != null)
out[id] = h.setup;
return out;
};
/** What is shown for every device: { device id: { state, since } }, devices with nothing to show left out. */
export function shown(hist) {
let out = {};
for (let id, h in hist)
if (h.state != null)
out[id] = { state: h.state, since: h.since };
return out;
};
/**
* The activity event for a change settle() made, or null: device_failing
* (detail: the new state) when a state shows, device_recovered (detail:
* the state it had) when it clears while the device is online. One that
* clears while the device is away (it stopped trying, it was paused) logs
* nothing: nobody saw it work.
*/
export function event_for(change, dev, on) {
if (!change)
return null;
if (change.to != null)
return { type: 'device_failing', person: dev.person, device: dev.id, detail: change.to };
if (on && change.from != null)
return { type: 'device_recovered', person: dev.person, device: dev.id, detail: change.from };
return null;
};
@@ -7,15 +7,18 @@
import { readfile, stat, unlink } from 'fs';
import { cursor } from 'uci';
import {
ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq,
ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq, syslog,
iface_status as util_iface_status, RUN_DIR, DATA_DIR
} from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as core from 'dawnline.core';
import * as schema from 'dawnline.schema';
// Online while the WireGuard session lives: it is dropped 180 s after its
// handshake, and a device that is there renews it every 2 min (a little slack
// for a renewal that needs a retry). One that left goes offline 1-3 min later.
// The shortest window: a device whose keep-alive is longer gets more
// (online_window), or it would flap between its handshakes.
export const ONLINE_WINDOW = 190;
/** A restore put other counters on flash: the agent reloads from there (dawnline.backup writes it). */
export const USAGE_RELOAD = `${RUN_DIR}/usage.reload`;
@@ -31,6 +34,8 @@ export const CATEGORY = {
person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
// A device's link (dawnline.link): failing in a named way, and working again.
device_failing: 'problems', device_recovered: 'problems',
};
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
@@ -95,24 +100,90 @@ export const PRESENCE = `${RUN_DIR}/presence.json`;
const BEAT = `${RUN_DIR}/agent.beat`;
const BEAT_STALE = 180;
/** The agent runs (its heartbeat is fresh): what its watcher wrote counts. */
function agent_running() {
let beat = +(read_json(BEAT, 0) ?? 0);
return beat > 0 && time() - beat <= BEAT_STALE;
}
/** What the watcher sees, or null when the agent isn't running. */
export function presence() {
let beat = +(read_json(BEAT, 0) ?? 0);
if (!beat || time() - beat > BEAT_STALE)
return null;
return read_json(PRESENCE, null);
return agent_running() ? read_json(PRESENCE, null) : null;
};
/**
* Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
* handshake, rx, tx } }, presence }. See dawnline.awg.
* Written by the agent's watcher when what it shows changes (dawnline.link):
* { device id: { state: 'trying' | 'shared' | 'dropped' | 'unstable', since } },
* only devices whose link fails in one of these ways (link.classify()).
*/
export function dump(m) {
// Only Dawnline's own tunnels decide `ok`: another AmneziaWG interface on
// the router that cannot be read is not our trouble.
let mine = m ? map(filter(values(m.servers), (s) => s.private_key && s.enabled), (s) => s.ifname) : null;
let d = awg.dump(mine);
d.presence = presence();
export const LINK = `${RUN_DIR}/link.json`;
/**
* Written by the agent's watcher when it changes (dawnline.link.setup, at
* once, without LINK's hold): what each device's link does right now, for the
* set-up sheet: { device id: { state: 'trying' | 'flowing' | 'nodata', since } },
* devices with none of these left out.
*/
export const SETUP = `${RUN_DIR}/setup.json`;
/**
* The interfaces of the servers that run: enabled, with keys and an
* interface that is Dawnline's (core.tunnels: never another tunnel that
* took the name); with `sid`, only that server's. What dawnline.awg.dump()
* reads; an empty list when none.
*/
export function tunnel_ifnames(m, sid) {
let out = [];
for (let id, srv in m.servers)
if (srv.enabled && (sid == null || id == sid))
for (let t in core.tunnels(srv))
push(out, t.ifname);
return out;
};
/**
* How long after its last handshake a device still counts as online, in
* seconds: ONLINE_WINDOW, or 30 s more than an idle device with its
* keep-alive goes between handshakes (awg.idle_handshake) when that is
* longer. A device that sends nothing renews its session only with its
* keep-alive: with one of about 95-120 s, or over 160 s, the fixed window
* would see it leave and come back between two handshakes. Keep-alive off:
* ONLINE_WINDOW.
*/
export function online_window(srv, dev) {
let h = srv ? awg.idle_handshake(srv, dev) : null;
return h != null ? max(ONLINE_WINDOW, h + 30) : ONLINE_WINDOW;
};
/** online_window() of every device (with `sid`, of that server's): { device id: seconds }. */
export function online_windows(m, sid) {
let out = {};
for (let id, d in m.devices) {
let s = m.people[d.person]?.server;
if (sid == null || s == sid)
out[id] = online_window(m.servers[s], d);
}
return out;
};
/**
* Dawnline's tunnels as dawnline.awg.dump() reads them (only those, each on
* its own: { ok, reads, ifaces, peers: { public key: { ifname, endpoint,
* handshake, rx, tx } } }), plus `presence`, the agent watcher's, `windows`,
* each device's online_window() (online() without the agent), `link`, the
* watcher's LINK ({} without the agent: its states would be stale), and
* `setup`, its SETUP (null without the agent: nobody tells data from a bare
* handshake then, view.device_view goes by the handshake). With `sid` only
* that server's tunnel is read (one person's page needs no other: one `awg`
* process, not one per server).
*/
export function dump(m, sid) {
let d = awg.dump(tunnel_ifnames(m, sid));
let up = agent_running();
d.presence = up ? read_json(PRESENCE, null) : null;
d.windows = online_windows(m, sid);
d.link = up ? (read_json(LINK, null) ?? {}) : {};
d.setup = up ? (read_json(SETUP, null) ?? {}) : null;
return d;
};
@@ -121,11 +192,15 @@ export function online(dmp, id, peer) {
let p = dmp?.presence?.online;
if (p)
return !!(peer && p[id]);
return !!(peer && peer.handshake > 0 && time() - peer.handshake < ONLINE_WINDOW);
return !!(peer && peer.handshake > 0 && time() - peer.handshake < (dmp?.windows?.[id] ?? ONLINE_WINDOW));
};
// "203.0.113.7:41821", "[2001:db8::1]:41821". A module constant, compiled once:
// the agent's watcher asks for every device, every second.
const ENDPOINT = /^\[?([^\]]+)\]?:[0-9]+$/;
export function endpoint_ip(ep) {
let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
let m = match(ep ?? '', ENDPOINT);
return m ? m[1] : ep;
};
@@ -214,34 +289,36 @@ function offline(rec) {
/**
* Fold the current kernel counters into `usage`. Counters restart from zero
* when a peer is re-added or the interface restarts; a drop is treated as a
* reset. Returns the per-device live view keyed by device id.
* when a peer is re-added or its tunnel is set up again; a drop is treated
* as a reset, and so is a new link (each record keeps the interface index
* its counters were read on: new counters that already passed the old ones
* would be counted short). Returns the per-device live view keyed by device id.
*
* A device missing from the dump had its counters reset only when its tunnel
* was actually read: an interface the tool couldn't read says nothing, and
* forgetting the last counters there would count them again on the next good
* read. A failed read with nothing in it changes nothing at all.
* was read or is down (dawnline.awg.dump's `reads`): one the tool couldn't
* read says nothing, and forgetting the last counters there would count them
* again on the next good read.
*/
export function collect(m, usage, d) {
d ??= dump(m);
let ts = time();
let live = {};
if (d.ok === false && !length(d.peers)) {
for (let id in keys(m.devices))
live[id] = offline(usage.devices[id]);
return live;
}
for (let id, dev in m.devices) {
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
let peer = d.peers[dev.public_key];
if (!peer) {
let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
if (d.ok !== false || d.ifaces[ifname] != null)
if (d.reads[ifname] != 'error')
rec.raw = [ 0, 0 ];
live[id] = offline(rec);
continue;
}
let raw = rec.raw ?? [ 0, 0 ];
let link = d.ifaces[peer.ifname]?.ifindex;
if (link != null && rec.ifindex != null && link != rec.ifindex)
raw = [ 0, 0 ];
if (link != null)
rec.ifindex = link;
let drx = peer.rx >= raw[0] ? peer.rx - raw[0] : peer.rx;
let dtx = peer.tx >= raw[1] ? peer.tx - raw[1] : peer.tx;
rec.raw = [ peer.rx, peer.tx ];
@@ -262,7 +339,7 @@ export function collect(m, usage, d) {
delete rec.ips[ips[i]];
}
live[id] = {
online: peer.handshake > 0 && ts - peer.handshake < ONLINE_WINDOW,
online: peer.handshake > 0 && ts - peer.handshake < online_window(m.servers[m.people[dev.person]?.server], dev),
handshake: peer.handshake || rec.handshake || 0,
endpoint: endpoint_ip(peer.endpoint) || rec.endpoint || '',
present: true,
@@ -345,13 +422,51 @@ function with_names(e, c) {
return e;
}
// Events about someone's connection, not about the system: they stay out of syslog
// (the activity log has them). Connects, roams, a device's link trouble and its end.
const NOT_SYSTEM = [ 'connect', 'disconnect', 'roam', 'device_failing', 'device_recovered' ];
/**
* An activity event at its syslog level, or null when it stays out (a
* connection: syslog says what the system does). People and their devices
* (what changes the tunnels and the rules) are info, problems warn and their
* end ("…_up") info.
*/
export function event_level(e) {
let cat = category_of(e.type);
if (cat == 'connections' || index(NOT_SYSTEM, e.type) >= 0)
return null;
if (cat == 'problems' && !match(e.type, /_up$/))
return 'warn';
return 'info';
};
/** An activity event as a syslog line: "Myata · Phone device changed · kind=phone, lan_bypass=on (portal)". */
export function event_line(e) {
let who = join(' · ', filter([ e.pname ?? e.person, e.dname ?? e.device ], (x) => x != null && x != ''));
return join(' ', filter([ who, replace(e.type ?? 'event', /_/g, ' '), e.detail ? `· ${e.detail}` : '', e.by ? `(${e.by})` : '' ], (x) => x != ''));
};
/** The system's events to syslog, whatever the activity log records (its categories are the admin's choice for the page). */
function syslog_events(list, c) {
for (let e in list) {
let lvl = event_level(e);
if (lvl)
syslog(lvl, category_of(e.type), event_line(with_names(e, c)));
}
}
export function add_events(list, pol) {
pol ??= policy();
list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0);
list ??= [];
if (!length(list))
return;
let c = cursor();
c.load('dawnline');
syslog_events(list, c);
list = filter(list, (e) => index(pol.categories, category_of(e.type)) >= 0);
if (!length(list))
return;
let l = lock('events');
let ev = load_events();
let ts = time();
@@ -369,8 +484,14 @@ export function add_event(e) {
add_events([ e ]);
};
/** Like add_event, but folds into the previous event of the same kind and person within `window` s. */
/**
* Like add_event, but folds into the previous event of the same kind, person
* and device (when it has one) within `window` s.
*/
export function add_event_merged(e, window) {
let c0 = cursor();
c0.load('dawnline');
syslog_events([ { ...e } ], c0);
let pol = policy();
if (index(pol.categories, category_of(e.type)) < 0)
return;
@@ -378,7 +499,7 @@ export function add_event_merged(e, window) {
let ev = load_events();
let last = ev[length(ev) - 1];
let ts = time();
if (last && last.type == e.type && last.person == e.person && ts - last.ts < (window ?? 120)) {
if (last && last.type == e.type && last.person == e.person && last.device == e.device && ts - last.ts < (window ?? 120)) {
let parts = uniq([ ...split(last.detail ?? '', ', '), ...split(e.detail ?? '', ', ') ]);
last.detail = join(', ', filter(parts, (x) => x != ''));
last.ts = ts;
@@ -84,6 +84,18 @@ export function resolve(host) {
return resolve_all([ host ])[host] ?? [];
};
/**
* The address to give an app that takes no name for the server (V2RayTun's
* Android core hands the endpoint over as it is): IPv4 first, as a phone on
* mobile data may have no IPv6. The host itself when it is an IP; null when
* the name does not resolve.
*/
export function host_ip(host) {
let ips = resolve(host);
let v4 = filter(ips, (x) => ip2int(x) != null);
return v4[0] ?? ips[0] ?? null;
};
/** The IPv4 address of a netifd interface (a zone name for older configs). */
export function wan_ipv4(zone) {
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
@@ -7,13 +7,24 @@
// └── NAT to a LAN address ┘
//
// The netns is one more device on the LAN bridge with its own address (picked
// from the LAN subnet above the DHCP pool). Replies come back the same way.
// from the LAN subnet above the DHCP pool) and its own MAC (hashed from the
// bridge's), the same each time it is created: the router's neighbour table
// knows the address by that MAC, so a netns created again keeps its address
// instead of seeing it held by another device. Replies come back the same way.
// Home-network destinations keep their direct route; per-person access is
// still enforced on dawn0 before any of this (table inet dawnline).
//
// Clients also use the netns address as DNS: it forwards to the DNS the LAN
// gets from DHCP, from the LAN side, so DNS interception applies as well.
//
// The netns forwards and NATs every packet a second time (conntrack, the
// forward hook): about 40% more CPU per packet on an MT7981. A flowtable on
// its two links (dlx1, dll1) lets established TCP and UDP flows skip that
// work. The netns holds no access rules: who may reach what is judged on the
// tunnel interfaces in the root namespace, which no flowtable here touches.
// Without kernel flowtables (kmod-nft-offload) the loop runs as before,
// slower, and logs it once.
//
// Separately, people with Home-only access get a plain resolver
// (dawnline.resolver). While the netns exists it runs inside it and sends its
// upstream queries back out through the transit link as forwarded traffic —
@@ -28,7 +39,7 @@
import { readfile, writefile, readlink, stat, unlink } from 'fs';
import { cursor } from 'uci';
import {
sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR
sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, syslog, syslog_lines, RUN_DIR
} from 'dawnline.util';
import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
@@ -41,6 +52,7 @@ const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.la
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
export const RESOLVER_CONF = resolver.CONF;
const STATE = `${RUN_DIR}/loop.json`;
const NS_RULES = '/var/etc/dawnline-ns.nft';
const WHO = L_('Internet like a home device');
@@ -48,12 +60,20 @@ function log(msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, WHO);
}
/**
* Run the commands that set the path up or take it down, each in syslog as
* it is given ("$ ip netns add dawnline"), a failure with what it said.
* Only called when something changes (ensure() returns early otherwise).
*/
function run(cmds) {
let errs = [];
syslog_lines('info', 'loop', join('\n', cmds), '$ ');
for (let c in cmds) {
let r = sh(c);
if (r.code != 0)
if (r.code != 0) {
push(errs, `${c}: ${trim(r.out)}`);
syslog('error', 'loop', `failed: ${c} · ${trim(r.out)}`);
}
}
return errs;
}
@@ -106,38 +126,63 @@ function used_addresses(dev) {
return used;
}
/** The MAC the netns's LAN link has now; null without the link. */
function our_mac() {
return sh_out(`ip -n ${NS} -j link show ${LAN_NS} 2>/dev/null | jsonfilter -e '@[0].address'`);
}
/** 32-bit FNV-1a of a string, continuing from `h`. */
function fnv1a(s, h) {
for (let i = 0; i < length(s); i++)
h = ((h ^ ord(s, i)) * 16777619) & 0xffffffff;
return h;
}
/**
* A LAN address for the netns: keep the saved one while it is valid and not
* taken by someone else, otherwise the highest free host above the DHCP pool
* (then below it), skipping static leases and anything that answers.
* The MAC for the netns's LAN link, from the bridge's MAC: a locally
* administered unicast address hashed from it, so it is the same every time
* and differs between routers. Not the bridge's MAC with a bit flipped: radios
* and ports often get those.
*/
function pick_address(lan, facts, saved, dev) {
let used = used_addresses(dev);
let mine = our_mac();
let taken = (ip) => {
let s = int2ip(ip);
if (ip == lan.ip || index(facts.statics, ip) >= 0)
return true;
export function lan_mac(bridge) {
let s = lc(trim(bridge ?? ''));
let h1 = fnv1a(`dawnline lan ${s}`, 0x811c9dc5), h2 = fnv1a(s, h1);
let b = [ ((h1 >> 24) & 0xfc) | 0x02, (h1 >> 16) & 0xff, (h1 >> 8) & 0xff, h1 & 0xff, (h2 >> 24) & 0xff, (h2 >> 16) & 0xff ];
return join(':', map(b, (x) => sprintf('%02x', x)));
};
/**
* True when the netns may use a LAN address (a number): a host of the
* network, not the router's, not a static lease, outside the DHCP pool and
* not held by another device in `used` (address → MAC, or true without one).
* An entry with one of the MACs in `mine` is the netns itself, also from
* before it was created again.
*/
export function address_free(ip, lan, facts, used, mine) {
if (ip <= lan.net || ip >= lan.net + lan.size - 1 || ip == lan.ip || index(facts.statics, ip) >= 0)
return false;
if (facts.pool && ip >= facts.pool[0] && ip <= facts.pool[1])
return true;
let u = used[s];
return u != null && !(mine && u == mine);
};
return false;
let u = used[int2ip(ip)];
return u == null || index(mine, u) >= 0;
};
/**
* A LAN address for the netns: keep the saved one while it is free (see
* address_free; `mine` are the netns's MACs), otherwise the highest free host
* above the DHCP pool (then below it) that does not answer.
*/
function pick_address(lan, facts, saved, dev, mine) {
let used = used_addresses(dev);
let sv = ip2int(saved ?? '');
if (sv != null && sv > lan.net && sv < lan.net + lan.size - 1 && !taken(sv))
if (sv != null && address_free(sv, lan, facts, used, mine))
return int2ip(sv);
for (let ip = lan.net + lan.size - 2; ip > lan.net; ip--) {
if (taken(ip))
if (!address_free(ip, lan, facts, used, mine))
continue;
// Last check: nobody answers on it.
sh(`ping -c 1 -W 1 -I ${q(dev)} ${int2ip(ip)}`);
let again = used_addresses(dev)[int2ip(ip)];
if (again != null && !(mine && again == mine))
continue;
if (address_free(ip, lan, facts, used_addresses(dev), mine))
return int2ip(ip);
}
return null;
@@ -195,8 +240,8 @@ function pick_table(saved) {
* { code: 'setup', detail } a command failed (detail: it and what it said)
*/
/** A reason from plan() for the service log: English, like every log line. */
function error_note(e) {
/** A reason from plan() for the service log and syslog: English, like every log line. */
export function error_note(e) {
if (e.code == 'no_lan')
return L_('No LAN detected.');
if (e.code == 'not_bridge')
@@ -208,7 +253,7 @@ function error_note(e) {
if (e.code == 'no_transit')
return L_('No free link-local range for the internal link.');
return L_('No free routing table.');
}
};
/**
* Why "like a home device" is off (a reason above), as a sentence in the
@@ -271,7 +316,9 @@ export function plan(m) {
return { error: { code: 'no_ipv4', dev } };
let facts = dhcp_facts(d.logical, lan);
let st = settings();
let addr = pick_address(lan, facts, st.lan_address, dev);
let mac = lan_mac(readfile(`/sys/class/net/${dev}/address`));
// The netns's MACs: the one it gets, and the one it has (a random one from an older version).
let addr = pick_address(lan, facts, st.lan_address, dev, [ mac, our_mac() ]);
if (!addr)
return { error: { code: 'no_address', net: `${int2ip(lan.net)}/${lan.prefix}` } };
let last = read_json(STATE, {});
@@ -291,6 +338,7 @@ export function plan(m) {
dev,
gateway: int2ip(lan.ip),
address: addr,
mac,
prefix: lan.prefix,
dns: facts.dns ?? int2ip(lan.ip),
transit: tx,
@@ -303,10 +351,20 @@ export function plan(m) {
/* ---------- apply ---------- */
function ns_rules(p) {
/**
* The netns's nft script as text (nothing is loaded). With `fast`, a
* flowtable on the netns's own two links takes established TCP and UDP flows
* past conntrack and the forward hook here. Only dlx1 and dll1: the root
* namespace's links (dawn0, dlx0) stay out, the guard there sees every packet.
*/
export function ns_rules(p, fast) {
return `table inet dawnline
delete table inet dawnline
table inet dawnline {
table inet dawnline {${fast ? `
flowtable ft {
hook ingress priority 0;
devices = { "${TX_NS}", "${LAN_NS}" };
}` : ''}
chain nat_pre {
type nat hook prerouting priority dstnat; policy accept;
iifname "${TX_NS}" ip daddr ${p.address} meta l4proto { tcp, udp } th dport 53 dnat ip to ${p.dns}:53
@@ -316,7 +374,8 @@ table inet dawnline {
oifname "${LAN_NS}" masquerade
}
chain filter_forward {
type filter hook forward priority filter; policy drop;
type filter hook forward priority filter; policy drop;${fast ? `
ct state established meta l4proto { tcp, udp } flow add @ft` : ''}
ct state established,related accept
iifname "${TX_NS}" oifname "${LAN_NS}" accept
}
@@ -329,8 +388,40 @@ table inet dawnline {
}
}
`;
};
/**
* Load the netns's rules, with the flowtable when the kernel takes it, else
* without (the loop works either way). { fast, slow, err }: slow is why the
* flowtable failed, err why the rules without it failed too.
*/
function load_ns_rules(p) {
ensure_dir('/var/etc');
let load = (fast) => {
writefile(NS_RULES, ns_rules(p, fast));
return run([ `ip netns exec ${NS} nft -f ${NS_RULES}` ])[0];
};
let slow = load(true);
return slow ? { fast: false, slow, err: load(false) } : { fast: true };
}
/**
* The policy rules plan `p` wants (pure), in order: [{ pref, iif, to, table }]
* (to null: all). Per server interface: DNS to the netns address through the
* netns, home networks and the tunnel network by main, the rest into the netns.
*/
export function rules(p) {
let out = [];
let rule = (pref, iif, to, table) => push(out, { pref, iif, to, table });
for (let s in p?.servers ?? []) {
rule(PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}`);
for (let n in s.direct)
rule(PREF_MAIN, s.ifname, n, 'main');
rule(PREF_LOOP, s.ifname, null, `${p.table}`);
}
return out;
};
/** Our policy rules: in our priority band and bound to a Dawnline tunnel interface. */
function current_rules(ifnames) {
let out = [];
@@ -345,31 +436,58 @@ function current_rules(ifnames) {
}
function rule_key(pref, iif, to, table) {
// `ip -j rule` shows a /32 destination without its length.
if (to && index(to, '/') < 0)
to += '/32';
return `${pref} ${iif} ${to ?? 'all'} ${table}`;
// A rule of ours with a source (none of rules() has one) is told apart, so it is removed.
function rule_key(pref, from, iif, to, table) {
// `ip -j rule` shows a /32 source or destination without its length.
let full = (n) => n && index(n, '/') < 0 ? `${n}/32` : n;
return `${pref} ${full(from) ?? 'all'} ${iif} ${full(to) ?? 'all'} ${table}`;
}
function sync_rules(p, ifnames) {
let want = [];
for (let s in p?.servers ?? []) {
push(want, [ PREF_LOOP_DNS, s.ifname, `${p.address}/32`, `${p.table}` ]);
for (let n in s.direct)
push(want, [ PREF_MAIN, s.ifname, n, 'main' ]);
push(want, [ PREF_LOOP, s.ifname, null, `${p.table}` ]);
/**
* A source or destination as `ip -j rule` has it ("10.9.0.2", or with its
* length), or null for all: a rule without a source shows `"src": "all"`
* (iproute2 prints "from all"), one without a destination no `dst`.
*/
function rule_net(addr, len) {
return addr && addr != 'all' ? `${addr}${len != null ? '/' + len : ''}` : null;
}
/** The command that removes one of current_rules(). */
function rule_del(r) {
let from = rule_net(r.src, r.srclen), to = rule_net(r.dst, r.dstlen);
return `ip -4 rule del priority ${r.priority}${from ? ' from ' + from : ''} iif ${q(r.iif)}${to ? ' to ' + to : ''} lookup ${r.table}`;
}
/**
* The commands that turn rules `current` (ours, as `ip -j -4 rule show`
* prints them) into rules(p) (pure): the missing ones added first, then the
* ones no longer wanted removed, so a device's traffic never falls between
* two rules while others change. [] when they are as wanted.
*/
export function rule_cmds(p, current) {
let have = {}, want = {}, cmds = [], twice = [];
for (let r in current) {
let k = rule_key(r.priority, rule_net(r.src, r.srclen), r.iif, rule_net(r.dst, r.dstlen), r.table);
if (have[k])
push(twice, rule_del(r));
have[k] = r;
}
let have = map(current_rules(ifnames), (r) => rule_key(r.priority, r.iif, r.dst ? `${r.dst}${r.dstlen != null ? '/' + r.dstlen : ''}` : null, r.table));
let wantk = map(want, (w) => rule_key(w[0], w[1], w[2] ?? null, w[3]));
if (join('\n', sort(have)) == join('\n', sort(wantk)))
return [];
let cmds = [];
for (let r in current_rules(ifnames))
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
for (let w in want)
push(cmds, `ip -4 rule add priority ${w[0]} iif ${q(w[1])}${w[2] ? ' to ' + w[2] : ''} lookup ${w[3]}`);
for (let w in rules(p)) {
let k = rule_key(w.pref, null, w.iif, w.to, w.table);
if (!have[k] && !want[k])
push(cmds, `ip -4 rule add priority ${w.pref} iif ${q(w.iif)}${w.to ? ' to ' + w.to : ''} lookup ${w.table}`);
want[k] = true;
}
for (let k, r in have)
if (!want[k])
push(cmds, rule_del(r));
// The same rule twice (one deletion removes one of them).
push(cmds, ...twice);
return cmds;
};
function sync_rules(p, ifnames) {
return rule_cmds(p, current_rules(ifnames));
}
function tunnel_ifnames() {
@@ -382,21 +500,25 @@ function tunnel_ifnames() {
return out;
}
/** Remove the netns, links and rules. */
/** Remove the netns, links and rules, and the router's neighbour entry for the netns. */
export function remove(ifnames) {
ifnames ??= tunnel_ifnames();
let cmds = [];
for (let r in current_rules(ifnames))
push(cmds, `ip -4 rule del priority ${r.priority} iif ${q(r.iif)}${r.dst ? ' to ' + r.dst + (r.dstlen != null ? '/' + r.dstlen : '') : ''} lookup ${r.table}`);
let t = read_json(STATE, {})?.plan?.table;
if (t)
push(cmds, `ip -4 route flush table ${t}`);
let last = read_json(STATE, {})?.plan;
// Read while the link is there: the entry is ours when it carries the netns's MAC.
let held = last?.dev ? used_addresses(last.dev)[last.address] : null;
let stale = type(held) == 'string' && index([ last.mac, our_mac() ], held) >= 0;
let cmds = map(current_rules(ifnames), rule_del);
if (last?.table)
push(cmds, `ip -4 route flush table ${last.table}`);
if (exists(TX_ROOT))
push(cmds, `ip link del ${TX_ROOT}`);
if (exists(LAN_ROOT))
push(cmds, `ip link del ${LAN_ROOT}`);
if (stat(`/var/run/netns/${NS}`))
push(cmds, `ip netns del ${NS}`);
// Left there, it would hold the address for a MAC nobody has.
if (stale)
push(cmds, `ip -4 neigh del ${q(last.address)} dev ${q(last.dev)}`);
run(cmds);
unlink(STATE);
};
@@ -427,13 +549,18 @@ export function ensure(m, force) {
if (same && healthy && !length(rules))
return p;
// A link made by an older version has a random MAC (its plan had none, so
// this runs once after an update): it gets the stable one.
let remac = exists(LAN_ROOT) && our_mac() != p.mac;
let cmds = [];
if (!stat(`/var/run/netns/${NS}`))
push(cmds, `ip netns add ${NS}`);
if (!exists(TX_ROOT))
push(cmds, `ip link add ${TX_ROOT} type veth peer name ${TX_NS} netns ${NS}`);
if (!exists(LAN_ROOT))
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} netns ${NS}`);
push(cmds, `ip link add ${LAN_ROOT} type veth peer name ${LAN_NS} address ${p.mac} netns ${NS}`);
if (remac)
push(cmds, `ip -n ${NS} link set ${LAN_NS} down`, `ip -n ${NS} link set ${LAN_NS} address ${p.mac}`);
let errs = run(cmds);
cmds = [
`ip addr flush dev ${TX_ROOT}`,
@@ -457,10 +584,13 @@ export function ensure(m, force) {
];
for (let s in p.servers)
push(cmds, `ip -n ${NS} route replace ${q(s.subnet)} via ${q(p.tx_root)} dev ${TX_NS}`);
ensure_dir('/var/etc');
writefile('/var/etc/dawnline-ns.nft', ns_rules(p));
push(cmds, `ip netns exec ${NS} nft -f /var/etc/dawnline-ns.nft`);
// The router knows the address by the old MAC: ask again now, not when the entry expires.
if (remac)
push(cmds, `ip -4 neigh flush to ${p.address} dev ${q(p.dev)}`);
push(errs, ...run(cmds));
let ft = load_ns_rules(p);
if (ft.err)
push(errs, ft.err);
push(errs, ...run(sync_rules(p, ifnames)));
if (length(errs)) {
@@ -472,11 +602,17 @@ export function ensure(m, force) {
return { error: why };
}
ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
write_json(STATE, { applied: time(), plan: p, transit: p.transit, fast: ft.fast }, 0o644);
if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
log(sprintf(L_('is on · traffic enters %s as %s'), p.dev, p.address), 'up');
else if (!healthy)
log(sprintf(L_('was broken - set up again (%s as %s)'), p.dev, p.address), 'repair');
// Once, not again on every apply while the module is still missing.
if (!ft.fast && last.fast !== false)
log(L_('runs without its fast path'), 'info', join('\n', [
L_('Without kmod-nft-offload every packet on this path passes the firewall twice. Install it and restart Dawnline.'),
ft.slow,
]));
return p;
};
@@ -0,0 +1,155 @@
// Dawnline — the live meter (Speed now on the Overview, the People list and a
// person's page): each server's throughput and that of each device moving
// traffic, one point a second over the last two minutes.
//
// The meter RPC (dawnline.rpc.status) calls want() and read(); the agent's
// watcher makes a point from every read it already does (sample(), point())
// and keeps the last two minutes in memory (keep()) whether anyone looks or
// not, so a look gets them all at once. It writes them to FILE (save()) only
// while WANT is younger than WANT_FOR seconds: the first second of a look,
// then with each new point. When WANT goes stale it removes FILE: with nobody
// looking the watcher pays a little arithmetic and one stat() a second, and
// writes nothing. FILE holds server and device ids and byte rates only, no
// keys, names or personal codes. Who is online and the per-minute rates are not here
// (dawnline.live, the agent's tick).
//
// Bytes are the peers' counters (dawnline.awg.dump): tx includes the
// disguise (S prefixes, padding, junk), rx the packets as they were
// received without their prefix, so both are close to what is on the wire.
import { writefile, stat, unlink } from 'fs';
import { read_json, write_file, ensure_dir, RUN_DIR } from 'dawnline.util';
/** Touched by every meter RPC: the watcher samples while it is fresh. */
export const WANT = `${RUN_DIR}/meter.want`;
/** The points, written by the watcher each second while WANT is fresh. */
export const FILE = `${RUN_DIR}/meter.json`;
/** Seconds after the last meter RPC the watcher keeps sampling. */
export const WANT_FOR = 10;
/** Points kept: two minutes, one a second. */
export const POINTS = 120;
/** Ask the watcher to sample for the next WANT_FOR seconds (the meter RPC). */
export function want() {
ensure_dir(RUN_DIR);
writefile(WANT, `${time()}`);
};
/** Someone asked for the meter within WANT_FOR seconds of `now`. */
export function wanted(now) {
let st = stat(WANT);
return st != null && now - st.mtime < WANT_FOR && st.mtime - now < WANT_FOR;
};
/**
* What the watcher wrote, for the RPC: { now, want: WANT_FOR, keep: POINTS,
* ts (newest point, 0 for none), points } with only the points newer than
* `since` when it is given (a page that polls asks for what it lacks).
* No points when nobody asked within WANT_FOR seconds or the agent is not
* running: FILE is gone (the agent removes it as it stops and starts), or,
* from one that died while someone looked, its newest point is over
* WANT_FOR seconds old (ts then stops moving).
*/
export function read(since) {
let f = read_json(FILE, null);
let ts = +(f?.ts ?? 0);
let pts = type(f?.points) == 'array' && time() - ts <= WANT_FOR ? f.points : [];
if (since > 0)
pts = filter(pts, (p) => p.ts > since);
return { now: time(), want: WANT_FOR, keep: POINTS, ts: ts, points: pts };
};
/** Monotonic seconds, with the fraction: the gap between two samples. */
function mono() {
let c = clock(true);
return c[0] + c[1] / 1e9;
}
/**
* One sample at `now` from the dump the watcher just read (`d`): { t, ts,
* servers: [ server id ] (those whose tunnel was read), dev: { device id:
* [ rx, tx, server id ] } (its peer's counters, on those servers) }. Nothing
* but the dump is read.
*/
export function sample(m, d, now) {
let s = { t: mono(), ts: now, servers: [], dev: {} };
let read = {};
for (let sid, srv in m.servers)
if (d.reads[srv.ifname] == 'read') {
read[sid] = true;
push(s.servers, sid);
}
for (let id, dev in m.devices) {
let peer = d.peers[dev.public_key];
let sid = m.people[dev.person]?.server;
if (peer && read[sid])
s.dev[id] = [ peer.rx, peer.tx, sid ];
}
return s;
};
/** A counter's change, 0 when it went down (a tunnel set up again starts from zero). */
function delta(a, b) {
return (b ?? 0) >= (a ?? 0) ? (b ?? 0) - (a ?? 0) : 0;
}
/**
* The point between samples `a` and `b`, null when they are not a second or
* so apart (the first sample, a stalled watcher): { ts, servers: { server
* id: [ rx, tx ] }, dev: { device id: [ rx, tx ] } }, bytes per second of
* each server's devices together (rx what came from them, tx what went to
* them, as a server's per-minute `rate`), for every server whose tunnel `b`
* read ([ 0, 0 ] when nothing moved), and of each device that moved
* something (one left out moved nothing, while its server was read). A
* device is counted from its second sample on, on the server it was on in both.
*/
export function point(a, b) {
let dt = b.t - a.t;
if (!(dt > 0.2 && dt < 5))
return null;
let sum = {}, dev = {};
for (let sid in b.servers)
sum[sid] = [ 0, 0 ];
for (let id, v in b.dev) {
let o = a.dev[id];
if (!o || o[2] != v[2])
continue;
let rx = delta(o[0], v[0]), tx = delta(o[1], v[1]);
sum[v[2]][0] += rx;
sum[v[2]][1] += tx;
if (rx || tx)
dev[id] = [ int(rx / dt), int(tx / dt) ];
}
let p = { ts: b.ts, servers: {}, dev };
for (let sid, v in sum)
p.servers[sid] = [ int(v[0] / dt), int(v[1] / dt) ];
return p;
};
/**
* Keep point `p` in `ring` ([ [ ts, the point as JSON ] ], newest last; each
* point is turned into text once, when it is made, not again every second for
* as long as it is kept): at most POINTS of them, none older than POINTS
* seconds before `p` (the watcher may have stalled in between) and none from
* its second or later (the clock went back).
*/
export function keep(ring, p) {
while (length(ring) && ring[length(ring) - 1][0] >= p.ts)
pop(ring);
push(ring, [ p.ts, sprintf('%J', p) ]);
while (length(ring) > POINTS || ring[0][0] <= p.ts - POINTS)
shift(ring);
};
/** Write the points kept in `ring` (keep()) to FILE. */
export function save(ring) {
let ts = length(ring) ? ring[length(ring) - 1][0] : 0;
ensure_dir(RUN_DIR);
write_file(FILE, `{"ts":${ts},"points":[${join(',', map(ring, (r) => r[1]))}]}`, 0o644);
};
/** Nobody looks any more: FILE goes (the next look gets the points kept then). */
export function stop() {
if (stat(FILE))
unlink(FILE);
};
@@ -5,7 +5,7 @@
import { cursor } from 'uci';
import { stat, unlink } from 'fs';
import { q, slog } from 'dawnline.util';
import { slog, syslog } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
import { L_ } from 'dawnline.i18n';
@@ -47,7 +47,7 @@ export function uhttpd() {
c.delete('uhttpd', 'main', 'error_page');
c.commit('uhttpd');
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
system(`logger -t dawnline ${q('portal removed from the LuCI web server')}`);
syslog('info', 'portal', 'portal removed from the LuCI web server');
}
if (stat(LAN_CGI))
unlink(LAN_CGI);
@@ -163,7 +163,7 @@ export function snapshot(fresh) {
let flags = hex(sysread(dev, 'flags') || '0');
let kind = +(sysread(dev, 'type') || '0');
let master = readlink(`${SYS}/${dev}/master`);
master = master ? replace(master, /^.*\//, '') : null;
master = master ? substr(master, rindex(master, '/') + 1) : null;
let bridge = stat(`${SYS}/${dev}/bridge`) != null;
let wifi = stat(`${SYS}/${dev}/phy80211`) != null || stat(`${SYS}/${dev}/wireless`) != null;
let nets = routes[dev] ? collapse(routes[dev]) : [];
@@ -295,10 +295,13 @@ export function lan_names() {
return out;
};
// A module constant, compiled once: event_hosts runs for every event of the log.
const ANY_IPV4 = /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g;
/** Event addresses that belong to devices at home, with their names ({ ip: name }). */
export function event_hosts(e, names) {
let out = null;
for (let ip in match(e.detail ?? '', /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/g) ?? [])
for (let ip in match(e.detail ?? '', ANY_IPV4) ?? [])
if (names[ip[0]])
(out ??= {})[ip[0]] = names[ip[0]];
return out;
@@ -4,10 +4,11 @@
// tunnel of your own, one from an imported config) is left alone and the
// server is reported instead. Why a server is kept down is kept in
// core.BLOCKED as a code with its values (awg.blocked_text says it).
// drift() tells the watchdog when one of them was edited outside Dawnline.
import { cursor } from 'uci';
import { stat, unlink, writefile } from 'fs';
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util';
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, syslog, opts_text, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import { L_ } from 'dawnline.i18n';
@@ -30,6 +31,14 @@ export function owner(ifname, c) {
return c.get('network', ifname, '_dawnline') ?? '';
};
/** What sync() writes into network.<ifname> apart from the markers: what netifd sets the tunnel up from. */
function options(srv) {
let o = awg.netifd_options(srv);
o.disabled = srv.enabled ? null : '1';
o.auto = srv.enabled ? null : '0';
return o;
}
/** Bring network config in line with the servers; true when it changed. */
export function sync(m) {
let c = cursor();
@@ -70,13 +79,15 @@ export function sync(m) {
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue;
}
// Disguise values AmneziaWG refuses or crashes on (a hand edit in uci;
// import and restore refuse them) never reach setconf and the kernel.
// A disguise this build cannot run (a 3.1 preset after a rollback to
// 2.0): the kernel would drop those options silently and run a tunnel
// no device can reach. Down, and said so, until the build or the
// disguise is changed.
let why = tools ? awg.obf_unsupported(srv.obf) : null;
let why = !tools ? null : length(awg.obf_unsafe(srv.obf)) ? { code: 'disguise_invalid' } : awg.obf_unsupported(srv.obf);
if (why) {
block(srv, why, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
block(srv, why, awg.blocked_fix(why));
continue;
}
delete srv.blocked;
@@ -84,18 +95,24 @@ export function sync(m) {
if (!tools)
continue;
// Per server: with several, each changed one has to be brought up again.
let mine = uci_section(c, 'network', ifn, 'interface');
let set = (opt, val) => {
if (uci_put(c, 'network', ifn, opt, val))
let created = uci_section(c, 'network', ifn, 'interface');
let mine = created, diff = {};
for (let k, v in options(srv))
if (uci_put(c, 'network', ifn, k, v)) {
mine = true;
};
for (let k, v in awg.netifd_options(srv))
set(k, v);
set('disabled', srv.enabled ? null : '1');
set('auto', srv.enabled ? null : '0');
set('_dawnline', id);
diff[k] = v;
}
if (mine)
syslog('info', 'network', `interface ${ifn} (${srv.name}): ${created ? 'created' : 'updated'} · ${opts_text(diff)}`);
else
syslog('debug', 'network', `interface ${ifn} (${srv.name}): unchanged · ${opts_text(options(srv))}`);
// The markers are saved, but netifd does not read them: a renamed server
// keeps its tunnel and every session in it.
if (uci_put(c, 'network', ifn, '_dawnline', id))
changed = true;
// For the log once the server is gone.
set('_dawnline_name', srv.name);
if (uci_put(c, 'network', ifn, '_dawnline_name', srv.name))
changed = true;
if (mine) {
changed = true;
push(touched, ifn);
@@ -117,6 +134,7 @@ export function sync(m) {
});
for (let ifn in stale) {
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
syslog('info', 'network', `interface ${ifn} (${c.get('network', ifn, '_dawnline_name') ?? 'a removed server'}): removed, ifdown ${ifn}`);
system(`ifdown ${q(ifn)} 2>/dev/null`);
c.delete('network', ifn);
changed = true;
@@ -125,12 +143,43 @@ export function sync(m) {
if (changed) {
c.commit('network');
ack_config([ 'network' ]);
}
// Only the markers changed: nothing for netifd to read (it ignores them, and so does a reload).
if (length(touched) || length(stale)) {
syslog('info', 'network', 'ubus call network reload');
system('ubus call network reload');
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled) {
syslog('info', 'network', `ifup ${ifn}`);
system(`ifup ${q(ifn)}`);
}
// Each tunnel's own line (restarting, turned off, removed) comes from hotplug.
system(`logger -t dawnline ${q('network updated: ' + join(', ', [ ...touched, ...stale ]))}`);
}
return changed;
};
/**
* For the watchdog: what of each running server's interface differs from
* what sync() writes, by option name (a LuCI or uci edit of network.<ifname>,
* which would otherwise last until the next apply): { server id: [ names ] },
* an empty list when it is as Dawnline set it. Only enabled servers whose
* section exists and is theirs (a missing one is the tunnel probe's); the
* markers are not compared, netifd does not read them. A dry run on a
* cursor of its own: nothing is saved. Meaningful while amneziawg-tools is
* installed (sync() leaves the interfaces alone without it).
*/
export function drift(m) {
let c = cursor();
c.load('network');
let out = {};
for (let id, srv in m.servers) {
if (!srv.enabled || !length(core.tunnels(srv)) || owner(srv.ifname, c) != id || c.get('network', srv.ifname) != 'interface')
continue;
let diff = [];
for (let k, v in options(srv))
if (uci_put(c, 'network', srv.ifname, k, v))
push(diff, k);
out[id] = diff;
}
return out;
};
@@ -5,21 +5,74 @@
// changes often (update, one atomic transaction).
import { unlink } from 'fs';
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, RUN_DIR } from 'dawnline.util';
import { sh, ensure_dir, write_file, rand_hex, ip2int, uniq, read_json, write_json, syslog, syslog_lines, some_of, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
/** Private IPv4 ranges: internet people never reach them (awg.BYPASS4 is the rest). */
export const PRIVATE4 = [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16', '224.0.0.0/3' ];
/** The sets whose members change at run time (update replaces them together). */
const SETS = [ 'lan_ok', 'lan_all', 'lan_part', 'mesh_pairs', 'inet_ok', 'svc_ok', 'svc_host', 'dns_real' ];
// The sets' members as last loaded, so a log line can say what changed.
const SETS_SEEN = `${RUN_DIR}/nft-sets.json`;
/** What a table script holds: its chains, its sets and the rules in its chains (for a log line). */
export function shape(t) {
let n = { chains: 0, sets: 0, rules: 0 }, in_chain = false;
for (let l in split(t ?? '', '\n')) {
l = trim(l);
if (substr(l, 0, 6) == 'chain ') {
n.chains++;
in_chain = true;
}
else if (substr(l, 0, 4) == 'set ')
n.sets++;
else if (in_chain && l == '}')
in_chain = false;
else if (in_chain && l != '' && substr(l, 0, 5) != 'type ' && substr(l, 0, 7) != 'policy ' && substr(l, 0, 1) != '#')
n.rules++;
}
return n;
};
/**
* The sets in syslog: info with each set that changed ("inet_ok 3 → 4: +10.8.0.5"),
* debug when none did; remembered for the next time.
*/
function log_sets(sets, how) {
let first = read_json(SETS_SEEN, null) == null;
let was = read_json(SETS_SEEN, {}), now = {}, diff = [];
for (let name in SETS) {
let a = uniq(was[name] ?? []), b = uniq(sets[name] ?? []);
now[name] = b;
let add = filter(b, (x) => index(a, x) < 0), del = filter(a, (x) => index(b, x) < 0);
if (length(add) || length(del))
push(diff, `${name} ${length(a)} → ${length(b)}${length(add) ? ': +' + some_of(add) : ''}${length(del) ? (length(add) ? ' ' : ': ') + '-' + some_of(del) : ''}`);
}
write_json(SETS_SEEN, now, 0o600);
// The first load since the router started: how many in each set (the members at debug).
if (first) {
syslog('info', 'nftables', `table inet dawnline: ${how} · ${join(', ', map(SETS, (n) => `${n} ${length(now[n])}`))}`);
for (let n in SETS)
if (length(now[n]))
syslog('debug', 'nftables', `set ${n}: ${join(' ', now[n])}`);
}
else if (length(diff))
syslog('info', 'nftables', `table inet dawnline: ${how} · ${join('; ', diff)}`);
else
syslog('debug', 'nftables', `table inet dawnline: ${how} · sets unchanged (${join(', ', map(SETS, (n) => `${n} ${length(now[n])}`))})`);
}
function ip4(a) {
return ip2int(a ?? '') != null;
}
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
/**
* Per-person runtime membership: which tunnel addresses may reach what.
* `snap` is the network (net.snapshot() when not given).
*/
export function access_sets(m, usage, states, snap) {
// lan_ok: home access (the router itself, the mesh); lan_all: every home
// network; lan_part: device . network for people limited to some networks;
// mesh_pairs: device . device within a circle (or one person's own devices);
@@ -27,7 +80,7 @@ export function access_sets(m, usage, states) {
let sets = {};
for (let k in SETS)
sets[k] = [];
let snap = net.snapshot();
snap ??= net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
@@ -91,13 +144,23 @@ function portal_ports(m) {
return ports;
}
function table(m, sets) {
/**
* What the table is made from besides the model, read from the router: the
* netns's DNS address (loop.client_dns), where the Home-only resolver runs
* (loop.resolver_target), the LAN's DNS and the network snapshot.
*/
function router_ctx() {
return { dns_addr: loop.client_dns(), resolver: loop.resolver_target(), lan_dns: loop.lan_dns(), snap: net.snapshot() };
}
function table(m, sets, ctx) {
ctx ??= router_ctx();
let ifs = [], tun = [];
let dns_addr = loop.client_dns();
let dns_addr = ctx.dns_addr;
if (!ip4(dns_addr))
dns_addr = null;
let rt = loop.resolver_target();
let snap = net.snapshot();
let rt = ctx.resolver;
let snap = ctx.snap;
// Each server's home networks are its own: with several servers, "all
// home" on one never reaches the other's networks (set lan_<id>).
let homes = {};
@@ -194,7 +257,7 @@ function table(m, sets) {
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' && ip4(rt.address) ? `dnat ip to ${rt.address}:53` : `redirect to :${+rt.port}`;
let lan_dns = loop.lan_dns();
let lan_dns = ctx.lan_dns;
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
@@ -202,6 +265,13 @@ function table(m, sets) {
if (length(ifs))
// Home names (and no LAN DNS at all): the plain resolver, whatever address was asked.
push(t, ` iifname { ${join(', ', ifs)} } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 ${to_resolver}`);
push(t, ' }');
// After the LAN's own DNS interceptors (transparent proxies redirect port 53
// at dstnat - 1): only the first NAT of a connection counts, so a DNAT here
// first would hand the query to the plain resolver behind their back. When
// none of them takes the tunnel, this sends it to the LAN's DNS.
push(t, ' chain dns_lan {');
push(t, ' type nat hook prerouting priority dstnat + 5; policy accept;');
for (let id, srv in m.servers)
for (let tn in core.tunnels(srv)) {
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
@@ -228,14 +298,28 @@ export function load(script) {
return replace(trim(r.out), f, 'rules') || `nft exited with ${r.code}`;
};
/** The table as text, for a check (`nft -c -f`) or a test; nothing is loaded. */
export function render(m, sets) {
return table(m, sets);
/**
* The table as text, for a check (`nft -c -f`) or a test; nothing is loaded.
* `ctx` (a test's) stands for what is read from the router: { dns_addr,
* resolver, lan_dns, snap } (router_ctx).
*/
export function render(m, sets, ctx) {
return table(m, sets, ctx);
};
/** Full table rebuild (structure changes: servers, home networks, DNS paths); null or the error. */
export function rebuild(m, sets) {
return load('table inet dawnline\ndelete table inet dawnline\n' + table(m, sets));
let t = table(m, sets);
let err = load('table inet dawnline\ndelete table inet dawnline\n' + t);
if (err) {
syslog('error', 'nftables', `table inet dawnline: rebuild failed · ${err}`);
return err;
}
let n = shape(t);
syslog('info', 'nftables', sprintf('table inet dawnline: rebuilt · %d chains, %d sets, %d rules', n.chains, n.sets, n.rules));
syslog_lines('debug', 'nftables', t, 'nft: ');
log_sets(sets, 'sets loaded with the table');
return null;
};
/**
@@ -251,7 +335,12 @@ export function update(sets) {
if (length(members))
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
}
return load(s);
let err = load(s);
if (err)
syslog('warn', 'nftables', `table inet dawnline: set update failed, rebuilding · ${err}`);
else
log_sets(sets, 'sets updated');
return err;
};
/** Is the table loaded (watchdog). */
@@ -47,13 +47,28 @@ export function version(name) {
return found ? trim(found[2]) : null;
};
/**
* The package a control text names: { name, version }, each null when it
* does not say. Pure: an ipk's control file (ipk true), else `apk adbdump`
* of an apk, whose first name and version are the package's own (its files
* are "- name:" entries further down).
*/
export function control_info(text, ipk) {
if (ipk)
return { name: match(text, /(^|\n)Package: *([^\n]+)/)?.[2], version: match(text, /(^|\n)Version: *([^\n]+)/)?.[2] };
return { name: match(text, /\n *name: *([^\n]+)/)?.[1], version: match(text, /\n *version: *([^\n]+)/)?.[1] };
};
/** The package inside a file: { name, version }, each null when the file does not say. */
export function file_info(path) {
if (match(path, /\.ipk$/))
return control_info(run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out, true);
return control_info(run(`apk adbdump ${q(path)}`).out, false);
};
/** The version inside a package file, or null. */
export function file_version(path) {
if (match(path, /\.ipk$/)) {
let o = run(`tar -xzOf ${q(path)} ./control.tar.gz | tar -xzO ./control`).out;
return match(o, /(^|\n)Version: *([^\n]+)/)?.[2];
}
return match(run(`apk adbdump ${q(path)}`).out, /\n *version: *([^\n]+)/)?.[1];
return file_info(path).version;
};
/**
@@ -105,22 +120,54 @@ function preflight(files, need_kb, log) {
log?.(' ' + sprintf(_('%d MB free on the overlay'), int(free / 1024)));
}
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
/** Dawnline's own package: a file of it tells whether apk really reinstalled it. */
const SELF = 'luci-app-dawnline', SELF_MARKER = '/usr/share/ucode/dawnline/util.uc';
/**
* The packages an apk install did not leave at their file's version: apk
* takes a given file as it is (an older version too, a rollback) but leaves
* an installed version alone, whatever the file. Pure: want [{ name,
* version, file }] from the files (file_info()), have { name: installed
* version }. [] when every package took.
*/
export function mismatched(want, have) {
return filter(want, (w) => w.name == null || w.version == null || have?.[w.name] != w.version);
};
/**
* Package files (from a release): true when every one is installed. force
* also reinstalls the same version or goes back to an older one (opkg; apk
* takes a file as it is: Dawnline's own package is checked by a file of it,
* any other by its installed version).
*/
export function install_files(files, force, log) {
preflight(files, 0, log);
let args = join(' ', map(files, q));
if (!is_apk())
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
// apk leaves an installed version alone, whatever the file: a reinstall
// that changed nothing is a failure, not a silent "done".
let marker = '/usr/share/ucode/dawnline/util.uc';
let before = force ? stat(marker)?.mtime : null;
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
if (ok && force && before != null && stat(marker)?.mtime == before) {
let want = map(files, (f) => ({ ...file_info(f), file: f }));
let own = length(filter(want, (w) => w.name == SELF)) > 0;
// Dawnline's own reinstall that changed nothing is a failure, not a silent "done".
let before = own && force ? stat(SELF_MARKER)?.mtime : null;
if (logged(`apk add --allow-untrusted ${args}`, log).code != 0)
return false;
if (own) {
if (force && before != null && stat(SELF_MARKER)?.mtime == before) {
log?.(' ' + _('apk did not reinstall the version that is already installed'));
die(_("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router"));
}
return ok;
return true;
}
// Any other package took when it is at its file's version (the same
// version again counts: apk keeps the installed one).
let have = {};
for (let w in want)
if (w.name != null)
have[w.name] = version(w.name);
let bad = mismatched(want, have);
for (let w in bad)
log?.(' ' + sprintf(_('apk did not install %s %s (installed: %s)'), w.name ?? w.file, w.version ?? '?', have[w.name] ?? '-'));
return !length(bad);
};
/** Packages by name from the feeds. */
@@ -1,11 +1,11 @@
// Dawnline — the personal portal.
//
// GET /<code> the app shell
// GET /<code>/assets/<file> its script, styles and fonts
// GET /<code>/assets/<file> its script and styles (gzipped when the browser takes it)
// GET /<code>/api/state
// POST /<code>/api/devices { name, kind, public_key? }
// POST /<code>/api/devices { name, kind, public_key?, lan_bypass? }
// GET /<code>/api/devices/<id>/config
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
// POST /<code>/api/devices/<id> { action: rename|reconnect|bypass|delete, name?, kind?, lan_bypass?, on? }
//
// The personal link is the key: every request carries its code, there are
// no sessions. Without a valid code every path answers the same bare 404 —
@@ -33,10 +33,11 @@
// that answers anything not shaped like a link (its not_found() twin).
import { stat, readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, syslog, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
import * as lookup from 'dawnline.lookup';
import * as view from 'dawnline.view';
import * as schema from 'dawnline.schema';
import * as devices from 'dawnline.devices';
@@ -45,7 +46,7 @@ import { _ } from 'dawnline.i18n';
const RATE = `${RUN_DIR}/portal-rate.json`;
const ASSETS = '/usr/share/dawnline/portal/assets';
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2', png: 'image/png' };
const TYPES = { js: 'text/javascript', css: 'text/css', png: 'image/png' };
const FAIL_LIMIT = 8;
const FAIL_WINDOW = 900;
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
@@ -263,24 +264,26 @@ function place(r) {
/** The app shell; it reads the code from its own URL and sends it along. */
function shell(r) {
// The build's time joins the version so every update busts the hour-long asset cache.
// The build's time joins the version: every update gives the assets new URLs, so they are cached for good.
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
let base = r.base, title = place(r);
// The icon goes in the page: a request of its own would start another CGI process.
let icon = readfile(`${ASSETS}/icon.svg`);
let favicon = icon ? `<link rel="icon" href="data:image/svg+xml;base64,${b64enc(icon)}" type="image/svg+xml">\n` : '';
headers(r, '200 OK', {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; " +
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
});
r.io.write(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<meta name="robots" content="noindex, nofollow">
<title>${html_escape(title)}</title>
<link rel="icon" href="${base}/assets/icon.svg${v}" type="image/svg+xml">
<link rel="stylesheet" href="${base}/assets/portal.css${v}">
${favicon}<link rel="stylesheet" href="${base}/assets/portal.css${v}">
</head>
<body>
<div id="app" data-base="${html_escape(base)}" data-title="${html_escape(title)}"></div>
@@ -291,13 +294,18 @@ function shell(r) {
finish();
}
/** Script, styles, icon and fonts (kept outside the web root). */
/** Script and styles (kept outside the web root); the shell's ?v= changes with every build, so they never go stale. */
function asset(r, name) {
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
let ext = match(name, /^[a-z0-9-]+\.(js|css|png)$/)?.[1];
// The build keeps a gzipped copy beside each: a third of the bytes for a browser that takes it.
let gz = ext && r.gzip ? readfile(`${ASSETS}/${name}.gz`) : null;
let data = gz ?? (ext ? readfile(`${ASSETS}/${name}`) : null);
if (data == null)
not_found(r);
headers(r, '200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
let h = { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=31536000, immutable', 'Vary': 'Accept-Encoding' };
if (gz != null)
h['Content-Encoding'] = 'gzip';
headers(r, '200 OK', h);
r.io.write(data);
finish();
}
@@ -368,7 +376,8 @@ function tz_offset() {
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
// Only their server's tunnel: one `awg` process per request, however many servers there are.
let v = view.person_view(m, person, usage, live.dump(m, person.server ?? ''), view.states(m, usage));
v.state = person_state(m, person, usage);
// Day by day this month, for the page's chart (the admin's views have no use for it).
v.month_days = view.month_days(usage.people?.[person.id]);
@@ -384,6 +393,9 @@ function state(r) {
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
// The home networks a device with LAN Bypass still sends into the tunnel (home and internet access):
// its own local network on the same addresses is out of reach (Add a device says so).
home: srv && person.access == 'both' ? core.person_home(srv, person).nets : [],
},
can_add: length(person.devices) < person.device_limit,
locked: index(LOCKED, v.state) >= 0,
@@ -412,6 +424,17 @@ function api_state(r) {
send_json(r, '200 OK', state(r));
}
/**
* A configuration as the portal sends it: with the server's address as an IP
* too (amnezia.host_ip, lookup.host_ip()), for V2RayTun on Android, which
* takes no name for AmneziaWG. Lookups are cached for minutes (lookup.uc).
*/
function with_ip(cfg) {
if (cfg?.amnezia)
cfg.amnezia.host_ip = lookup.host_ip(cfg.amnezia.host);
return cfg;
}
function api_add(r) {
need_open(r);
need_https(r);
@@ -419,9 +442,10 @@ function api_add(r) {
if (!devices.ready())
fail(r, '503 Service Unavailable', not_ready());
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
// lan_bypass: JSON true keeps the device's own local network out of the tunnel; anything else is off.
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key, lan_bypass: b.lan_bypass === true }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
send_json(r, '200 OK', { id: res.id, config: with_ip(res.config), state: state(r) });
}
function api_config(r, id) {
@@ -429,7 +453,7 @@ function api_config(r, id) {
need_open(r);
need_https(r);
awg.mark_issued(r.m, d.id);
send_json(r, '200 OK', awg.client_config(r.m, d));
send_json(r, '200 OK', with_ip(awg.client_config(r.m, d)));
}
/** POST /devices/<id> { action }: what each action does; the answer carries the new state. */
@@ -443,8 +467,20 @@ const ACTIONS = {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', not_ready());
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config };
// What it is and LAN Bypass may change with the keys (the sheet asks again); left out, they stay.
let kind = type(b.kind) == 'string' ? b.kind : null;
let bypass = type(b.lan_bypass) == 'bool' ? b.lan_bypass : null;
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer,
kind, lan_bypass: bypass }));
return { config: with_ip(config) };
},
// LAN Bypass on or off, keys unchanged: the device takes its updated configuration (the set-up sheet opens on it).
bypass: (r, d, b) => {
need_https(r);
if (type(b.on) != 'bool')
fail(r, '400 Bad Request', _('Unknown action.'));
guard(r, () => devices.update(d.id, { lan_bypass: b.on }, { by: 'portal', person: r.person.id }));
return {};
},
'delete': (r, d, b) => {
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
@@ -514,6 +550,7 @@ export function handle(io) {
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null,
base: '',
gzip: match(lc(header('accept-encoding') ?? ''), /(^|[ ,])gzip([ ;,]|$)/) != null,
};
let segs = filter(split(path, '/'), (s) => s != '');
@@ -577,7 +614,11 @@ export function serve(io) {
handle(io);
}
catch (e) {
if (e.message != DONE)
if (e.message != DONE) {
// What broke and where; the path without its first part (the person's link code is a secret).
let path = replace(split(io.env.REQUEST_URI ?? '', '?')[0], /^\/[^\/]*/, '/<link>');
syslog('error', 'portal', `${io.env.REQUEST_METHOD ?? '?'} ${path}: 500 · ${e.message}${e.stacktrace?.[0]?.context ? ' · ' + replace(e.stacktrace[0].context, /[\r\n\t]+/g, ' ') : ''}`);
io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`);
}
}
};
@@ -21,11 +21,14 @@ export function name_covers(name, host) {
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
};
// A module constant, compiled once, not for each file of the directory.
const FULLCHAIN = /^(.+)\.fullchain\.crt$/;
/** ACME certificates on the router and the names each covers. */
export function acme_certs() {
let out = [];
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
let m = match(f, /^(.+)\.fullchain\.crt$/);
let m = match(f, FULLCHAIN);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
@@ -6,7 +6,7 @@
import { readfile, writefile, stat } from 'fs';
import { cursor } from 'uci';
import { ensure_dir, iface_status, uniq } from 'dawnline.util';
import { ensure_dir, iface_status, uniq, syslog, syslog_lines } from 'dawnline.util';
import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
@@ -90,10 +90,15 @@ export function sync(m, target, lan) {
for (let d in lan_domain(m))
push(lines, `server=/${d}/${lan}`);
let conf = join('\n', lines) + '\n';
if ((readfile(CONF) ?? '') == conf)
let where = target.mode == 'ns' ? `${target.address}:${target.port} in the netns` : length(ifs) ? `port ${target.port} on ${join(', ', ifs)}` : 'loopback only (no tunnel on)';
if ((readfile(CONF) ?? '') == conf) {
syslog('debug', 'dns', `resolver for Home-only devices: unchanged · ${where}`);
return false;
}
writefile(CONF, conf);
system(`chmod 644 ${CONF}`);
syslog('info', 'dns', `resolver for Home-only devices: ${CONF} written · ${where} · upstream ${join(' ', wan_dns()) || 'none'}${lan ? ` · home names via ${lan}` : ''}; restarting it`);
syslog_lines('debug', 'dns', conf, 'dnsmasq: ');
let pid = trim(readfile(PID) ?? '');
if (match(pid, /^[0-9]+$/))
system(`kill ${pid} 2>/dev/null`);
@@ -8,6 +8,7 @@ import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import * as lookup from 'dawnline.lookup';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
import { _ } from 'dawnline.i18n';
@@ -56,7 +57,9 @@ function person_update(a) {
let s = apply.sync();
let m = core.load();
let u = core.load_usage();
return { person: view.person_view(m, m.people[a.id], u, live.dump(m), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
// One person: only their server's tunnel is read.
let p = m.people[a.id];
return { person: view.person_view(m, p, u, live.dump(m, p.server ?? ''), view.states(m, u), { admin: true }), was: before?.access, warning: s.warning };
}
function person_pause(a) {
@@ -138,20 +141,34 @@ function person_usage(a) {
function device_create(a) {
devices.need_awg();
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
return devices.add(a.person, a.name, a.kind, { by: 'admin', lan_bypass: a.lan_bypass === true });
}
/**
* A device's configuration. Only `issue` (true: the admin shows its QR code,
* downloads or copies it) counts as handing it out; a look at the device
* marks nothing, so its "settings changed" stays until it really gets them.
*/
function device_config(a) {
let m = core.load();
let d = m.devices[a.id];
if (!d)
die(_('Unknown device.'));
if (a.issue === true)
awg.mark_issued(m, d.id);
return awg.client_config(m, d);
let cfg = awg.client_config(m, d);
// V2RayTun on Android takes the server by its IP (the admin's set-up shows its link for phones, tablets and
// other devices): only where it can connect at all, and AmneziaWG 3.1 (Maximum) is beyond it.
let srv = m.servers[m.people[d.person]?.server];
if (cfg && d.kind != 'router' && d.kind != 'computer' && srv?.preset != 'max')
cfg.amnezia.host_ip = lookup.host_ip(cfg.amnezia.host);
return cfg;
}
/** Name, on/off and the link values (mtu, keepalive: strings, '' = the server's; lan_bypass: true or false). */
function device_update(a) {
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
return devices.update(a.id, { name: a.name, disabled: a.disabled, mtu: a.mtu, keepalive: a.keepalive,
lan_bypass: a.lan_bypass == null ? null : a.lan_bypass === true }, { by: 'admin' });
}
export const methods = {
@@ -169,9 +186,10 @@ export const methods = {
person_links: { args: { id: '' }, call: wrap(person_links) },
person_delete: { args: { id: '' }, call: wrap(person_delete) },
person_usage: { args: { id: '', days: 30 }, call: wrap(person_usage) },
device_create: { args: { person: '', name: '', kind: '' }, call: wrap(device_create) },
device_config: { args: { id: '' }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false }, call: wrap(device_update) },
device_create: { args: { person: '', name: '', kind: '', lan_bypass: false }, call: wrap(device_create) },
device_config: { args: { id: '', issue: false }, call: wrap(device_config) },
device_update: { args: { id: '', name: '', disabled: false, mtu: '', keepalive: '', lan_bypass: false }, call: wrap(device_update) },
device_delete: { args: { id: '' }, call: wrap((a) => devices.remove(a.id, { by: 'admin' })) },
device_rotate: { args: { id: '' }, call: wrap((a) => devices.rotate(a.id, { by: 'admin' })) },
// New keys: the device is set up again, as with the portal's Reconnect.
device_rotate: { args: { id: '' }, call: wrap((a) => devices.reconnect(a.id, { by: 'admin' })) },
};
@@ -325,7 +325,8 @@ function server_create(a) {
set('detected_wan', snap.wan);
if (snap.lan)
set('detected_lan', snap.lan);
set('lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
// Off unless asked for: the loop through the LAN costs speed (the wizard says how much).
set('lan_like', a.lan_like === true || a.lan_like === 1 || a.lan_like === '1' ? '1' : '0');
set('enabled', '1');
if (a.portal_enabled != null) {
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
@@ -595,6 +596,10 @@ function server_ports(a) {
function server_obfuscation(a) {
let preset = str(a.preset) || default_method();
let o = awg.obf_preset(check_method(preset));
// A cheap self-check: new values pass what a restore would be held to.
let errs = awg.obf_errors(o);
if (length(errs))
die(join(' ', errs));
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
@@ -2,7 +2,7 @@
// history, updates). What may be saved is dawnline.schema's.
import { stat } from 'fs';
import { q, sh_out, admin_log, RUN_DIR, DATA_DIR } from 'dawnline.util';
import { q, sh_out, admin_log, syslog, RUN_DIR, DATA_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
@@ -96,16 +96,25 @@ function settings_update(a) {
die(_('Nothing to save.'));
let res = store.transact((c, m) => {
let restart = false;
// What each key was and became, as uci holds them (for syslog: every change, not only those worth a line).
let diff = [];
let note = (k, to) => {
let from = c.get(core.CONFIG, 'settings', k);
if (!same(to, from))
push(diff, { k, from, to });
};
c.set(core.CONFIG, 'settings', 'settings');
for (let k, val in v) {
if (k == 'log_category') {
let lst = filter(type(val) == 'array' ? val : [], (x) => index(live.CATEGORIES, x) >= 0);
note(k, length(lst) ? lst : [ '' ]);
c.set(core.CONFIG, 'settings', 'log_category', length(lst) ? lst : [ '' ]);
// Superseded by the category list.
c.delete(core.CONFIG, 'settings', 'log_connections');
continue;
}
let nv = schema.validate(k, val);
note(k, nv);
if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k)))
restart = true;
if (nv == null)
@@ -114,8 +123,13 @@ function settings_update(a) {
c.set(core.CONFIG, 'settings', k, nv);
}
check_portal(core.load(c), m);
return { restart, was: m.settings };
return { restart, was: m.settings, diff };
});
// Every setting that changed, in syslog: "admin changed settings · log_keep_days: 30 → 90, domain: lan → home".
if (length(res.diff)) {
let val = (x) => x == null || x == '' ? 'default' : type(x) == 'array' ? join(' ', filter(x, (y) => y != '')) || 'none' : `${x}`;
syslog('info', 'settings', `admin changed settings · ${join(', ', map(res.diff, (d) => `${d.k}: ${val(d.from)} → ${val(d.to)}`))}`);
}
let s = null;
if (res.restart)
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
@@ -1,5 +1,6 @@
// Dawnline rpcd methods: the live revision, the Overview status (servers,
// people, totals, map, recent activity), the activity log and traffic history.
// people, totals, map, recent activity), the live meter, the activity log and
// traffic history.
import { readfile } from 'fs';
import { _ } from 'dawnline.i18n';
@@ -13,6 +14,7 @@ import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as lookup from 'dawnline.lookup';
import * as health from 'dawnline.health';
import * as meter from 'dawnline.meter';
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
/** The router's public IPv4 (null when none or private). */
@@ -127,7 +129,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
blocked: awg.blocked_text(srv),
// Home networks (interfaces) for the per-person picker.
home: map(net.server_net(srv).home, (h) => ({ dev: h.dev, nets: h.nets })),
peers, online, obf: srv.obf,
// The header protection key is a secret every device shares: whether there is one.
peers, online, obf: awg.obf_public(srv.obf), hpk: !!srv.obf.header_protection_key,
// Bytes per second, one point a minute: [ts, rx, tx] (rx = from devices).
rate: rates[srv.id] ?? [],
// Daily traffic of the people on this server (its Overview chart).
@@ -137,7 +140,8 @@ function server_view(m, srv, usage, dmp, rates, days) {
/*
* Everything the pages show at once. Readable by read-only users: no personal
* codes or links here (person_links has them).
* codes or links here (person_links has them), and no keys but public ones
* (device_config has the rest).
*/
function status(a) {
let m = core.load();
@@ -282,8 +286,21 @@ function rev() {
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
}
/*
* The live meter (Overview): each call keeps the agent's watcher writing out
* the points it keeps for meter.WANT_FOR seconds more (a first call finds
* none yet: the watcher writes the last two minutes within a second) and
* returns them (dawnline.meter.read), those newer than `since` when given. Read-only users may look: server ids
* and bytes per second only, no keys or personal codes.
*/
function meter_points(a) {
meter.want();
return meter.read(+a.since || 0);
}
export const methods = {
rev: { call: wrap(rev) },
meter: { args: { since: 0 }, call: wrap(meter_points) },
status: { args: { days: 30 }, call: wrap(status) },
events: { args: { limit: 300, person: '', since: 0 }, call: wrap(events_list) },
logs_clear: { args: { person: '', device: '', category: '', older_days: '' }, call: wrap(logs_clear) },
@@ -44,11 +44,14 @@ function awg_tunnels() {
return out;
}
// A line of /etc/openwrt_release. A module constant, compiled once, not for each line.
const RELEASE_LINE = /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/;
function status(a) {
let m = core.load();
let rel = {};
for (let line in split(readfile('/etc/openwrt_release') ?? '', '\n')) {
let x = match(line, /^DISTRIB_(RELEASE|TARGET|ARCH)='([^']*)'/);
let x = match(line, RELEASE_LINE);
if (x)
rel[lc(x[1])] = x[2];
}
@@ -77,7 +80,7 @@ function releases(a) {
let page = +(a.page ?? 1);
if (page != int(page) || page < 1 || page > 50)
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, ids: null })), page };
}
/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */
@@ -91,7 +94,7 @@ function notes(a) {
r = gh.release(rp, `v${tag}`);
if (!r)
die(sprintf(_('No release %s in %s.'), tag, rp));
return { ...r, digests: null, repo: rp };
return { ...r, digests: null, ids: null, repo: rp };
}
/** What changed between the installed Dawnline and a release (points for the Components tab). */
@@ -108,8 +111,10 @@ function changes(a) {
}
/**
* Start an update job. Returns the new job once its worker has written it,
* else null (the caller follows updates_status); never an older job.
* Start an update job. Returns the new job once its worker has written it
* (a quick check may be over by then), else null (the caller follows
* updates_status); never an older job. Waits two seconds at most: LuCI gives
* up on a call after twenty.
*/
function run(a) {
let what = a.what ?? 'check';
@@ -123,16 +128,17 @@ function run(a) {
if (upd.busy())
die(_('Another component action is already running'));
ensure_dir(RUN_DIR);
let t0 = time();
let t0 = time(), prev = read_json(upd.JOB_FILE, null)?.id;
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
// The job speaks the admin's language (use() let only a plain language code through).
let lang = i18n.current();
system(`${lang ? `DAWNLINE_LANG=${lang} ` : ''}start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
for (let i = 0; i < 20; i++) {
let j = read_json(upd.JOB_FILE, null);
if (j?.state == 'running' && j.started >= t0)
if (j && j.id != prev && j.started >= t0)
return { started: true, job: j };
system('usleep 100000 2>/dev/null || sleep 1');
// ucode's own sleep: OpenWrt's BusyBox has no usleep.
sleep(100);
}
return { started: true, job: null };
}
@@ -127,6 +127,8 @@ export const SETTINGS = {
geo_enabled: { type: 'bool', dflt: false },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ] },
log_connections: { type: 'bool', dflt: true },
// What goes to syslog (dawnline.util syslog): error | warn | info | debug (each step of a start or an apply).
log_level: { type: 'enum', dflt: 'info', values: [ 'error', 'warn', 'info', 'debug' ] },
watchdog: { type: 'bool', dflt: true },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999 },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000 },
@@ -158,6 +160,7 @@ function messages() {
default_device_limit: _('Default device limit must be 1-32.'),
domain: _('Domain may use lowercase letters, digits, dashes and dots.'),
geo_provider: _('Unknown location service.'),
log_level: _('Choose a system log level: errors, warnings, normal or verbose.'),
log_keep_days: _('Keep activity for 0 (no age limit) to 9999 days.'),
log_max: _('Log size must be 100-20000 events.'),
log_persist: _('Save the log every 10min, hourly or off.'),
@@ -30,7 +30,7 @@ export function check(ctx) {
/**
* The sha256 a release publishes for a file: GitHub's own (API), else the
* release's sha256sums.txt fetched straight from github.com (never a mirror).
* release's sha256sums.txt fetched straight from GitHub (never a mirror).
*/
function want_sha(ctx, tag, asset, dir) {
let want = gh.asset_sha256(REPO, tag, asset);
@@ -1,6 +1,8 @@
// Dawnline updater: AmneziaWG — the builds published for this firmware by
// each source, installing or switching a build (verified against GitHub's
// sha256), the Russian LuCI translation, and rolling back to a kept build.
// Every install and rollback is recorded (dawnline.awg_builds), with whether
// the new kernel module runs or waits for the next boot.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { stat } from 'fs';
@@ -89,6 +91,8 @@ export function check(ctx) {
current = id;
let mine = current ? sources[current] : null;
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
// An update that waits for a reboot: Components says so after a check.
let pending = builds.waits_for_reboot();
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
ctx.log(cur == null ? _('AmneziaWG is not installed')
: !current ? sprintf(_('AmneziaWG %s: no source publishes this build for this firmware any more'), cur)
@@ -99,13 +103,19 @@ export function check(ctx) {
update: cur == null || st == 'outdated',
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1)) : null };
pending,
note: !length(filter(values(sources), (x) => x.version)) ? sprintf(_('No AmneziaWG build for OpenWrt %s yet'), substr(fw.tag, 1))
: pending ? _('The AmneziaWG update is installed and starts after a reboot.') : null };
};
/** Tunnels on a new kernel module: every AmneziaWG interface is brought down and up again. */
function reload_module(ctx, before, after) {
if (!before['kmod-amneziawg'] || before['kmod-amneziawg'] == after['kmod-amneziawg'])
return;
/**
* Tunnels on a new kernel module: every AmneziaWG interface is brought down,
* the module swapped and the interfaces brought up again. False when the old
* module stays loaded: the tunnels come back on it (the tools talk to an
* older module at its own netlink version) and the installed one starts
* with the next boot, which caps() and Health then wait for.
*/
function reload_module(ctx) {
let ifaces = [];
let c = cursor();
c.load('network');
@@ -119,33 +129,58 @@ function reload_module(ctx, before, after) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`);
}
// Both steps must really happen: the new tools against the old module (or
// no module at all) leave every tunnel down while the job says "done".
ctx.run('rmmod amneziawg');
if (stat('/sys/module/amneziawg'))
die(_('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update'));
ctx.run('rmmod amneziawg');
let swapped = !stat('/sys/module/amneziawg');
if (swapped) {
ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg'))
die(_("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)"));
}
for (let i in ifaces)
sh(`ifup '${i}'`);
return swapped;
}
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
/**
* After packages changed: the module loaded, netifd knowing the protocol,
* Dawnline set up again. was: the module loaded before (builds.module_now()).
* Returns whether the module that runs is the installed one; false while the
* old one stays loaded until the next boot.
*/
function settle(ctx, before, after, was) {
let b = before['kmod-amneziawg'], a = after['kmod-amneziawg'];
let fresh = true;
// A new module package, one over a module loaded by hand, or an earlier
// update that still waits for a boot (Reinstall tries again).
if (a && (a != b || was.pending) && (b || was.core != null))
fresh = reload_module(ctx);
else if (a && !b) {
ctx.phase(_('Loading the kernel module'));
if (ctx.run('modprobe amneziawg').code != 0 && !stat('/sys/module/amneziawg'))
die(_("AmneziaWG is installed, but its kernel module doesn't load on this firmware"));
}
else
reload_module(ctx, before, after);
// netifd reads its protocol handlers when it starts.
if (index(ctx.run('ubus call network get_proto_handlers').out, '"amneziawg"') < 0) {
ctx.phase(_('Restarting the network so it knows AmneziaWG (connections drop for a few seconds)'));
ctx.run('/etc/init.d/network restart');
}
ctx.after('apply');
return fresh;
}
/**
* The packages are in: settle them and record the build (source, tag) with
* the module that ran before (was). An old module that stays loaded is no
* failure: the job says so, and Health until the next boot.
*/
function finish(ctx, out, source, tag, was) {
out.after = builds.installed();
out.reloaded = settle(ctx, out.before, out.after, was);
builds.record(source, tag, out.after, { prev_gen: was.gen, prev_core: was.core, reloaded: out.reloaded });
if (!out.reloaded)
ctx.log(_('The old kernel module stays loaded (another AmneziaWG interface may use it): the AmneziaWG update is installed and starts after a reboot.'));
return out;
}
/** The first source that publishes every package for this firmware. */
@@ -165,6 +200,7 @@ function pick(fw) {
/** arg: [auto|slava|grey][:ru] | rollback */
export function install(ctx, arg) {
let before = builds.installed();
let was = builds.module_now(before['kmod-amneziawg']);
let out = { from: before['amneziawg-tools'], to: null, before };
let fw = builds.firmware();
if (!fw)
@@ -182,9 +218,7 @@ export function install(ctx, arg) {
if (!pkg.install_files(k.files, true, ctx.log))
die(_('Package installation failed'));
upd.forget('amneziawg');
out.after = builds.installed();
settle(ctx, before, out.after);
return out;
return finish(ctx, out, k.build, fw.tag, was);
}
let parts = split(arg ?? '', ':');
let id = parts[0] || 'auto';
@@ -236,8 +270,5 @@ export function install(ctx, arg) {
die(_('Package installation failed'));
if (!want_ru && pkg.version(builds.RU))
pkg.remove([ builds.RU ], ctx.log);
out.after = builds.installed();
settle(ctx, before, out.after);
builds.record(id, fw.tag, out.after);
return out;
return finish(ctx, out, id, fw.tag, was);
};
@@ -5,7 +5,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
import { _ } from 'dawnline.i18n';
export const VERSION = '0.12.1';
export const VERSION = '0.18.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
@@ -226,6 +226,96 @@ export function ack_config(confs) {
writefile(md5f, join('\n', lines) + '\n');
};
/* ---------- syslog ---------- */
/*
* Every line Dawnline puts in syslog, as podkop and sing-box do it:
* dawnline: [info] [awg] Home started · accepting connections on port 51820
* with the matching priority (daemon.err, .warning, .info, .debug), so
* `logread -e dawnline` or a remote syslog filters by level. The admin's
* level (settings.log_level) decides what goes out: error | warn | info
* (the default) | debug (each step of a start or an apply).
*/
const LOG_RANK = { error: 0, warn: 1, info: 2, debug: 3 };
const LOG_PRIO = { error: 'err', warn: 'warning', info: 'info', debug: 'debug' };
const LOG_LEVEL_RE = regexp("option log_level '?(error|warn|info|debug)'?");
// The level as last read, and the config file's mtime it was read at (a long-running agent sees a change).
let log_cfg = { mtime: -1, level: 'info' };
/** The admin's syslog level (settings.log_level): error | warn | info | debug; info when not set. */
export function log_level() {
let mt = stat('/etc/config/dawnline')?.mtime ?? 0;
if (mt != log_cfg.mtime) {
let m = match(readfile('/etc/config/dawnline') ?? '', LOG_LEVEL_RE);
log_cfg = { mtime: mt, level: m?.[1] ?? 'info' };
}
return log_cfg.level;
};
/** Does a line at `level` go out at the admin's level? */
export function log_on(level) {
return (LOG_RANK[level] ?? 2) <= LOG_RANK[log_level()];
};
// A line break or a tab with the blanks around it: one space in a syslog line (compiled once, syslog runs often).
const LOG_BREAK = /[ \t\r\n]*[\t\r\n][ \t\r\n]*/g;
/** One syslog line's words: "[level] [src] line", on one line, at most 1000 characters. */
export function syslog_line(level, src, line) {
let one = replace(trim(`${line ?? ''}`), LOG_BREAK, ' ');
return substr(`[${LOG_RANK[level] != null ? level : 'info'}] [${src ?? 'dawnline'}] ${one}`, 0, 1000);
};
/**
* A line in syslog at `level` (error | warn | info | debug) from `src`
* (dawnline, awg, portal, apply, agent, service, settings, people, …), when
* the admin's level takes it. Nothing is kept anywhere else: what the admin UI
* shows goes through slog() below, which calls this too.
*/
export function syslog(level, src, line) {
if (!log_on(level))
return;
system(`logger -t dawnline -p daemon.${LOG_PRIO[level] ?? 'info'} ${q(syslog_line(level, src, line))}`);
};
// Option names whose values never go in a log line: private, preshared and header-protection keys.
const SECRET_OPT = /(private|preshared|protection)_?key/;
/**
* Options as a log line's words: "listen_port=51820, addresses=10.8.0.1/24,
* private_key=***" (arrays joined with spaces, null as "-", secrets masked).
*/
export function opts_text(o) {
let out = [];
for (let k, v in o ?? {}) {
let s = v == null ? '-' : type(v) == 'array' ? join(' ', v) : `${v}`;
push(out, `${k}=${match(k, SECRET_OPT) ? '***' : s}`);
}
return join(', ', out);
};
/**
* A block of text in syslog, a line per line (an nft script, a peer list),
* each "[level] [src] <prefix><line>": one logger for all of them.
*/
export function syslog_lines(level, src, text, prefix) {
if (!log_on(level) || trim(`${text ?? ''}`) == '')
return;
let p = popen(`logger -t dawnline -p daemon.${LOG_PRIO[level] ?? 'info'}`, 'w');
if (!p)
return;
for (let l in split(`${text ?? ''}`, '\n'))
if (trim(l) != '')
p.write(syslog_line(level, src, `${prefix ?? ''}${trim(l)}`) + '\n');
p.close();
};
/** A list in a log line: the first `n` (10) and how many more ("a, b, c and 12 more"). */
export function some_of(list, n) {
n ??= 10;
return length(list) <= n ? join(', ', list) : `${join(', ', slice(list, 0, n))} and ${length(list) - n} more`;
};
/* ---------- service log ---------- */
/*
@@ -257,7 +347,11 @@ export function slog(src, level, msg, detail, who, extra) {
f.close();
}
let line = e.by == 'admin' ? join(' ', filter([ 'admin', msg, e.kind, who, e.note ? '· ' + e.note : null ], (x) => x)) : who ? `${who} ${msg}` : msg;
system(`logger -t dawnline${level == 'error' ? ' -p user.err' : ''} ${q(line)}`);
// Problems carry what went wrong (the service log's detail: an error's text, the syslog lines around a crash).
let lvl = { error: 'error', repair: 'warn', down: 'warn' }[level] ?? 'info';
if (e.detail && lvl != 'info')
line += ` · ${substr(replace(e.detail, /[\r\n\t]+/g, ' | '), 0, 400)}`;
syslog(lvl, src, line);
};
/** A change the admin made in LuCI, for the service log. */
@@ -365,8 +459,14 @@ export function slog_restore() {
/* ---------- IPv4 ---------- */
// Module constants, compiled once: a regex literal is compiled again each
// time it runs (rules/backend.md), and these run for every address and every
// network in a list (status, the portal, the agent's checks).
const IPV4 = /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/;
const CIDR = /^([0-9.]+)(\/([0-9]+))?$/;
export function ip2int(ip) {
let m = match(ip, /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
let m = match(ip, IPV4);
if (!m)
return null;
let n = 0;
@@ -389,7 +489,7 @@ export function int2ip(n) {
* allowed networks use this; parse_cidr is the stricter one for subnets.
*/
export function cidr_any(s) {
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/);
let m = match(s ?? '', CIDR);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
@@ -432,10 +532,10 @@ export function cloudflare_ip(a) {
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
export function parse_cidr(cidr) {
let m = match(cidr ?? '', /^([0-9.]+)\/([0-9]+)$/);
if (!m)
let m = match(cidr ?? '', CIDR);
if (!m || m[3] == null)
return null;
let ip = ip2int(m[1]), prefix = +m[2];
let ip = ip2int(m[1]), prefix = +m[3];
if (ip == null || prefix < 8 || prefix > 30)
return null;
let size = 1 << (32 - prefix);
@@ -549,8 +649,94 @@ export function name_rule() {
return _('Enter a name: up to 48 characters, without < > " or \\.');
};
// Character sets for checks written without a regex: ucode compiles a regex
// literal each time it runs, and musl's regcomp takes milliseconds for a
// bounded repeat (rules/backend.md). ltrim stops at a NUL byte, so a string
// with one fails these checks (a regex looks only up to it).
const ASCII_ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const B64 = `${ASCII_ALNUM}+/`;
/**
* The longest name a device takes, in characters: ordinary words fill a portal card's line about as far as its
* status ("Return to save, Esc to cancel"), and fit the server list in the AmneziaVPN app. Names set before the rule stay as they are; it holds when a name is set.
*/
export const DEVICE_NAME_MAX = 20;
// What a device's name may hold of ASCII: letters, digits, spaces and - _ . It goes into configurations, file
// names and the AmneziaVPN key: nothing there to escape.
const DEVICE_NAME_CHARS = `${ASCII_ALNUM} ._-`;
// Past ASCII, letters of any language are welcome; these blocks are not: symbols, punctuation, arrows, maths,
// emoji and invisibles (code point ranges, both ends in; web/src/shared/format.ts NAME_SYMBOLS is the same list,
// and the page asks Unicode besides that a character is a letter or a digit).
const NAME_SYMBOLS = [
[ 0x80, 0xbf ], [ 0xd7, 0xd7 ], [ 0xf7, 0xf7 ], [ 0x2000, 0x2bff ], [ 0x3000, 0x303f ], [ 0xd800, 0xf8ff ],
[ 0xfe00, 0xfe0f ], [ 0xfe30, 0xfe4f ], [ 0xfeff, 0xfeff ], [ 0xfff0, 0xffff ], [ 0x1f000, 0x1fbff ],
[ 0xe0000, 0xe007f ]
];
function name_symbol(cp) {
for (let r in NAME_SYMBOLS)
if (cp >= r[0] && cp <= r[1])
return true;
return false;
}
/**
* A device's name (trimmed by the caller): 1-DEVICE_NAME_MAX characters, not blank, each one of
* DEVICE_NAME_CHARS or past ASCII outside NAME_SYMBOLS. Read by code points: broken UTF-8, and an
* ASCII character spelled long (0xC0 0xAF for "/"), are refused.
*/
export function valid_device_name(s) {
if (type(s) != 'string' || length(trim(s)) == 0 || ulength(s) > DEVICE_NAME_MAX)
return false;
let i = 0, n = length(s);
while (i < n) {
let b = ord(s, i), cp, len;
if (b < 0x80) {
if (index(DEVICE_NAME_CHARS, substr(s, i, 1)) < 0)
return false;
i++;
continue;
}
if ((b & 0xe0) == 0xc0) {
len = 2;
cp = b & 0x1f;
}
else if ((b & 0xf0) == 0xe0) {
len = 3;
cp = b & 0x0f;
}
else if ((b & 0xf8) == 0xf0) {
len = 4;
cp = b & 0x07;
}
else
return false;
if (i + len > n)
return false;
for (let k = 1; k < len; k++) {
let c = ord(s, i + k);
if ((c & 0xc0) != 0x80)
return false;
cp = (cp << 6) | (c & 0x3f);
}
if (cp < 0xc0 || cp > 0x10ffff || name_symbol(cp))
return false;
i += len;
}
return true;
};
// 32 bytes are 43 base64 characters: the last holds four bits of the key and two zero bits.
const KEY_LAST = 'AEIMQUYcgkosw048';
/**
* A (Amnezia)WireGuard key: 32 bytes in base64, 43 characters and "=", the
* same as /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/ without its 1.7 ms
* compile on the WR3000P: the agent's watcher checks two keys per line of
* `awg show <ifname> dump` every second. This takes about 0.03 ms.
*/
export function valid_key(s) {
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
return type(s) == 'string' && length(s) == 44 && substr(s, 43) == '=' &&
index(KEY_LAST, substr(s, 42, 1)) >= 0 && ltrim(substr(s, 0, 42), B64) == '';
};
/** An IPv6 address in its usual spelling (no zone, no brackets). */
@@ -558,10 +744,25 @@ export function is_ip6(s) {
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
};
const LABEL = `${ASCII_ALNUM}-`;
/**
* Dot-separated labels of 1-63 letters, digits and dashes, none starting or
* ending with a dash: the same as
* /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/
* without its 10 ms compile on the WR3000P.
*/
function host_name(s) {
for (let l in split(s, '.'))
if (length(l) < 1 || length(l) > 63 || ltrim(l, LABEL) != '' ||
index(ASCII_ALNUM, substr(l, 0, 1)) < 0 || index(ASCII_ALNUM, substr(l, -1)) < 0)
return false;
return true;
}
/** A host name or an IP address, as a public address or the portal's name may be given. */
export function valid_host(s) {
return type(s) == 'string' && length(s) <= 253 &&
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
ip2int(s) != null || is_ip6(s));
return type(s) == 'string' && length(s) <= 253 && (host_name(s) || ip2int(s) != null || is_ip6(s));
};
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
@@ -573,11 +774,18 @@ export function valid_date(s) {
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
};
// Runs of other characters become one dash. Module constants: host_label and
// tunnel_name run for every device of a status or a portal answer.
const NOT_LC_ALNUM = /[^a-z0-9]+/g, NOT_ALNUM = /[^A-Za-z0-9]+/g;
// Names Windows keeps for devices: no file may be called that, whatever the case.
const WIN_DEVICES = [ 'con', 'prn', 'aux', 'nul', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9',
'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9' ];
/** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
export function slugify(s) {
let out = lc(translit(trim(`${s ?? ''}`)));
out = replace(out, /[^a-z0-9]+/g, '-');
out = replace(out, /^-+|-+$/g, '');
out = replace(out, NOT_LC_ALNUM, '-');
out = trim(out, '-');
return substr(out, 0, 32) || 'user';
};
@@ -586,8 +794,8 @@ export function slugify(s) {
* "telefon"): at most 40 characters, "device" when nothing is left.
*/
export function host_label(s) {
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
let l = replace(lc(translit(`${s ?? ''}`)), NOT_LC_ALNUM, '-');
l = rtrim(substr(trim(l, '-'), 0, 40), '-');
return l || 'device';
};
@@ -598,9 +806,9 @@ export function host_label(s) {
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
*/
export function tunnel_name(s) {
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
let l = replace(translit(`${s ?? ''}`), NOT_ALNUM, '-');
l = rtrim(substr(trim(l, '-'), 0, 15), '-');
return l && index(WIN_DEVICES, lc(l)) < 0 ? l : 'dawnline';
};
/* ---------- time ---------- */
@@ -660,9 +868,21 @@ export function now() {
return time();
};
const IFACE = `${ASCII_ALNUM}_.@-`;
/**
* A netifd interface name (network.interface.<name>, a person's home network):
* 1-32 letters, digits and _ . @ -, the same as /^[A-Za-z0-9_.@-]{1,32}$/
* without its 3 ms compile on the WR3000P (iface_status runs several times for
* the Overview's status, and in the agent's minute checks).
*/
export function valid_iface(s) {
return type(s) == 'string' && length(s) >= 1 && length(s) <= 32 && ltrim(s, IFACE) == '';
};
/** netifd's view of an interface (ubus network.interface.<name> status), or null. */
export function iface_status(ifname) {
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/))
if (!valid_iface(ifname))
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)
@@ -58,6 +58,7 @@ export function device_view(m, d, usage, dmp) {
m._reconnect ??= awg.reconnects();
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
let p = m.people[d.person];
let srv = m.servers[p?.server];
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
let label = '';
if (m.settings.hostnames && p) {
@@ -65,6 +66,7 @@ export function device_view(m, d, usage, dmp) {
m._labels[p.id] ??= core.device_labels(m, p);
label = m._labels[p.id][d.id] ?? 'device';
}
let online = hs > 0 && live.online(dmp, d.id, peer);
let v = {
id: d.id,
name: d.name,
@@ -73,7 +75,7 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled,
created: d.created,
created_by: d.created_by,
online: hs > 0 && live.online(dmp, d.id, peer),
online,
handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer,
@@ -84,6 +86,21 @@ export function device_view(m, d, usage, dmp) {
browser_key: d.private_key == '',
// Its configuration changed since it was last shown or downloaded.
config_stale: config_stale(m, d),
// How it connects: its own local network outside the tunnel, its own MTU
// and keep-alive (0 / null: the server's) and what its configuration carries.
lan_bypass: d.lan_bypass,
mtu: d.mtu,
keepalive: d.keepalive,
mtu_used: srv ? core.device_mtu(srv, d) : null,
keepalive_used: srv ? core.device_keepalive(srv, d) : null,
// Its link failing in a named way, as the agent's watcher shows it
// (dawnline.link): { state, since }, or null.
link: dmp.link?.[d.id] ?? null,
// What its link does right now, for the set-up sheet (dawnline.link
// setup_state): { state: 'trying' | 'flowing' | 'nodata', since }, or null.
// Without the agent nobody tells data from a bare handshake: a session
// that lives counts as data flowing, so the sheet still sees it arrive.
setup: dmp.setup != null ? (dmp.setup[d.id] ?? null) : online ? { state: 'flowing', since: hs } : null,
};
return v;
};
@@ -44,7 +44,23 @@ function restart_services() {
function probes(m) {
let out = [];
// The tunnels check themselves: AmneziaWG (packages, kernel module, netifd) and each server's interface.
push(out, ...awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) }));
let tunnels = awg.probes(m, { udp_listening: health.udp_listening, reapply: () => apply.apply(), owner: (ifn) => netifd.owner(ifn) });
push(out, ...tunnels);
// A tunnel's interface edited outside Dawnline (LuCI, uci) keeps that until
// the next apply: set up again with Dawnline's settings. Only while
// AmneziaWG itself works (its target comes first, and is fixed first).
if (filter(tunnels, (p) => p.id == 'awg')[0]?.ok)
for (let id, diff in netifd.drift(m)) {
let srv = m.servers[id];
push(out, {
id: `cfg_${id}`, src: 'awg', name: `${srv.name} · interface settings`, who: srv.name, ok: !length(diff),
problem: sprintf(L_('interface %s was changed outside Dawnline'), srv.ifname),
back: sprintf(L_("interface %s has Dawnline's settings again"), srv.ifname),
// Option names only: their values hold the server's private key.
detail: () => sprintf(L_('Changed: %s.'), join(', ', diff)),
repair: { what: L_('setting it up again'), run: () => apply.apply() },
});
}
if (length(m.servers))
push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: L_('Access rules'), ok: nft.present(),
@@ -184,6 +200,14 @@ function names() {
};
}
/** A target's chip name in the language of the call: names(), a server's interface settings, else as stored. */
function chip_name(m, n, id, stored) {
if (n[id])
return n[id];
let srv = substr(id, 0, 4) == 'cfg_' ? m.servers[substr(id, 4)] : null;
return srv ? sprintf(_('%s · interface settings'), srv.name) : stored;
}
/**
* For the Health page: the watchdog's state and the newest log entries. Target
* and repair names in the language of the call; the log as it was written.
@@ -195,11 +219,11 @@ export function view(m) {
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
let targets = [ { id: 'agent', name: n.agent, ok: beat > 0 && time() - beat < 180, tries: 0 } ];
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
push(targets, { id, name: n[id] ?? x.name, ok: !!x.ok, tries: x.tries ?? 0 });
push(targets, { id, name: chip_name(m, n, id, x.name), ok: !!x.ok, tries: x.tries ?? 0 });
return {
watchdog: {
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: n[r.id] ?? r.name })),
targets, repairs: map(st.repairs ?? [], (r) => ({ ...r, name: chip_name(m, n, r.id, r.name) })),
},
log: slog_read(200),
};
+4 -3
View File
@@ -7,7 +7,7 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
- `util`, `schema` (validation) → `core` (model, allocation) → `store` (the only writer of `/etc/config/dawnline`) → domain modules (`net`, `nft`, `fw`, `netifd`, `awg`, `loop`, `resolver`, `live`, `health`, `backup`, …) → `apply` (reconciliation) → entry points (`rpc/*`, `portal`, the `dawnline` CLI, the agent, the updater).
- Read models for the UI live in `view`; RPC modules translate arguments and call down, they hold no business logic.
- The updater is a thin dispatcher over `upd_app` / `upd_awg` / `upd_pkgs`, with GitHub in `github`, the package manager in `pkg`, policy/locks/history in `updates`.
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.ONLINE_WINDOW`): traffic silence is no signal, a phone asleep is silent too.
- Live state: the agent's watcher owns who is online (`live.PRESENCE`); readers ask `live.online()`, never re-derive it from handshake ages. Online means the WireGuard session lives (`live.online_window()`: 190 s, longer for a device with a long keep-alive): traffic silence is no signal, a phone asleep is silent too. A device's link trouble (trying, shared, dropped, unstable) is the watcher's too (`dawnline.link`, `live.LINK`).
## ucode
@@ -21,9 +21,10 @@ Read with `code-standards.md`. Everything here runs on a small router (2 × Cort
## Cost on the router
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action.
- **The portal is CGI:** every request starts ucode and compiles the module graph, about 140 ms of CPU before any work (a full `state` answer about 180 ms). No periodic polling from the portal; one request per user action. A person's answers read only their server's tunnel (`live.dump(m, sid)`: one `awg` process, however many servers).
- **rpcd keeps the admin backend loaded:** LuCI RPC calls are cheap, so the admin UI may poll small methods often (`rev`), and the heavy ones (`status`) only on change or rarely.
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show all dump` (about 4 ms with process start), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
- **Code on the agent's 1-second watcher stays in the low milliseconds:** one `awg show <ifname> dump` per Dawnline tunnel, never `all` (another AmneziaWG interface's peers are not Dawnline's; about 4 ms with process start, 1 ms to parse), the model cached by the config file's mtime/inode (`core.load()` is about 4 ms), files written only when something changed. Slow work (geo lookups, apply) runs only on a transition.
- **A regex literal is compiled every time it runs:** ucode calls regcomp for `/…/` each time the expression is evaluated, and musl's regcomp grows with the pattern. Bounded repeats are copied out (`{42}` about 1.7 ms on the WR3000P, `[A-Za-z0-9_.@-]{1,32}` 3 ms, two `{0,61}` 10 ms), alternations and classes add up (`/^(PrivateKey|Jc|Jmin|Jmax) /` 0.11 ms, `/^[0-9]+$/` 0.02 ms); matching a compiled regex takes 0.01–0.1 ms. In a loop or on a hot path, hoist the regex into a module `const` (compiled once, when the module loads — every portal request pays that too) or check with `length`/`substr`/`ltrim` (`util.valid_key`, `valid_host`, `valid_iface`).
- Measure before and after on the router (a loop of 20–200 calls, `/proc/self/stat` CPU ticks, system busy from `/proc/stat`) when adding anything periodic.
## Checks
+2 -2
View File
@@ -1,6 +1,6 @@
# Frontend (TypeScript: admin UI and portal)
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`).
Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18n.md` (every visible string goes through `_()`). Portal work starts with `DESIGN.md` (its tokens, components and motion).
## Code
@@ -16,4 +16,4 @@ Read with `code-standards.md` and, for anything visible, `ui-design.md` and `i18
## Checks
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm run i18n:check`, `npm test`, `npm run build`; the rebuilt bundles under `package/` and the catalogs are committed (CI fails otherwise).
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm run lint`, `npm run knip`, `npm run i18n:check`, `npm test`, `npm run build`; the catalogs are committed, the bundles under `package/` are git-ignored (CI builds them before packaging).
+1
View File
@@ -63,6 +63,7 @@ Write like a careful Russian product (Telegram, Яндекс), not a word-for-wo
| home network | домашняя сеть |
| internet | интернет |
| home network + internet | домашняя сеть и интернет |
| LAN Bypass (a device's option) | обход локальной сети («Обход локальной сети») |
| portal, personal link, personal page | портал, личная ссылка, личная страница |
| invite (card) | приглашение (карточка приглашения) |
| disguise; Off / Balanced / Maximum | маскировка; Выкл. / Сбалансированная / Максимальная |
+2
View File
@@ -2,6 +2,8 @@
The bar is a modern product UI (Linear / Vercel / Raycast level), not a "native" LuCI form. A plain label + input row, a bare radio list, three columns of check marks or a text dump is a first draft, never the result.
**The portal has its own design system, `DESIGN.md`** (repo root): read it before any portal work, mocks included. Build from its tokens, components and spring tokens, follow its Do's and Don'ts, and update it in the same change when the portal's look or motion changes. The admin follows this file and the LuCI theme.
## Approach
- **Mock first.** Any visible change beyond a one-line fix: show a mockup (2–4 genuinely different options when the direction is open) with a recommendation, then build the chosen one. Do not start coding a layout the user has not seen.
+5
View File
@@ -17,6 +17,11 @@ APK_SDK="${APK_SDK:-itdoginfo/openwrt-sdk-apk:25.12.3}"
grep -q "^export const VERSION = '$VERSION';" "$APP/root/usr/share/ucode/dawnline/util.uc" || { echo "util.uc VERSION != $VERSION" >&2; exit 1; }
grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; }
# The web bundles are not committed: web/ builds them (npm run build).
for f in htdocs/luci-static/resources/dawnline/app.js root/usr/share/dawnline/portal/assets/portal.js root/usr/share/dawnline/portal/assets/portal.css; do
[ -f "$APP/$f" ] || { echo "$APP/$f is missing: run 'npm run build' in web/" >&2; exit 1; }
done
mkdir -p "$OUT"
build() {
local type="$1" sdk="$2" tag="dawnline-build:$1"
+4
View File
@@ -18,6 +18,10 @@ grep -q "PKG_VERSION:=$VERSION\$" "$APP/Makefile" || { echo "Makefile PKG_VERSIO
grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/package.json version != $VERSION" >&2; exit 1; }
[ "${SKIP_WEB:-0}" = 1 ] || (cd "$ROOT/web" && npm run --silent ci)
# With SKIP_WEB=1 the bundles come from an earlier build (they are not committed).
for f in htdocs/luci-static/resources/dawnline/app.js root/usr/share/dawnline/portal/assets/portal.js root/usr/share/dawnline/portal/assets/portal.css; do
[ -f "$APP/$f" ] || { echo "$APP/$f is missing: run 'npm run build' in web/" >&2; exit 1; }
done
mkdir -p "$STAGE/www" "$OUT"
cp -R "$APP/root/." "$STAGE/"
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env node
// Capture the raw README screenshots of the personal portal into
// docs/screenshots/raw/ (2x PNG): the page (portal.png) and the three steps of
// adding a phone in front of it (portal-add-1..3.png: Add a device, the set-up
// sheet waiting, the phone connected), each sheet alone on a transparent page.
// The Russian ones take a -ru suffix. scripts/frame-screenshots.py then frames
// them for the README.
//
// The portal is its demo build (web/dist/demo, `npm run build:demo`, built
// first unless --no-build): the real portal over a router that lives in the
// page, so no one's real page is shown and adding a device adds none. It is
// opened as https://vpn.example.com/<code> and every file is answered from the
// build over the DevTools protocol (scripts/cdp.mjs), so its personal link
// reads like one. The cast is made up here: the demo's own three devices (the
// ones its router keeps, so adding one works) under other names, three more
// shown beside them, and the person's and the server's names.
//
// scripts/capture-portal.mjs [--lang en,ru] [--no-build]
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, extname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { die, launch, sleep } from './cdp.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const WEB = join(ROOT, 'web');
const DEMO = join(WEB, 'dist', 'demo');
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
const SCALE = 2;
/** The page's width, as the README shot always had it. */
const WIDTH = 1320;
/** Around a sheet in its capture: left, top, right, bottom (frame-screenshots.py FLOW_MARGIN). */
const MARGIN = [56, 40, 56, 72];
const ORIGIN = 'https://vpn.example.com';
/** The demo's personal link (web/src/portal/demo/index.html, data-base). */
const CODE = 'kelino-sarupa-motive';
const NAMES = { person: 'Aemeath', server: 'Ames Gateway' };
/** The device this page is open on (its card says "This device"). */
const HERE = 'MacBook Air';
/** The phone added in the steps. */
const NEW = 'Pixel 9';
const SLOTS = 8;
const args = { langs: ['en', 'ru'], build: true };
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
if (a === '--lang') args.langs = (process.argv[++i] ?? die('--lang needs a value')).split(',');
else if (a === '--no-build') args.build = false;
else die(`unknown argument ${a}`);
}
const DAY = 86400;
const now = () => Math.floor(Date.now() / 1000);
/**
* What the demo's router keeps (its DemoDb, in localStorage before the page loads): three devices, so one more
* fits its limit of four and the steps add it for real.
*/
function demoDb(t) {
const dev = (id, name, kind, n, gb, hs, days) => ({
id,
name,
kind,
n,
gb,
hs,
connectAt: 0,
created: t - days * DAY,
by: 'admin',
stale: false,
});
return {
scenario: 'normal',
devs: [
dev('d_mac', HERE, 'computer', 2, 5.4, t - 20, 60),
dev('d_iph', 'iPhone 16', 'phone', 3, 2.3, t - 40, 58),
dev('d_gal', 'Galaxy S24', 'phone', 4, 0.66, t - 26 * 3600, 30),
],
next: 5,
};
}
/**
* The page's side, before it loads: the language, the router's devices, the demo's own chrome hidden, and every
* answer of its router touched on the way to the page (the names, this device, the slots, the devices shown
* beside the ones it keeps).
*/
const prelude = (lang, db) => `(() => {
try {
localStorage.setItem('dl.lang', ${JSON.stringify(lang)});
localStorage.setItem('dawnline-demo', ${JSON.stringify(JSON.stringify(db))});
} catch {}
const NAMES = ${JSON.stringify(NAMES)}, HERE = ${JSON.stringify(HERE)}, SLOTS = ${SLOTS};
const extra = (devs, t) => {
const like = (d, o) => ({ ...d, link: null, setup: null, online: false, config_stale: false, created_by: 'admin', ...o });
const mac = devs.find((d) => d.name === HERE) ?? devs[0];
const none = { handshake: 0, endpoint: '', month: [0, 0], total: [0, 0], spark: mac.spark.map(() => [0, 0]) };
const scale = (p, f) => p.map((v) => Math.round(v * f));
return [
like(mac, { id: 'x_tv', name: 'Living room TV', kind: 'other', address: '10.8.0.6', handshake: t - 3 * 3600,
config_stale: true, month: scale(mac.month, 1.13), total: scale(mac.total, 1.4),
spark: mac.spark.map((p) => scale(p, 1.1)), created: t - 45 * 86400 }),
like(mac, { id: 'x_ipad', name: 'iPad', kind: 'tablet', address: '10.8.0.7', created: t - 2 * 86400, ...none }),
like(mac, { id: 'x_rtr', name: 'Cottage router', kind: 'router', address: '10.8.0.8', created: t - 86400, ...none }),
];
};
const touch = (st) => {
if (!st?.person) return;
const own = st.person.devices;
st.person.name = NAMES.person;
if (st.server) st.server.name = NAMES.server;
st.person.devices = [...own, ...extra(own, st.now)];
st.person.device_limit = SLOTS;
st.can_add = st.person.devices.length < SLOTS;
st.here = own.find((d) => d.name === HERE)?.id ?? null;
};
let inner = window.fetch;
Object.defineProperty(window, 'fetch', {
configurable: true,
get: () => inner,
// The demo's router takes fetch over (demo/serve.ts): its answers pass through here.
set: (f) => {
inner = async (...a) => {
const r = await f(...a);
if (!String(a[0] instanceof Request ? a[0].url : a[0]).includes('/api/')) return r;
let j;
try { j = await r.clone().json(); } catch { return r; }
touch(j?.person ? j : j?.state);
return new Response(JSON.stringify(j), { status: r.status, headers: { 'content-type': 'application/json' } });
};
},
});
addEventListener('DOMContentLoaded', () => {
const s = document.createElement('style');
// The demo's chip, GitHub knob and set-up state switch go, and the path takes the row again, as on a router's
// page.
s.textContent = '.dm-chip, .dm-gh, .dm-way { display: none !important; } .cr-path { flex: 1 !important; }';
document.head.append(s);
});
})()`;
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' };
/** Answer the page's requests from the demo build: its page for the personal link, its files by name. */
async function serve(page) {
page.on('Fetch.requestPaused', async (e) => {
const path = new URL(e.request.url).pathname;
const file = path === `/${CODE}` || path === '/' ? 'index.html' : path.slice(1);
let body;
try {
body = readFileSync(join(DEMO, file));
} catch {
await page.send('Fetch.fulfillRequest', { requestId: e.requestId, responseCode: 404, body: '' }).catch(() => {});
return;
}
await page.send('Fetch.fulfillRequest', {
requestId: e.requestId,
responseCode: 200,
responseHeaders: [{ name: 'Content-Type', value: TYPES[extname(file)] ?? 'application/octet-stream' }],
body: body.toString('base64'),
});
});
await page.send('Fetch.enable', { patterns: [{ urlPattern: `${ORIGIN}/*`, requestStage: 'Request' }] });
}
async function shoot(page, file, clip) {
const { data } = await page.send('Page.captureScreenshot', {
format: 'png',
clip: { ...clip, scale: 1 },
captureBeyondViewport: true,
});
writeFileSync(join(RAW, file), Buffer.from(data, 'base64'));
console.log(`${file}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
}
// The page's content: everything on screen but full-width or full-height wrappers, 36px around it (as the
// README shot always was; what waits off screen, as a field's measuring copy does, is no content).
const PAGE_CLIP = `(() => {
let l = innerWidth, r = 0, b = 0;
for (const e of document.querySelectorAll('#app *')) {
const x = e.getBoundingClientRect();
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
if (x.left < 0 || x.right > innerWidth) continue;
l = Math.min(l, x.left);
r = Math.max(r, x.right);
b = Math.max(b, x.bottom);
}
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
})()`;
// The open sheet alone: the page and the scrim out of sight on a transparent page, MARGIN around the sheet.
const SHEET_CLIP = `(() => {
const r = document.querySelector('.sheet-root.open .sheet').getBoundingClientRect();
const [l, t, rr, b] = ${JSON.stringify(MARGIN)};
return { x: r.left - l, y: r.top - t, width: r.width + l + rr, height: r.height + t + b };
})()`;
const ALONE = `(() => {
const s = document.createElement('style');
s.id = 'alone';
s.textContent = 'html, body { background: transparent !important; } #app { visibility: hidden !important; } .scrim { display: none !important; }';
document.head.append(s);
})()`;
async function capture(lang) {
const suffix = lang === 'en' ? '' : `-${lang}`;
const b = await launch([`--lang=${lang}`]);
const { page, evaluate, go, waitSel } = b;
try {
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
await page.send('Emulation.setDeviceMetricsOverride', { width: WIDTH, height: 1400, deviceScaleFactor: SCALE, mobile: false });
// Where the page paints nothing (a sheet alone), the capture is transparent.
await page.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
await serve(page);
await page.send('Page.addScriptToEvaluateOnNewDocument', { source: prelude(lang, demoDb(now())) });
await go(`${ORIGIN}/${CODE}`);
await waitSel('.dev[data-id]');
await sleep(2500);
await shoot(page, `portal${suffix}.png`, await evaluate(PAGE_CLIP));
// 1: Add a device, a phone, its name typed in.
await evaluate(`document.querySelector('.dev.add').click()`);
await waitSel('.sheet-root.open .kinds');
await sleep(900);
await evaluate(`document.querySelectorAll('.sheet-root.open .kind')[1].click()`);
await sleep(500);
await evaluate(`(() => { const i = document.querySelector('.sheet-root.open .field input'); i.focus(); i.select(); })()`);
await page.send('Input.insertText', { text: NEW });
await evaluate(`document.activeElement.blur()`);
await sleep(900);
await evaluate(ALONE);
await shoot(page, `portal-add-1${suffix}.png`, await evaluate(SHEET_CLIP));
await evaluate(`document.getElementById('alone').remove()`);
// 2: the set-up sheet, waiting for the phone, its link open as a code for the phone's camera (the page
// opens on the app's row, whose code a key makes too dense to read at this size).
await evaluate(`document.querySelector('.sheet-root.open .field .go').click()`);
await waitSel('.sheet-root.open .way');
await sleep(1200);
await evaluate(`document.querySelector('.sheet-root.open .acc-row:not(.open) .acc-head').click()`);
await sleep(1500);
await evaluate(ALONE);
await shoot(page, `portal-add-2${suffix}.png`, await evaluate(SHEET_CLIP));
await evaluate(`document.getElementById('alone').remove()`);
// 3: connected (the demo's phone does within 6-9 s), what was under the way folded away.
await waitSel('.sheet-root.open .way.done', 15000);
await sleep(1150);
await evaluate(ALONE);
await shoot(page, `portal-add-3${suffix}.png`, await evaluate(SHEET_CLIP));
page.close();
} finally {
await b.close();
}
}
async function main() {
if (args.build) execFileSync('npm', ['run', '--silent', 'build:demo'], { cwd: WEB, stdio: 'inherit' });
for (const lang of args.langs) await capture(lang);
}
main().catch((e) => die(e.message));
+44 -143
View File
@@ -1,29 +1,33 @@
#!/usr/bin/env node
// Capture the raw README screenshots from a live router into
// Capture the raw README screenshots of the admin pages from a live router into
// docs/screenshots/raw/<name>.png (2x PNG); scripts/frame-screenshots.py then
// puts them into a browser window for the README.
// frames them for the README. The portal's come from its demo instead
// (scripts/capture-portal.mjs): no one's real page, and adding a device there adds none.
//
// Drives a headless Chromium (BROWSER=/path/to/chrome, default: Brave or Chrome
// on macOS) over the DevTools protocol, no npm packages. Signs in to LuCI with
// on macOS) over the DevTools protocol (scripts/cdp.mjs). Signs in to LuCI with
// the password from LUCI_PASSWORD or asked on the terminal; the session lives
// only in a throwaway profile (LUCI_USER picks another user than root). Nothing on the router is changed.
//
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
// [--mask real=shown ...] [--name real=shown ...]
// [--only overview,people] [--demo]
// [--only overview,people] [--demo] [--lang ru]
//
// --lang asks LuCI for the pages in that language (its catalog, po/<lang>/dawnline.po;
// the router's LuCI language left on auto) and names the captures <name>-<lang>.png
// for that README (README_ru.md); English (the default) keeps <name>.png.
// --mask replaces text on every page before the capture (a domain, a name);
// --name does the same for a person's name in any case, and for their initials.
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
// the router's answers are rewritten in the headless browser on their way to the page.
import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { execFileSync } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline';
import { die, launch, sleep } from './cdp.mjs';
import { demoRpc } from './screenshot-demo.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -37,6 +41,7 @@ const args = {
names: [],
only: [],
demo: false,
lang: 'en',
};
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
@@ -47,8 +52,26 @@ for (let i = 2; i < process.argv.length; i++) {
else if (a === '--name') args.names.push(v().split('=', 2));
else if (a === '--only') args.only = v().split(',');
else if (a === '--demo') args.demo = true;
else if (a === '--lang') args.lang = v();
else die(`unknown argument ${a}`);
}
const SUFFIX = args.lang === 'en' ? '' : `-${args.lang}`;
/** The admin's catalog for --lang: msgid -> msgstr, the entries without a context (English: none). */
const CATALOG = (() => {
const out = new Map();
if (args.lang === 'en') return out;
let po;
try {
po = readFileSync(join(ROOT, 'package', 'luci-app-dawnline', 'po', args.lang, 'dawnline.po'), 'utf8');
} catch {
die(`no admin catalog for --lang ${args.lang}`);
}
for (const m of po.matchAll(/^(msgctxt .*\n)?msgid "(.*)"\nmsgstr "(.*)"$/gm)) if (!m[1] && m[3]) out.set(m[2], m[3]);
return out;
})();
/** A button's words as the page shows them in --lang (the pages are clicked by what they say). */
const tr = (id) => CATALOG.get(id) ?? id;
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
/** As shared/format initials(): first letters of the first and last word, or the first two of one word. */
@@ -60,12 +83,7 @@ for (const [real, shown] of args.names)
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
function die(msg) {
console.error(msg);
process.exit(1);
}
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
const LUCI = `${args.router}/cgi-bin/luci/admin/services/dawnline`;
const USER = process.env.LUCI_USER || 'root';
/*
@@ -93,7 +111,7 @@ const SHOTS = [
ready: '.dl-srvov .dl-panel.flush .maplibregl-canvas',
// The map shows the last 30 days, not only who is online now.
prep: `(() => {
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === '30 days');
const b = [...document.querySelectorAll('.dl-srvov .dl-panel.flush button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('30 days'))});
b?.click();
})()`,
settle: 6000,
@@ -113,7 +131,7 @@ const SHOTS = [
ready: '.dl-grid-person .dl-row',
// Where they connected from, on the map.
prep: `(() => {
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === ${JSON.stringify(tr('Show map'))});
b?.click();
})()`,
settle: 6000,
@@ -131,25 +149,6 @@ const SHOTS = [
return { x: c.x, y: 0, width: c.w, height: cut };
})()`,
},
{
name: 'portal',
url: (s) => s.portal,
width: 1320,
ready: 'body',
settle: 3000,
// The content: everything but full-width or full-height wrappers, 36px around it.
clip: `(() => {
let l = innerWidth, r = 0, b = 0;
for (const e of document.body.querySelectorAll('*')) {
const x = e.getBoundingClientRect();
if (!x.width || !x.height || x.width > innerWidth - 40 || x.height > innerHeight - 40) continue;
l = Math.min(l, x.left);
r = Math.max(r, x.right);
b = Math.max(b, x.bottom);
}
return { x: l - 36, y: 0, width: r - l + 72, height: b + 40 };
})()`,
},
];
const MASK = `((pairs, inits) => {
@@ -198,87 +197,20 @@ async function password() {
}
}
function findBrowser() {
const c = [
process.env.BROWSER,
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/chromium',
'/usr/bin/google-chrome',
];
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
}
/** A page over the DevTools protocol: send(method, params) and waitFor(event). */
async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = fail;
});
let id = 0;
const pending = new Map();
const waiters = [];
const listeners = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) {
const { ok, fail } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) {
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params);
}
}
};
const send = (method, params = {}) =>
new Promise((ok, fail) => {
pending.set(++id, { ok, fail });
ws.send(JSON.stringify({ id, method, params }));
});
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
const on = (method, fn) => listeners.push({ method, fn });
return { send, waitFor, on, close: () => ws.close() };
}
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
async function main() {
const pass = await password();
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
const chrome = spawn(
findBrowser(),
[
'--headless=new',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
// The router's certificate is usually for its public name, not router.lan.
'--ignore-certificate-errors',
'--hide-scrollbars',
'--no-first-run',
'--no-default-browser-check',
// MapLibre needs WebGL; headless gets it from SwiftShader.
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
'about:blank',
],
{ stdio: 'ignore' },
);
const b = await launch(['--ignore-certificate-errors', `--lang=${args.lang}`]);
const { page, evaluate, go, waitSel } = b;
try {
const portFile = join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
const port = readFileSync(portFile, 'utf8').split('\n')[0];
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable');
// LuCI on auto speaks the browser's language: this one, whatever this computer's is.
await page.send('Network.enable');
await page.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': args.lang } });
await page.send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
});
// The person shown on the Person page; known once People has loaded (or from --person).
const s = { person: args.person, portal: '' };
const s = { person: args.person };
if (args.demo) {
page.on('Fetch.requestPaused', async (e) => {
try {
@@ -302,27 +234,6 @@ async function main() {
});
}
const evaluate = async (expression) => {
const r = await page.send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
});
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
const go = async (url) => {
const loaded = page.waitFor('Page.loadEventFired');
await page.send('Page.navigate', { url });
await loaded;
};
const waitSel = async (sel, ms = 20000) => {
for (let t = 0; t < ms; t += 250) {
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
await sleep(250);
}
throw new Error(`timed out waiting for ${sel}`);
};
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
const viewport = (width, height = 2600) =>
page.send('Emulation.setDeviceMetricsOverride', {
@@ -350,24 +261,16 @@ async function main() {
);
}
// The person to show (the first one on People unless --person) and their personal link.
// The person to show: the first one on People unless --person.
await go(`${LUCI}/server?section=people`);
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
if (!s.person)
s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
.then((r) => r.link ?? r.links?.[0] ?? '')`);
for (const shot of SHOTS) {
if (args.only.length && !args.only.includes(shot.name)) continue;
const url = shot.url(s);
if (!url) {
console.log(`skip ${shot.name}: no URL (the portal is off?)`);
continue;
}
await viewport(shot.width);
await go(url);
await go(shot.url(s));
await waitSel(shot.ready);
await sleep(2000);
if (shot.prep) await evaluate(shot.prep);
@@ -379,14 +282,12 @@ async function main() {
clip: { ...clip, scale: 1 },
captureBeyondViewport: true,
});
writeFileSync(join(RAW, `${shot.name}.png`), Buffer.from(data, 'base64'));
console.log(`${shot.name}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
writeFileSync(join(RAW, `${shot.name}${SUFFIX}.png`), Buffer.from(data, 'base64'));
console.log(`${shot.name}${SUFFIX}: ${Math.round(clip.width)}x${Math.round(clip.height)} (x${SCALE})`);
}
page.close();
} finally {
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });
await b.close();
}
}
+122
View File
@@ -0,0 +1,122 @@
// A headless Chromium driven over the DevTools protocol, no npm packages: what
// the README screenshot scripts share (capture-screenshots.mjs from a router,
// capture-portal.mjs from the portal demo). BROWSER=/path/to/chrome picks the
// browser (default: Brave or Chrome on macOS); its profile is a throwaway one.
import { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
export const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
export function die(msg) {
console.error(msg);
process.exit(1);
}
export function findBrowser() {
const c = [
process.env.BROWSER,
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/chromium',
'/usr/bin/google-chrome',
];
return c.find((b) => b && existsSync(b)) ?? die('No Chromium-based browser found; set BROWSER=/path/to/chrome');
}
/** A page over the DevTools protocol: send(method, params), waitFor(event) and on(event, fn). */
export async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((ok, fail) => {
ws.onopen = ok;
ws.onerror = fail;
});
let id = 0;
const pending = new Map();
const waiters = [];
const listeners = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) {
const { ok, fail } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) {
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params);
}
}
};
const send = (method, params = {}) =>
new Promise((ok, fail) => {
pending.set(++id, { ok, fail });
ws.send(JSON.stringify({ id, method, params }));
});
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
const on = (method, fn) => listeners.push({ method, fn });
return { send, waitFor, on, close: () => ws.close() };
}
/**
* Start the browser headless on a fresh profile and connect to its first page. `flags` go on its command line
* (a language, certificate errors). Returns the page, its helpers, and close() that ends the browser and removes
* the profile.
*/
export async function launch(flags = []) {
const profile = mkdtempSync(join(tmpdir(), 'dawnline-shots-'));
const chrome = spawn(
findBrowser(),
[
'--headless=new',
'--remote-debugging-port=0',
`--user-data-dir=${profile}`,
'--hide-scrollbars',
'--no-first-run',
'--no-default-browser-check',
// MapLibre needs WebGL; headless gets it from SwiftShader.
'--use-angle=swiftshader',
'--enable-unsafe-swiftshader',
...flags,
'about:blank',
],
{ stdio: 'ignore' },
);
const close = async () => {
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });
};
try {
const portFile = join(profile, 'DevToolsActivePort');
for (let i = 0; i < 100 && !existsSync(portFile); i++) await sleep(100);
const port = readFileSync(portFile, 'utf8').split('\n')[0];
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable');
const evaluate = async (expression) => {
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
return r.result.value;
};
const go = async (url) => {
const loaded = page.waitFor('Page.loadEventFired');
await page.send('Page.navigate', { url });
await loaded;
};
const waitSel = async (sel, ms = 20000) => {
for (let t = 0; t < ms; t += 250) {
if (await evaluate(`!!document.querySelector(${JSON.stringify(sel)})`)) return;
await sleep(250);
}
throw new Error(`timed out waiting for ${sel}`);
};
return { page, evaluate, go, waitSel, close };
} catch (e) {
await close();
throw e;
}
}
+8 -9
View File
@@ -2,7 +2,8 @@
"""Frame the README screenshots the way the portal draws its own surfaces.
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
per CSS pixel (scripts/capture-screenshots.mjs takes the admin's from a router,
scripts/capture-portal.mjs the portal's from its demo); the framed images
are written to docs/screenshots/<name>.png at the same scale. Each page sits on
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
@@ -22,14 +23,13 @@ import tempfile
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
OUT = os.path.join(ROOT, 'docs', 'screenshots')
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
'geist-latin-wght-normal.woff2')
SHOTS = ['overview', 'people', 'person', 'portal']
# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
# adding a device there would add one.
SHOTS = ['overview', 'people', 'person', 'portal', 'overview-ru', 'people-ru', 'person-ru', 'portal-ru']
# name -> the steps in front of its page, in order (raw captures). The portal's come from its demo
# (scripts/capture-portal.mjs), not a router: adding a device there would add one. -ru: README_ru's.
FLOWS = {
'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
'portal-ru': ['portal-add-1-ru', 'portal-add-2-ru', 'portal-add-3-ru'],
}
PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
@@ -45,7 +45,6 @@ CANDIDATES = [
]
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
@font-face{{font-family:Geist;src:url('file://{font}') format('woff2');font-weight:100 900}}
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
body{{position:relative;background:#080808}}
.panel{{position:absolute;left:{px}px;top:{py}px;width:{pw}px;height:{ph}px;
@@ -54,7 +53,7 @@ body{{position:relative;background:#080808}}
box-shadow:0 0 0 1px rgba(255,255,255,.04)}}
.sheet{{position:absolute;display:block;filter:drop-shadow(0 24px 48px rgba(0,0,0,.6))}}
.n{{position:absolute;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;
font:600 16px Geist,sans-serif;color:#ededed;background:#232323;
font:600 16px system-ui,-apple-system,sans-serif;color:#ededed;background:#232323;
box-shadow:0 0 0 1px rgba(255,255,255,.12),0 6px 16px rgba(0,0,0,.5)}}
</style></head><body><div class="panel"></div><img class="page" src="file://{src}">{steps}</body></html>"""
@@ -111,7 +110,7 @@ def main():
html = os.path.join(tmp, f'{name}.html')
with open(html, 'w', encoding='utf-8') as f:
f.write(TEMPLATE.format(w=w, h=h, x=x, y=y, iw=iw, ih=ih, px=x - INSET, py=y - INSET, pw=iw + 2 * INSET,
ph=ih + 2 * INSET, src=src, font=FONT, steps=steps))
ph=ih + 2 * INSET, src=src, steps=steps))
out = os.path.join(OUT, f'{name}.png')
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
+8 -4
View File
@@ -41,9 +41,13 @@ def strip_comments(text):
return re.sub(r'//[^\n]*|/\*.*?\*/', '', text, flags=re.S)
def blank_comments(text):
"""Comments replaced by their newlines: line numbers stay, their text goes."""
return re.sub(r'//[^\n]*|/\*.*?\*/', lambda m: '\n' * m.group(0).count('\n'), text, flags=re.S)
def blank_comments_templates(text):
"""Comments and template literals replaced by their newlines, strings kept:
line numbers stay, and a `}` that starts a line of a template (nft rules)
ends no function. A template inside another one's `${…}` reads as code:
good enough for how Dawnline writes them."""
return re.sub(r"//[^\n]*|/\*.*?\*/|'(?:\\.|[^'\\\n])*'|\"(?:\\.|[^\"\\\n])*\"|`(?:\\.|[^`\\])*`",
lambda m: m.group(0) if m.group(0)[0] in '\'"' else '\n' * m.group(0).count('\n'), text, flags=re.S)
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
@@ -66,7 +70,7 @@ for f in files:
problem(f"{f}:{line}: {name}() is used before its definition")
# In a module an exported function is an expression statement: its closing
# brace needs a semicolon ("Expecting ';'" breaks the whole module).
lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
lines = blank_comments_templates(open(f, encoding='utf-8').read()).split('\n')
inside = None
for n, text in enumerate(lines, 1):
if inside is None and re.match(r'^export function \w+\(', text):
+1 -1
View File
@@ -63,7 +63,7 @@ Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk):
sh -c "\$(wget -qO- https://raw.githubusercontent.com/$REPO/main/install.sh)"
\`\`\`
Or update from LuCI → Network → Dawnline → Components.
Or update from LuCI → Services → Dawnline → Components.
EOF
if [ -n "$PREV" ]; then
printf '\n**Full Changelog**: https://github.com/%s/compare/%s...%s\n' "$REPO" "$PREV" "$TAG"
+36 -4
View File
@@ -129,16 +129,31 @@ const seen = (when, now) => {
}[k] ?? 0
);
};
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
/**
* A week of daily [rx, tx] that adds up to about a quarter of the month, today last (nothing before it was first
* seen), rx (from the device) about an eighth.
*/
const week = (gb, last, now) =>
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => {
const b = !gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7);
return [Math.round(b * 0.12), b - Math.round(b * 0.12)];
});
/**
* One second of the cast's traffic through a server (the k-th), [rx, tx] in bytes/s: a few devices streaming,
* their uploads small. The same for a second whichever call asks, so the live chart keeps its shape.
*/
const meterRate = (ts, k) => {
const wave = (a, b) => Math.sin(ts / a + k) * 0.45 + Math.sin(ts / b + 2 * k) * 0.25;
const noise = (((ts * 7919 + k * 104729) % 1000) / 1000 - 0.5) * 0.35;
return [Math.round(Math.max(0, 1.8e5 * (1 + wave(7, 17) + noise))), Math.round(Math.max(0, 1.6e6 * (1 + wave(9, 23) + noise)))];
};
let ipN = 10;
/** A documentation address (the capture swaps public addresses for these anyway). */
const ip = () => `203.0.113.${ipN++}`;
const where = (city) => `${city} · ${CITIES[city][4]}`;
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
const demo = { events: [], people: new Map(), days: [], now: 0 };
/** What the last status made of the router's ids, for the calls that come after it (events, usage, the meter). */
const demo = { events: [], people: new Map(), days: [], now: 0, servers: [] };
/**
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
@@ -255,6 +270,12 @@ function demoStatus(st, first) {
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
spark: week(gb, hs, now),
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
// As set up: nothing failing, its own link values the server's, its data flowing while online.
link: null,
setup: online ? { state: 'flowing', since: hs } : null,
lan_bypass: false,
mtu: 0,
keepalive: null,
};
});
for (const [name, ago, by] of c.added ?? []) {
@@ -313,6 +334,7 @@ function demoStatus(st, first) {
demo.events = events;
points.sort((a, b) => b.ts - a.ts);
demo.now = now;
demo.servers = (st.servers ?? []).map((x) => x.id);
demo.days = (st.series ?? []).map((x) => x.day);
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
@@ -384,6 +406,16 @@ export function demoRpc(request, response, first) {
},
],
};
// Speed now, live: the last two minutes of the cast's traffic, not the router's.
if (method === 'meter' && Array.isArray(data.points)) {
const ids = demo.servers.length ? demo.servers : [...new Set(data.points.flatMap((p) => Object.keys(p.servers ?? {})))];
const keep = data.keep > 1 ? data.keep : 120;
const since = +args?.since || 0;
const points = [];
for (let ts = data.now - keep + 1; ts <= data.now; ts++)
if (ts > since) points.push({ ts, servers: Object.fromEntries(ids.map((id, k) => [id, meterRate(ts, k)])) });
return { ...r, result: [r.result[0], { ...data, ts: data.now, points }] };
}
if (method === 'events' && Array.isArray(data.events)) {
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
return {
+67
View File
@@ -0,0 +1,67 @@
// dawnline.access: the Check access walk for a device that keeps its own
// local network out of the tunnel (lan_bypass), and the way its internet
// leaves, on a model and a network snapshot of the test's own (nothing read
// from the container).
import * as access from 'dawnline.access';
const KEY_TV = 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', KEY_PHONE = 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=';
/** Bob (Internet only) on a server that sends everyone direct: a TV with lan_bypass and a phone without. */
function model() {
return {
settings: { portal_enabled: false },
servers: {
home: { id: 'home', name: 'Home', ifname: 'awghome', subnet: '10.9.0.0/29', private_key: 'k', enabled: true, lan_like: false,
auto_wan: false, wan_device: 'eth1', auto_lan: false, lan_devices: [ 'br-lan' ], mesh: 'all', device_mesh: true, dns: [] },
},
people: { bob: { id: 'bob', name: 'Bob', server: 'home', access: 'internet', services: [], devices: [ 'tv', 'phone' ] } },
devices: {
tv: { id: 'tv', person: 'bob', name: 'TV', address: '10.9.0.2', public_key: KEY_TV, lan_bypass: true },
phone: { id: 'phone', person: 'bob', name: 'Phone', address: '10.9.0.3', public_key: KEY_PHONE, lan_bypass: false },
},
services: {},
circles: {},
};
}
const CTX = {
states: { bob: 'active' },
dmp: { peers: {}, windows: {} },
snap: {
devices: {
'br-lan': { nets: [ '192.168.1.0/24' ], zone: 'lan', addrs: [ '192.168.1.1/24' ] },
eth1: { nets: [ '203.0.113.0/24' ], zone: 'wan', addrs: [ '203.0.113.7/24' ] },
awghome: { nets: [ '10.9.0.0/29' ], addrs: [ '10.9.0.1/29' ] },
},
lan: 'br-lan',
wan: 'eth1',
},
};
function last(r) {
return r.steps[length(r.steps) - 1];
}
test('check: a device with its local network outside the tunnel', () => {
let m = model();
let r = access.check(m, 'tv', '192.168.1.20', CTX);
eq([ r.ok, last(r).ok, last(r).title ], [ false, false, "Its configuration doesn't send it to the router" ],
'a home address: on its own network, not blocked in the tunnel');
ok(index(last(r).detail, "the device's own network handles it") >= 0, 'says where it goes');
r = access.check(m, 'tv', '192.168.1.1:80', CTX);
eq(last(r).title, "Its configuration doesn't send it to the router", 'the router\'s LAN address is on its own network too');
r = access.check(m, 'tv', '10.9.0.1:53', CTX);
eq([ r.ok, r.steps[1].title ], [ true, '10.9.0.1 is this router: DNS is open to everyone' ], 'its DNS stays in the tunnel');
r = access.check(m, 'tv', '8.8.8.8', CTX);
eq([ r.ok, last(r).title, last(r).detail ], [ true, '8.8.8.8 is on the internet', 'It leaves through eth1.' ], 'the internet through the tunnel');
r = access.check(m, 'phone', '192.168.1.20', CTX);
eq([ r.ok, last(r).title ], [ false, '192.168.1.20 is at home (br-lan)' ], 'without it: into the tunnel, and blocked there');
});
test('check: the way out is the server\'s', () => {
let m = model();
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves through eth1.', 'direct');
m.servers.home.lan_like = true;
eq(last(access.check(m, 'phone', '8.8.8.8', CTX)).detail, 'It leaves like a home device would.', 'like a home device');
});
+466 -27
View File
@@ -1,8 +1,18 @@
// dawnline.awg: disguise presets against their own validation, the parser
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
// dawnline.awg: disguise presets against their own validation, the values
// AmneziaWG refuses (obf_unsafe, one case per rule), the parser of `awg show
// <ifname> dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1 and how
// each tunnel's read went (the stand-in awg in fixtures/bin prints the
// fixture put at AWG_DUMP), the devices a tunnel should hold, Reconnect, a
// device's configuration from the fixture model, what the server's interface
// and the read-only status get of it.
import { readfile, writefile, unlink } from 'fs';
import { cursor } from 'uci';
import { valid_key, cidr_any } from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as core from 'dawnline.core';
import * as backup from 'dawnline.backup';
import * as rpc_status from 'dawnline.rpc.status';
import * as nft from 'dawnline.nft';
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
let fixtures = sourcepath(0, true) + '/fixtures';
@@ -32,7 +42,8 @@ test('obf_preset balanced', () => {
test('obf_preset max', () => {
let o = awg.obf_preset('max');
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from awg genkey');
ok(valid_key(o.header_protection_key), 'a header protection key');
ok(o.header_protection_key != awg.obf_preset('max').header_protection_key, 'made for each server, without awg genkey');
ok(+o.jc >= 4 && +o.jc <= 6, 'jc');
ok(substr(o.i1, 0, 3) == '<r ', 'DNS-like first packet');
eq([ o.random_trailers, o.disable_cookies, o.content_padding_addition ], [ 'on', 'on', '10-100' ], '3.1 options');
@@ -44,55 +55,279 @@ test('obf_preset max', () => {
shapes[awg.obf_preset('max').i1] = true;
ok(length(keys(shapes)) > 1, 'signature packets differ between servers');
// The preset passes the server's own validation (jmin/jmax may be small: 0.5.2).
eq(awg.obf_errors(o), [], 'max is valid');
for (let i = 0; i < 25; i++)
eq(awg.obf_errors(awg.obf_preset('max')), [], 'max is valid');
});
test('obf_errors', () => {
test('obf_errors: Dawnline\'s own bounds on top of obf_unsafe', () => {
eq(awg.obf_errors({}), [], 'nothing set');
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-10)' ], 'jc range');
eq(awg.obf_errors(null), [], 'no values');
eq(awg.obf_errors({ jc: '11' }), [ 'Jc must be from 0 to 10.' ], 'jc range');
eq(awg.obf_errors({ jmin: '0', jmax: '0' }), [], 'zero junk sizes are allowed');
eq(awg.obf_errors({ jmin: '2000' }), [ 'jmin=2000 (0-1024)' ], 'jmin range');
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'jmin > jmax' ], 'order');
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 's1 + 56 = s2' ], 'the handshake size clash');
eq(awg.obf_errors({ s4: '33' }), [ 's4=33 (0-32)' ], 's4 range');
eq(awg.obf_errors({ jc: 'x' }), [ 'jc=x (0-10)' ], 'not a number');
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'h1-h4 must be distinct' ], 'duplicate headers');
eq(awg.obf_errors({ h1: '7-9', h2: 'abc' }), [ 'h2 must be a number or range' ], 'header ranges');
eq(awg.obf_errors({ jmin: '2000', jmax: '3000' }), [ 'Jmin must be from 0 to 1024.', 'Jmax must be from 0 to 1024.' ], 'junk sizes');
eq(awg.obf_errors({ s1: '5', s2: '61' }), [ 'S2 must not be S1 + 56: the handshake initiation and response would have the same size.' ],
'the handshake size clash');
eq(awg.obf_errors({ s4: '33' }), [ 'S4 must be from 0 to 32.' ], 's4 range');
// What AmneziaWG refuses comes first, said once.
eq(awg.obf_errors({ jc: 'x' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'not a number');
eq(awg.obf_errors({ jmin: '200', jmax: '100' }), [ 'Jmin must not be larger than Jmax.' ], 'order');
eq(awg.obf_errors({ h1: '7', h2: '7' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'duplicate headers');
eq(awg.obf_neutral({ jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }), true, 'off is neutral');
eq(awg.obf_neutral({ jc: '4', jmin: '64', jmax: '128' }), false, 'junk is not neutral');
});
// One case per rule of obf_unsafe: what an import, a restore or a hand edit must never hand to the kernel.
const HPK = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
const MAX = { s1: '12', s2: '12', s3: '12', s4: '12', header_protection_key: HPK };
test('obf_unsafe: what the presets and older servers hold passes', () => {
eq(awg.obf_unsafe(null), [], 'no values');
eq(awg.obf_unsafe(awg.obf_preset('off')), [], 'off');
for (let i = 0; i < 25; i++) {
eq(awg.obf_unsafe(awg.obf_preset('balanced')), [], 'balanced');
eq(awg.obf_unsafe(awg.obf_preset('max')), [], 'max');
}
// Values from before 0.8 and hand-tuned ones the kernel takes: none of Dawnline's own bounds here.
let old = { jc: '12', jmin: '50', jmax: '1400', s1: '100', s2: '156', h1: '1234567', h2: '2345678', h3: '3456789', h4: '4567890' };
eq(awg.obf_unsafe(old), [], 'older and hand-tuned values');
ok(length(awg.obf_errors(old)) > 0, 'which a new server would not get');
});
test('obf_unsafe: 16-bit numbers', () => {
eq(awg.obf_unsafe({ jc: '65535', s4: '0' }), [], 'the ends');
eq(awg.obf_unsafe({ jc: '65536' }), [ 'Jc must be a whole number from 0 to 65535.' ], 'too large');
eq(awg.obf_unsafe({ s3: '-1' }), [ 'S3 must be a whole number from 0 to 65535.' ], 'negative');
eq(awg.obf_unsafe({ jmax: '1e3' }), [ 'Jmax must be a whole number from 0 to 65535.' ], 'not digits');
});
test('obf_unsafe: Jmin not above Jmax', () => {
eq(awg.obf_unsafe({ jmin: '50', jmax: '50' }), [], 'equal');
eq(awg.obf_unsafe({ jmin: '51', jmax: '50' }), [ 'Jmin must not be larger than Jmax.' ], 'the kernel would write past its junk buffer');
eq(awg.obf_unsafe({ jmin: '51' }), [], 'Jmax not given');
});
test('obf_unsafe: header values are numbers or ranges', () => {
eq(awg.obf_unsafe({ h1: '100-200', h2: '300', h3: '4294967295', h4: '0' }), [], 'numbers and ranges');
eq(awg.obf_unsafe({ h1: '200-100' }), [ 'H1 must be a number or a range like 100-200, up to 4294967295.' ], 'reversed');
eq(awg.obf_unsafe({ h2: '4294967296' }), [ 'H2 must be a number or a range like 100-200, up to 4294967295.' ], 'past 32 bits');
eq(awg.obf_unsafe({ h3: '5-6-7' }), [ 'H3 must be a number or a range like 100-200, up to 4294967295.' ], 'two dashes');
eq(awg.obf_unsafe({ h4: 'abc' }), [ 'H4 must be a number or a range like 100-200, up to 4294967295.' ], 'not a number');
});
test('obf_unsafe: header values do not overlap', () => {
eq(awg.obf_unsafe({ h1: '10-20', h2: '20-30', h3: '40', h4: '50' }), [ 'H1 and H2 overlap: each packet type needs values of its own.' ], 'a shared end');
eq(awg.obf_unsafe({ h1: '10-20', h2: '30', h3: '15', h4: '50' }), [ 'H1 and H3 overlap: each packet type needs values of its own.' ], 'one inside a range');
// One not given keeps WireGuard's type: 1-4.
eq(awg.obf_unsafe({ h1: '1-10' }), [ 'H1 and H2 overlap: each packet type needs values of its own.', 'H1 and H3 overlap: each packet type needs values of its own.',
'H1 and H4 overlap: each packet type needs values of its own.' ], 'over the default types');
eq(awg.obf_unsafe({ h1: '5-10' }), [], 'clear of them');
});
test('obf_unsafe: header protection needs a key and 12-byte padding', () => {
eq(awg.obf_unsafe(MAX), [], 'the 3.1 values');
eq(awg.obf_unsafe({ ...MAX, header_protection_key: 'abc' }), [ 'The header protection key is not a key.' ], 'not a key');
eq(awg.obf_unsafe({ ...MAX, s3: '11' }), [ 'S3 must be at least 12 with header protection.' ], 'too little padding');
eq(awg.obf_unsafe({ ...MAX, s4: null }), [ 'S4 must be at least 12 with header protection.' ], 'no padding');
eq(awg.obf_unsafe({ s1: '0', s2: '0' }), [], 'none needed without the key');
});
test('obf_unsafe: 3.1 timers and counts', () => {
eq(awg.obf_unsafe({ rekey_after_time: '100-120', rekey_timeout: '3', keepalive_timeout: '0', max_handshake_attempts: '0-0' }), [],
'numbers, ranges and 0 (the default)');
eq(awg.obf_unsafe({ rekey_timeout: '0-7' }), [ 'RekeyTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'a 0 in a range');
eq(awg.obf_unsafe({ keepalive_timeout: '15-5' }), [ 'KeepaliveTimeout must be a number or a range like 5-15, from 1 to 65535.' ], 'reversed');
eq(awg.obf_unsafe({ max_handshake_attempts: '70000' }), [ 'MaxHandshakeAttempts must be a number or a range like 5-15, from 1 to 65535.' ], 'past 16 bits');
eq(awg.obf_unsafe({ content_padding_addition: '0-100' }), [], 'padding may start at 0');
eq(awg.obf_unsafe({ content_padding_addition: '10-x' }), [ 'ContentPaddingAddition must be a number or a range like 10-100, up to 65535.' ], 'padding');
});
test('obf_unsafe: RejectAfterTime up to 180 seconds', () => {
eq(awg.obf_unsafe({ reject_after_time: '150-180' }), [], 'the preset');
eq(awg.obf_unsafe({ reject_after_time: '150-181' }), [ 'RejectAfterTime must be at most 180 seconds.' ], 'the kernel drops keys after 180 seconds');
});
test('obf_unsafe: switches', () => {
eq(awg.obf_unsafe({ random_trailers: 'on', disable_cookies: '0' }), [], 'on, off, 1, 0');
eq(awg.obf_unsafe({ random_trailers: 'yes' }), [ 'RandomTrailers must be on or off.' ], 'what the .conf parser refuses');
eq(awg.obf_unsafe({ disable_cookies: 'true' }), [ 'DisableCookies must be on or off.' ], 'the same for cookies');
});
test('obf_unsafe: signature packet tags', () => {
let bad = (name, tag) => `${name}: <${tag}> is not a tag AmneziaWG apps accept: use <b 0x…> with an even number of hex digits, <r N>, <rc N> or <rd N> with N from 1 to 1000, or <t>.`;
eq(awg.obf_unsafe({ i1: '<b 0xC0ffee><r 1><rc 1000><rd 12><t>', i2: 'text between tags <r 2> is skipped' }), [], 'every tag both parsers know');
eq(awg.obf_unsafe({ i1: '<b 0xabc>' }), [ bad('I1', 'b 0xabc') ], 'an odd number of hex digits');
eq(awg.obf_unsafe({ i1: '<b 0x>' }), [ bad('I1', 'b 0x') ], 'no bytes');
eq(awg.obf_unsafe({ i1: '<b ff00>' }), [ bad('I1', 'b ff00') ], 'no 0x (the kernel needs it)');
eq(awg.obf_unsafe({ i1: '<b 0xzz>' }), [ bad('I1', 'b 0xzz') ], 'not hex');
eq(awg.obf_unsafe({ i2: '<r -5>' }), [ bad('I2', 'r -5') ], 'a negative length writes past the packet');
eq(awg.obf_unsafe({ i2: '<rc 0>' }), [ bad('I2', 'rc 0') ], 'no length');
eq(awg.obf_unsafe({ i2: '<rd 1001>' }), [ bad('I2', 'rd 1001') ], 'too long');
eq(awg.obf_unsafe({ i3: '<r 5>' }), [ bad('I3', 'r 5') ], 'two spaces');
eq(awg.obf_unsafe({ i3: '<t >' }), [ bad('I3', 't ') ], 'a space after t');
eq(awg.obf_unsafe({ i4: '<c>' }), [ bad('I4', 'c') ], 'the kernel\'s counter, which amneziawg-go refuses');
for (let t in [ 'd', 'ds', 'dz' ])
eq(awg.obf_unsafe({ i4: `<${t}>` }), [ bad('I4', t) ], `amneziawg-go's <${t}>, which the kernel refuses`);
eq(awg.obf_unsafe({ i5: '<>' }), [ bad('I5', '') ], 'an empty tag');
eq(awg.obf_unsafe({ i5: '<r <5>' }), [ bad('I5', 'r <5') ], 'a tag inside a tag');
eq(awg.obf_unsafe({ i5: '<b 0x0102030405060708090a0b0c0d0e0f>' }), [], 'long tags are fine');
eq(awg.obf_unsafe({ i5: '<x 0x0102030405060708090a0b0c0d0e0f>' }), [ bad('I5', 'x 0x0102030405060708090a…') ], 'shown cut short');
eq(awg.obf_unsafe({ i1: '<r 5' }), [ 'I1 has a tag that is not closed with >.' ], 'not closed');
eq(awg.obf_unsafe({ i1: '<r 5><b 0x00> # note' }), [ 'I1 may not contain # or a line break.' ], 'a comment in a .conf');
eq(awg.obf_unsafe({ i1: '<r 5>\n<t>' }), [ 'I1 may not contain # or a line break.' ], 'a line break');
});
test('obf_unsafe: I1-I5 fit one configuration', () => {
// A tag of 100 characters.
let tag = '<b 0x';
for (let n = 0; n < 47; n++)
tag += 'ab';
tag += '>';
let many = (n) => {
let out = '';
for (let k = 0; k < n; k++)
out += tag;
return out;
};
let four = many(4);
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: four }), [], '2000 characters');
eq(awg.obf_unsafe({ i1: four, i2: four, i3: four, i4: four, i5: many(5) }), [ 'I1-I5 together must be at most 2000 characters, not 2100.' ], 'over 2000');
});
test('obf_unsafe: an import or restore with such values is refused', () => {
let dir = '/tmp/dawnline-tests/import';
let errs = (text) => {
system(`rm -rf ${dir}; mkdir -p ${dir}/.delta`);
writefile(`${dir}/dawnline`, text);
let c = cursor(dir, `${dir}/.delta`);
c.load('dawnline');
let out = backup.config_errors(c);
system(`rm -rf ${dir}`);
return out;
};
let fixture = readfile('/etc/config/dawnline');
let bad = errs(replace(fixture, "option jmax '128'", "option jmax '32'"));
ok(index(bad, 'Server Main: Jmin must not be larger than Jmax.') >= 0, `refused: ${join(' ', bad)}`);
eq(filter(errs(fixture), (e) => index(e, 'Jmin') >= 0), [], 'the fixture as it is');
});
// The stand-in's call log and failures (fixtures/bin/awg).
const AWG_CALLS = '/tmp/dawnline-tests/awg-calls';
const AWG_FAIL = '/tmp/dawnline-tests/awg-fail-';
const SERVER_KEY = 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=';
const PEER_ON = 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=', PEER_NEW = 'TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0=';
// A fixture's lines as another interface's (`show all` prints the ifname first).
function lines_as(name, ifname) {
let out = '';
for (let l in split(readfile(`${fixtures}/awg-dump-${name}.txt`), '\n'))
if (l != '')
out += `${ifname}${substr(l, length('awgmain'))}\n`;
return out;
}
// lo is in every container's /sys/class/net (index 1), and is no AmneziaWG
// interface: the stand-in prints the fixture's lines for it, as for a tunnel.
function dump_of(name) {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
return awg.dump();
writefile(AWG_DUMP, lines_as(name, 'lo'));
return awg.dump([ 'lo' ]);
}
test('dump: AmneziaWG 1.0 (14 interface fields)', () => {
let d = dump_of('1.0');
eq(d.ok, true, 'ok');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(d.peers['HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw='],
{ ifname: 'awgmain', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 }, 'peer with a session');
eq(d.peers['TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0='],
{ ifname: 'awgmain', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
eq(d.reads, { lo: 'read' }, 'read');
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface; its index is the epoch of its counters');
eq(d.peers[PEER_ON], { ifname: 'lo', endpoint: '203.0.113.7:41821', handshake: 1760000000, rx: 123456, tx: 654321 },
'peer with a session, with the ifname the lines leave out');
eq(d.peers[PEER_NEW], { ifname: 'lo', endpoint: '', handshake: 0, rx: 0, tx: 0 }, 'peer that never connected');
});
test('dump: AmneziaWG 2.0 (33 interface fields)', () => {
let d = dump_of('2.0');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(keys(d.peers), [ 'HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw=' ], 'one peer');
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
eq(keys(d.peers), [ PEER_ON ], 'one peer');
});
test('dump: AmneziaWG 3.1 (33 interface fields, protection on)', () => {
let d = dump_of('3.1');
eq(d.ifaces, { awgmain: { public_key: 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=', port: 51820 } }, 'interface');
eq(d.ifaces, { lo: { public_key: SERVER_KEY, port: 51820, ifindex: 1 } }, 'interface');
eq(length(d.peers), 2, 'two peers');
});
test('dump: the tool fails', () => {
// awgmain is not in the container's /sys/class/net, as a tunnel netifd could not bring up.
test('dump: a tunnel that is not there is down, without a process', () => {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`));
unlink(AWG_CALLS);
eq(awg.dump([ 'awgmain' ]), { ok: true, reads: { awgmain: 'down' }, ifaces: {}, peers: {} }, 'its counters are gone');
eq(readfile(AWG_CALLS), null, 'awg is not asked about a link the kernel does not have');
eq(awg.dump([]), { ok: true, reads: {}, ifaces: {}, peers: {} }, 'no tunnel runs');
});
test('dump: each tunnel on its own', () => {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-1.0.txt`) + lines_as('2.0', 'lo'));
let d = awg.dump([ 'awgmain', 'lo' ]);
eq([ d.ok, d.reads ], [ true, { awgmain: 'down', lo: 'read' } ], 'one down, one read');
eq(keys(d.ifaces), [ 'lo' ], 'only what was read');
eq(filter(values(d.peers), (p) => p.ifname != 'lo'), [], 'no peers of the one that is down');
});
// The tool says "Operation not supported" for lo on a real system.
test('dump: a tunnel that exists but cannot be read', () => {
writefile(AWG_DUMP, lines_as('2.0', 'lo'));
writefile(`${AWG_FAIL}lo`, 'Unable to access interface: Operation not supported\n');
let d = awg.dump([ 'awgmain', 'lo' ]);
unlink(`${AWG_FAIL}lo`);
eq(d.ok, false, 'not every tunnel was read');
eq(d.reads, { awgmain: 'down', lo: 'error' }, 'each on its own');
eq([ d.ifaces, d.peers ], [ {}, {} ], 'nothing of the failed one');
});
// The agent's watcher reads every second: with one server, one process.
test('dump: only the tunnels asked for, one process each', () => {
writefile(AWG_DUMP, lines_as('1.0', 'lo') + lines_as('2.0', 'wgclient'));
unlink(AWG_CALLS);
let d = awg.dump([ 'lo' ]);
// The tests after these find no tunnel, as on a router without AmneziaWG running.
unlink(AWG_DUMP);
let d = awg.dump();
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
eq(readfile(AWG_CALLS), 'show lo dump\n', 'one call, never `all`');
eq(keys(d.ifaces), [ 'lo' ], 'the other tunnel is not read');
eq(d.peers[PEER_ON].ifname, 'lo', 'its peers stand in for none of ours');
});
test('tunnel_devices: what sync_peers loads', () => {
let m = {
servers: { s: { public_key: SERVER_KEY } },
people: { a: { id: 'a', server: 's' }, b: { id: 'b', server: 's' }, c: { id: 'c', server: 'other' } },
devices: {
on: { person: 'a', public_key: PEER_ON, address: '10.9.0.2' },
own: { person: 'a', public_key: SERVER_KEY, address: '10.9.0.8' },
off: { person: 'a', public_key: PEER_NEW, address: '10.9.0.3', disabled: true },
paused: { person: 'b', public_key: SERVER_KEY, address: '10.9.0.4' },
elsewhere: { person: 'c', public_key: PEER_NEW, address: '10.9.0.5' },
badkey: { person: 'a', public_key: 'not a key', address: '10.9.0.6' },
badaddr: { person: 'a', public_key: PEER_NEW, address: '' },
nobody: { person: 'gone', public_key: PEER_NEW, address: '10.9.0.7' },
},
};
let st = { a: 'quota', b: 'paused', c: 'active' };
eq(map(awg.tunnel_devices(m, 's', st), (d) => d.address), [ '10.9.0.2' ],
'over the limit stays; off, paused, other servers, lines syncconf would refuse and the server\'s own key (ignored by the kernel) do not');
eq(map(awg.tunnel_devices(m, 'other', st), (d) => d.address), [ '10.9.0.5' ], 'the other server');
eq(awg.tunnel_devices(m, 'none', st), [], 'none');
});
test('peer_diff: by key, per tunnel', () => {
let dmp = { peers: {} };
dmp.peers[PEER_ON] = { ifname: 'awgmain' };
dmp.peers[SERVER_KEY] = { ifname: 'awgmain' };
dmp.peers[PEER_NEW] = { ifname: 'awgother' };
let devs = (...ks) => map(ks, (k) => ({ public_key: k }));
eq(awg.peer_diff(devs(PEER_ON, SERVER_KEY), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 0 }, 'the same');
eq(awg.peer_diff(devs(PEER_ON, PEER_NEW), dmp, 'awgmain'), { loaded: 2, missing: 1, extra: 1 },
'a stale peer standing in for a missing one');
eq(awg.peer_diff(devs(PEER_ON), dmp, 'awgmain'), { loaded: 2, missing: 0, extra: 1 }, 'one too many');
eq(awg.peer_diff(devs(PEER_NEW), dmp, 'awgdown'), { loaded: 0, missing: 1, extra: 0 }, 'a tunnel with no peers read');
eq(awg.peer_diff([], { peers: {} }, 'awgmain'), { loaded: 0, missing: 0, extra: 0 }, 'nothing either way');
});
test('handshake_since: Reconnect hides older handshakes', () => {
@@ -114,4 +349,208 @@ test('blocked reasons', () => {
// Files of older versions hold the English fragment after the name.
eq(awg.blocked_text(srv('has an invalid interface name "x"')), 'Home has an invalid interface name "x".', 'old fragment');
eq(awg.blocked_note({ code: 'ifname', ifname: 'x' }), 'has an invalid interface name "x"', 'the log keeps the fragment');
// Values AmneziaWG refuses: which ones, from the server's own when read.
let bad = { name: 'Home', obf: { jmin: '60', jmax: '50' }, blocked: { code: 'disguise_invalid' } };
eq(awg.blocked_text(bad), 'Home is kept down: its disguise has values AmneziaWG cannot take. Jmin must not be larger than Jmax.', 'invalid values');
eq(awg.blocked_text({ ...bad, obf: {} }), 'Home is kept down: its disguise has values AmneziaWG cannot take.', 'fixed since');
eq(awg.blocked_note(bad.blocked), 'is kept down: its disguise has values AmneziaWG cannot take', 'the log');
eq(awg.blocked_fix(bad.blocked), 'Choose a disguise on the Server page: it replaces the values set by hand.', 'what to do about it');
eq(awg.blocked_fix({ code: 'taken', ifname: 'wg0' }), 'Choose another interface name in the server settings.', 'what to do about a name');
});
test('netifd_options: the server keeps its defence against handshake floods', () => {
let m = core.load();
let srv = m.servers.main;
srv.obf = awg.obf_preset('max');
let o = awg.netifd_options(srv);
ok('awg_disable_cookies' in o, 'named, so netifd.sync takes it off an interface that had it');
eq(o.awg_disable_cookies, null, 'no DisableCookies on the server');
eq([ o.awg_header_protection_key, o.awg_jc, o.awg_i1, o.awg_random_trailers ], [ srv.obf.header_protection_key, srv.obf.jc, srv.obf.i1, 'on' ],
'the rest of the disguise stays');
ok(index(split(awg.client_config(m, m.devices.alice_phone).conf, '\n'), 'DisableCookies = on') >= 0, 'devices keep it');
});
test('client_config: one keep-alive for the .conf and the AmneziaVPN key', () => {
let m = core.load();
let srv = m.servers.main, dev = m.devices.alice_phone;
let ka = () => {
let c = awg.client_config(m, dev);
return [ match(c.conf, /\nPersistentKeepalive = ([^\n]*)\n/)?.[1], c.amnezia.persistent_keep_alive ];
};
eq(ka(), [ '25', '25' ], 'a number without header protection');
srv.obf = awg.obf_preset('max');
eq(ka(), [ '25-35', '25-35' ], 'jittered with 3.1');
srv.keepalive = 0;
eq(ka(), [ null, '0' ], 'off');
});
test('status: the header protection key stays out of what read-only users get', () => {
eq(awg.obf_public({ jc: '4', header_protection_key: HPK }), { jc: '4' }, 'obf_public');
eq(awg.obf_public(null), {}, 'no values');
// Server main on Maximum, as a uci change not committed (the fixture file stays as it is).
let c = cursor();
c.load('dawnline');
let o = awg.obf_preset('max');
for (let k, v in o)
c.set('dawnline', 'main', k, v);
c.save('dawnline');
let out = rpc_status.methods.status.call({ args: { days: 30 } });
c.revert('dawnline');
eq(out.error, null, 'status answers');
let srv = filter(out.servers ?? [], (x) => x.id == 'main')[0];
eq([ srv?.hpk, srv?.obf?.header_protection_key, srv?.obf?.disable_cookies ], [ true, null, 'on' ], 'whether there is a key, not which');
let text = sprintf('%J', out);
ok(index(text, o.header_protection_key) < 0, 'the key is nowhere in the answer');
let found = uniq(map(match(text, /[A-Za-z0-9+\/]{43}=/g) ?? [], (x) => x[0]));
eq(found, [ srv.public_key ], 'no key but the server\'s public one');
});
test('client_config: an IPv6 endpoint in brackets, without a regex', () => {
let m = core.load();
let srv = m.servers.main, dev = m.devices.alice_phone;
let ep = (h) => {
srv.endpoint = h;
return match(awg.client_config(m, dev).conf, /\nEndpoint = ([^\n]*)\n/)?.[1];
};
eq(ep('vpn.example.com'), 'vpn.example.com:51820', 'a name');
eq(ep('203.0.113.7'), '203.0.113.7:51820', 'IPv4');
eq(ep('2001:db8::1'), '[2001:db8::1]:51820', 'IPv6');
eq(ep('[2001:db8::1]'), '[2001:db8::1]:51820', 'IPv6 in brackets already');
eq(ep(''), 'vpn.example.com:51820', 'the portal name when the server has none');
// The regexes it stands for, on hosts changed at each character.
for (let h in [ '2001:db8::1', '[::1]', 'a.b' ])
for (let i = 0; i <= length(h); i++)
for (let c in [ ':', '[', ']', 'a', '' ]) {
let s = `${substr(h, 0, i)}${c}${substr(h, i + 1)}`;
let want = match(s, /:/) && !match(s, /^\[/) ? `[${s}]` : s;
eq(ep(s), `${want || 'vpn.example.com'}:51820`, s);
}
});
test('config_fingerprint leaves out the private key and the junk', () => {
let m = core.load();
let dev = m.devices.alice_phone;
let f = awg.config_fingerprint(m, dev);
ok(match(f, /^[0-9a-f]{8}$/), 'eight hex digits');
dev.private_key = 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=';
eq(awg.config_fingerprint(m, dev), f, 'a private key');
m.servers.main.obf.jc = '7';
eq(awg.config_fingerprint(m, dev), f, 'another junk count');
m.servers.main.port = 51821;
ok(awg.config_fingerprint(m, dev) != f, 'another port');
eq(awg.config_fingerprint(m, null), null, 'no device');
});
/* ---------- a device's local network, MTU and keep-alive ---------- */
// Exactly the complement: aligned prefixes, none overlapping another or a
// private range, and all of them together the whole address space.
test('BYPASS4: every IPv4 address outside the private ranges, once', () => {
let nets = [ ...map(awg.BYPASS4, (n) => [ n, false ]), ...map(nft.PRIVATE4, (n) => [ n, true ]) ];
let total = 0;
for (let i = 0; i < length(nets); i++) {
let a = cidr_any(nets[i][0]);
ok(a && a.ip == a.net, `${nets[i][0]}: a prefix`);
total += a.size;
for (let j = i + 1; j < length(nets); j++) {
let b = cidr_any(nets[j][0]);
ok(a.net + a.size <= b.net || b.net + b.size <= a.net, `${nets[i][0]} and ${nets[j][0]} apart`);
}
}
eq(total, 4294967296, 'together: every address');
});
test('BYPASS6: every IPv6 address outside fc00::/7, fe80::/10 and ff00::/8, once', () => {
// Each of them is /16 or wider: the first 16 bits decide.
let span = (n) => {
let p = split(n, '/'), len = +p[1];
ok(len >= 1 && len <= 16 && substr(p[0], -2) == '::', `${n}: a prefix of the first 16 bits`);
let g = substr(p[0], 0, length(p[0]) - 2);
let start = g == '' ? 0 : hex(g), size = 1 << (16 - len);
ok(start % size == 0, `${n}: aligned`);
return [ start, size ];
};
let nets = map([ ...awg.BYPASS6, 'fc00::/7', 'fe80::/10', 'ff00::/8' ], span);
let total = 0;
for (let i = 0; i < length(nets); i++) {
total += nets[i][1];
for (let j = i + 1; j < length(nets); j++)
ok(nets[i][0] + nets[i][1] <= nets[j][0] || nets[j][0] + nets[j][1] <= nets[i][0], `${i} and ${j} apart`);
}
eq(total, 65536, 'together: every address');
});
test('allowed_ips: the local network outside the tunnel', () => {
let m = core.load();
let srv = m.servers.main;
// No home network from the container's own interfaces.
srv.auto_lan = false;
srv.lan_devices = [];
let alice = m.people.alice, bob = m.people.bob;
eq(awg.allowed_ips(m, srv, bob), [ '0.0.0.0/0', '::/0' ], 'no device: everything');
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: false }), [ '0.0.0.0/0', '::/0' ], 'as before');
let dns = (list) => [ ...slice(list, 0, 2), '10.9.0.1/32', ...slice(list, 2) ];
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'internet: the rest, and its DNS');
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...slice(awg.BYPASS4, 0, 2), '10.9.0.0/29', ...slice(awg.BYPASS4, 2), ...awg.BYPASS6 ],
'home too: the tunnel network with the other devices (the DNS is in it)');
srv.mesh = 'off';
srv.device_mesh = false;
eq(awg.allowed_ips(m, srv, alice, { lan_bypass: true }), [ ...dns(awg.BYPASS4), ...awg.BYPASS6 ], 'no mesh: the router');
srv.dns = [ '192.168.1.1', '192.168.1.53', 'fd00::53', '2001:4860:4860::8888', 'fe80::1' ];
let all = awg.allowed_ips(m, srv, bob, { lan_bypass: true });
ok(index(all, '192.168.1.1/32') >= 0 && index(all, '192.168.1.53/32') >= 0, 'every private IPv4 DNS server stays in the tunnel, not only the first');
eq(slice(all, length(all) - length(awg.BYPASS6) - 2), [ ...awg.BYPASS6, 'fd00::53/128', 'fe80::1/128' ],
'a private IPv6 one too; a public IPv6 one is in the rest already');
eq(length(all), length(awg.BYPASS4) + 2 + length(awg.BYPASS6) + 2, 'nothing else');
srv.dns = [ '1.1.1.1' ];
eq(awg.allowed_ips(m, srv, bob, { lan_bypass: true }), [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'a public DNS is in the rest already');
alice.access = 'lan';
alice.dns_mode = 'home';
let lan = awg.allowed_ips(m, srv, alice, { lan_bypass: true });
eq(lan, awg.allowed_ips(m, srv, alice), 'Home only: the same either way');
let c = awg.client_config(m, { ...m.devices.alice_phone, person: 'bob', lan_bypass: true });
eq(c.amnezia.allowed_ips, [ ...awg.BYPASS4, ...awg.BYPASS6 ], 'in the AmneziaVPN key');
ok(index(c.conf, `AllowedIPs = ${join(', ', [ ...awg.BYPASS4, ...awg.BYPASS6 ])}\n`) >= 0, 'in the .conf');
});
test('keepalive_range and idle_handshake', () => {
let srv = { keepalive: 25, obf: {} };
eq(awg.keepalive_range(srv, {}), [ 25, 25 ], 'the server\'s, no range');
eq(awg.keepalive_range(srv, { keepalive: 120 }), [ 120, 120 ], 'the device\'s own');
eq(awg.keepalive_range(srv, { keepalive: 0 }), null, 'off for the device');
eq(awg.keepalive_range({ keepalive: 0, obf: {} }, {}), null, 'off on the server');
let max = { keepalive: 25, obf: awg.obf_preset('max') };
eq(awg.keepalive_range(max, {}), [ 25, 35 ], 'jittered with 3.1');
eq(awg.keepalive_range(max, { keepalive: 60 }), [ 60, 70 ], 'the device\'s own, jittered');
// The first keep-alive after the rekey time (120 s; RekeyAfterTime's upper end) starts a handshake.
eq(awg.idle_handshake(srv, {}), 145, 'within the rekey time: up to one keep-alive past it');
eq(awg.idle_handshake(max, {}), 155, 'Maximum: RekeyAfterTime 100-120, keep-alive up to 35');
eq(awg.idle_handshake(srv, { keepalive: 100 }), 220, 'every second keep-alive');
eq(awg.idle_handshake(srv, { keepalive: 300 }), 300, 'every keep-alive once they are further apart');
eq(awg.idle_handshake({ keepalive: 25, obf: { rekey_after_time: '200-400' } }, {}), 205, 'past 180 s the key is refused anyway');
eq(awg.idle_handshake(srv, { keepalive: 0 }), null, 'no keep-alive: none');
});
test('client_config: the device\'s own MTU and keep-alive', () => {
let m = core.load();
let dev = m.devices.alice_phone;
let line = (c, k) => match(c.conf, regexp(`\n${k} = ([^\n]*)\n`))?.[1];
let c = awg.client_config(m, dev);
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu ], [ '1280', '25', '1280' ], 'the server\'s (a phone)');
let fp = awg.config_fingerprint(m, dev);
let old = { ...dev };
delete old.mtu;
delete old.keepalive;
delete old.lan_bypass;
eq(awg.config_fingerprint(m, old), fp, 'a device without values of its own keeps its fingerprint (as before the options)');
dev.mtu = 1420;
dev.keepalive = 0;
c = awg.client_config(m, dev);
eq([ line(c, 'MTU'), line(c, 'PersistentKeepalive'), c.amnezia.mtu, c.amnezia.persistent_keep_alive ], [ '1420', null, '1420', '0' ],
'its own; keep-alive off');
ok(awg.config_fingerprint(m, dev) != fp, 'a change asks it to import again');
m.servers.main.obf = awg.obf_preset('max');
dev.keepalive = 120;
c = awg.client_config(m, dev);
eq([ line(c, 'PersistentKeepalive'), c.amnezia.persistent_keep_alive ], [ '120-130', '120-130' ], 'jittered with 3.1');
});
+59
View File
@@ -0,0 +1,59 @@
// dawnline.awg_builds: the AmneziaWG generation of package and kernel module
// versions, whether an installed update waits for a reboot (its old module
// stayed loaded) and the generation that really runs meanwhile, which is
// what caps() reports.
import * as builds from 'dawnline.awg_builds';
import * as awg from 'dawnline.awg';
// The live router's module (3.1) after an update from a 2.0 one that could not be swapped.
const KMOD_31 = '6.12.94.3.1.20260906-r1';
const WAITING = { reloaded: false, boot: 'boot-1', prev_gen: '2.0', prev_core: 98304 };
test('gen of package versions', () => {
eq(builds.gen(null), null, 'not installed');
eq(builds.gen('3.1.20260812-r1'), '3.1', 'amneziawg-tools 3.1');
eq(builds.gen('3.1.0-r1'), '3.1', 'luci-proto-amneziawg 3.1');
eq(builds.gen('1.0.20250722-r1'), '2.0', 'July 2025 on: 2.0');
eq(builds.gen('1.0.20250901'), '2.0', 'no release suffix');
eq(builds.gen('1.0.20250610-r1'), '1.0', 'before July 2025');
eq(builds.gen('1.0.20241112-r2'), '1.0', '2024');
});
test('gen of kernel module versions', () => {
eq(builds.gen(KMOD_31), '3.1', 'kernel release in front');
eq(builds.gen('6.12.94.3.1.20260906'), '3.1', 'no release suffix');
eq(builds.gen('6.6.73.1.0.20250722-r1'), '2.0', '2.0 module');
eq(builds.gen('6.6.73.1.0.20250612-r1'), '1.0', 'first generation module');
eq(builds.gen('5.15.150.1.0.20240711-r3'), '1.0', '2024 module on an older kernel');
eq(builds.gen('3.1.20260812'), '3.1', 'the version.h string of a 3.1 module');
});
test('pending: an update waits for a reboot', () => {
ok(builds.pending(WAITING, 'boot-1', 98304), 'the old module still loaded, same boot');
ok(!builds.pending(WAITING, 'boot-2', 98304), 'rebooted');
ok(!builds.pending(WAITING, 'boot-1', null), 'no module loaded: the next one is the new one');
ok(!builds.pending(WAITING, 'boot-1', 110592), 'another module loaded (reloaded by hand)');
ok(!builds.pending({ ...WAITING, reloaded: true }, 'boot-1', 98304), 'the install swapped it');
ok(!builds.pending({ ...WAITING, reloaded: null }, 'boot-1', 98304), 'a record of a module Dawnline did not install');
ok(!builds.pending({ osrelease: '6.12.94', source: 'slava', tag: 'v25.12.5', installed: 1 }, 'boot-1', 98304),
'a record from before boots were kept');
ok(!builds.pending({ ...WAITING, boot: null }, null, 98304), 'the kernel gave no boot id');
ok(!builds.pending(null, 'boot-1', 98304), 'no record');
});
test('caps: the generation that runs while a reboot is pending', () => {
eq(builds.running_gen(WAITING, 'boot-1', 98304, KMOD_31), '2.0', 'the 2.0 module runs, not the 3.1 package');
eq(builds.running_gen(WAITING, 'boot-2', 98304, KMOD_31), '3.1', 'after the reboot: the package');
eq(builds.running_gen(WAITING, 'boot-1', null, KMOD_31), '3.1', 'nothing loaded: the package loads');
eq(builds.running_gen(null, 'boot-1', 98304, KMOD_31), '3.1', 'no record: the package');
eq(builds.running_gen({ ...WAITING, prev_gen: null }, 'boot-1', 98304, KMOD_31), null,
'a module installed by hand before: unknown, the tools are believed');
eq(builds.running_gen(null, null, null, null), null, 'nothing installed');
});
test('caps in a container without AmneziaWG', () => {
let c = awg.caps();
eq(c.kmod, null, 'no module package');
eq(c.pending, false, 'nothing waits for a reboot');
eq(builds.module_core(), null, 'no module loaded');
});
+119 -1
View File
@@ -1,6 +1,8 @@
// dawnline.core: the model read from the fixture config (real libuci), access
// hours, quotas and the derived person state at an explicit time, address
// allocation and the automatic MTU.
// allocation, the automatic MTU, a device's own MTU, keep-alive and local
// network, and other packages' port forwards.
import { readfile, writefile, unlink } from 'fs';
import * as core from 'dawnline.core';
// A local time that no time zone turns into another day.
@@ -27,6 +29,8 @@ test('load reads the fixture', () => {
eq(m.settings.updates.interval, '7d', 'update policy from the same section');
eq(m.settings.updates.targets, [ 'app' ], 'update targets list');
eq(m.settings.retention.log_connections, '0', 'raw retention values');
let d = m.devices.alice_phone;
eq([ d.mtu, d.keepalive, d.lan_bypass ], [ 0, null, false ], 'a device without link values of its own');
});
test('parse_hours', () => {
@@ -128,6 +132,94 @@ test('tunnel_mtu / device_mtu', () => {
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone' }), 1280, 'phone');
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer' }), 1380, 'computer');
eq(core.device_mtu({ mtu: 1200 }, { kind: 'tablet' }), 1200, 'a smaller tunnel MTU stays');
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 1420 }), 1420, 'the device\'s own, also above 1280 on a phone');
eq(core.device_mtu({ mtu: 1420 }, { kind: 'computer', mtu: 1280 }), 1280, 'the device\'s own below the tunnel\'s');
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'computer', mtu: 9000 }), 1380, 'out of range (a hand edit): the automatic one');
eq(core.device_mtu({ mtu: 0, obf: {} }, { kind: 'phone', mtu: 0 }), 1280, '0: as before');
});
test('device_keepalive', () => {
let srv = { keepalive: 25 };
eq(core.device_keepalive(srv, { keepalive: null }), 25, 'the server\'s');
eq(core.device_keepalive(srv, {}), 25, 'none read');
eq(core.device_keepalive(srv, { keepalive: 0 }), 0, 'off for this device');
eq(core.device_keepalive(srv, { keepalive: 120 }), 120, 'its own');
eq(core.device_keepalive(srv, { keepalive: 700 }), 25, 'out of range: the server\'s');
eq(core.device_keepalive({ keepalive: 0 }, { keepalive: 15 }), 15, 'its own on a server without keep-alive');
});
/** A uci cursor that records what is written: { 'section.option': value or null (deleted) }. */
function recorder() {
let w = {};
return { w, c: { set: (cfg, s, k, v) => { w[`${s}.${k}`] = v; }, delete: (cfg, s, k) => { w[`${s}.${k}`] = null; } } };
}
test('set_device_kind', () => {
let mm = { devices: { d: { id: 'd', kind: 'phone' } } };
let r = recorder();
eq(core.set_device_kind(r.c, mm, 'd', 'tablet'), true, 'changed');
eq([ r.w, mm.devices.d.kind ], [ { 'd.kind': 'tablet' }, 'tablet' ], 'written, and the model follows');
r = recorder();
eq(core.set_device_kind(r.c, mm, 'd', 'tablet'), false, 'the same kind changes nothing');
eq(r.w, {}, 'nothing written');
throws(() => core.set_device_kind(r.c, mm, 'd', 'toaster'), /^Unknown device type\.$/, 'not a kind');
throws(() => core.set_device_kind(r.c, mm, 'x', 'phone'), /^Unknown device\.$/, 'unknown device');
});
test('set_device_link', () => {
let mm = { devices: { d: { id: 'd', mtu: 0, keepalive: null, lan_bypass: false } } };
let r = recorder();
eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: '0', lan_bypass: true }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'what changed');
eq(r.w, { 'd.mtu': '1400', 'd.keepalive': '0', 'd.lan_bypass': '1' }, 'written');
r = recorder();
mm.devices.d = { id: 'd', mtu: 1400, keepalive: 0, lan_bypass: true };
eq(core.set_device_link(r.c, mm, 'd', { mtu: '', keepalive: '', lan_bypass: false }), [ 'mtu', 'keepalive', 'lan_bypass' ], 'back');
eq(r.w, { 'd.mtu': null, 'd.keepalive': null, 'd.lan_bypass': null }, 'removed: the server\'s again');
r = recorder();
eq(core.set_device_link(r.c, mm, 'd', { mtu: '1400', keepalive: ' 0 ' }), [], 'the same values change nothing');
eq(r.w, {}, 'nothing written');
eq(core.set_device_link(r.c, mm, 'd', {}), [], 'nothing asked');
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1279' }), /^MTU must be 1280-1500\.$/, 'MTU too small');
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1501' }), /^MTU must be 1280-1500\.$/, 'MTU too large');
throws(() => core.set_device_link(r.c, mm, 'd', { mtu: '1400.5' }), /^MTU/, 'not a whole number');
throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '601' }), /^Keep-alive must be 0-600 seconds\.$/, 'keep-alive too long');
throws(() => core.set_device_link(r.c, mm, 'd', { keepalive: '-1' }), /^Keep-alive/, 'negative');
throws(() => core.set_device_link(r.c, mm, 'x', { mtu: '' }), /^Unknown device\.$/, 'unknown device');
});
test('create_device: the local network outside the tunnel', () => {
let mm = core.load();
let r = recorder();
let keys = { public_key: 'a8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=', preshared_key: '' };
let id = core.create_device(r.c, mm, 'bob', 'Laptop', 'computer', { keys, lan_bypass: true });
eq([ r.w[`${id}.lan_bypass`], mm.devices[id].lan_bypass, mm.devices[id].mtu, mm.devices[id].keepalive ], [ '1', true, 0, null ], 'set');
r = recorder();
id = core.create_device(r.c, mm, 'bob', 'Tablet', 'tablet', { keys: { ...keys, public_key: 'b8Z2wq0b8rQx3mN6kYyQ2G3bQm2kq5tY5m7Q0yq3m3c=' } });
ok(!(`${id}.lan_bypass` in r.w) && !mm.devices[id].lan_bypass, 'off unless asked');
});
test('create_device: not with the server\'s own key', () => {
let mm = core.load();
let keys = { public_key: mm.servers.main.public_key, preshared_key: '' };
throws(() => core.create_device(recorder().c, mm, 'bob', 'Laptop', 'computer', { keys }), /^This key is already in use\.$/,
'it is in every configuration of the server');
mm.devices.alice_phone.public_key = mm.servers.main.public_key;
eq(core.model_errors(mm), [ "Device Phone of Alice: the public key is the server's own." ], 'one set by hand is named');
});
test('model_errors: a device\'s own MTU and keep-alive', () => {
let mm = core.load();
eq(core.model_errors(mm), [], 'the fixture is consistent');
let d = mm.devices.alice_phone;
d.mtu = 1400;
d.keepalive = 0;
eq(core.model_errors(mm), [], 'values of its own in range');
d.mtu = 9000;
d.keepalive = 601;
eq(core.model_errors(mm), [
'Device Phone of Alice: MTU 9000 is not between 1280 and 1500.',
'Device Phone of Alice: keep-alive 601 is not between 0 and 600 seconds.',
], 'named');
});
test('names and codes', () => {
@@ -164,3 +256,29 @@ test('device_labels', () => {
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
});
test('wan_forwards leaves out Dawnline\'s own, without a regex', () => {
// A firewall config for this case only (the container's own is put back).
let path = '/etc/config/firewall', saved = readfile(path);
let names = [ 'dawnline_portal', 'dawnline_', 'dawnline', 'Dawnline_x', 'xdawnline_y', 'dawnlinex_1', 'web' ];
let conf = '';
for (let i = 0; i < length(names); i++)
conf += sprintf("config redirect '%s'\n\toption src 'wan'\n\toption proto 'udp'\n\toption src_dport '%d'\n\n", names[i], 6000 + i);
writefile(path, conf);
let got = null, err = null;
try {
got = core.wan_forwards('wan', 'udp');
}
catch (e) {
err = e;
}
if (saved != null)
writefile(path, saved);
else
unlink(path);
if (err)
die(err.message);
// The names the pattern it stands for let through.
eq(map(got, (f) => f.name), filter(names, (n) => !match(n, /^dawnline_/)), 'names');
eq(got[0], { from: 6002, to: 6002, name: 'dawnline' }, 'a forward');
});
+86
View File
@@ -0,0 +1,86 @@
// The admin's device methods (dawnline.rpc.people over dawnline.devices): what
// counts as handing a configuration out, and New keys as setting the device up
// again. The real calls on the fixture: the stand-in awg makes the keys, the
// sync's nft and awg steps fail harmlessly in the container. /etc/config/dawnline
// and the issued and reconnect marks are put back after.
import { readfile, writefile, unlink } from 'fs';
import { DATA_DIR, RUN_DIR, ensure_dir } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as people from 'dawnline.rpc.people';
import * as devices from 'dawnline.devices';
const CONFIG = '/etc/config/dawnline';
const ISSUED = `${DATA_DIR}/issued.json`;
const RECONNECT = `${DATA_DIR}/reconnect.json`;
const EVENTS = `${RUN_DIR}/events.json`;
// fn(), then the files as they were, whatever fn did.
function kept(paths, fn) {
let had = map(paths, (p) => readfile(p));
let err = null;
try {
fn();
}
catch (e) {
err = e;
}
for (let i = 0; i < length(paths); i++)
had[i] == null ? unlink(paths[i]) : writefile(paths[i], had[i]);
if (err)
die(err.message ?? `${err}`);
}
function call(name, args) {
return people.methods[name].call({ args });
}
test('device_config: a look marks nothing, a delivery does', () => {
ensure_dir(DATA_DIR, 0o700);
kept([ ISSUED ], () => {
let old = sprintf('%J', { alice_phone: '00000000' });
writefile(ISSUED, old);
ok(index(call('device_config', { id: 'alice_phone' }).conf ?? '', '[Peer]') >= 0, 'the configuration comes back');
eq(readfile(ISSUED), old, 'without issue: issued.json left alone');
call('device_config', { id: 'alice_phone', issue: false });
eq(readfile(ISSUED), old, 'issue false: the same');
call('device_config', { id: 'alice_phone', issue: true });
let m = core.load();
eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'issue: what it holds now counts as handed out');
eq(call('device_config', { id: 'nobody', issue: true }).error, 'Unknown device.', 'an unknown device');
});
});
test('device_rotate: New keys set the device up again', () => {
kept([ CONFIG, ISSUED, RECONNECT ], () => {
unlink(RECONNECT);
let before = core.load().devices.alice_phone;
let t0 = time();
let c = call('device_rotate', { id: 'alice_phone' });
ok(c.error == null && index(c.conf ?? '', '[Peer]') >= 0, `the new configuration comes back (${c.error})`);
let m = core.load();
ok(m.devices.alice_phone.preshared_key != before.preshared_key, 'new keys');
let at = awg.reconnects().alice_phone;
ok(at >= t0 && at <= time(), `a reconnect mark at the rotation (${at})`);
eq(awg.handshake_since(t0 - 30, at), 0, "the old keys' last handshake no longer counts: Not set up yet, with Connect");
eq(awg.issued().alice_phone, awg.config_fingerprint(m, m.devices.alice_phone), 'its new configuration is the one handed out');
});
eq(core.load().devices.alice_phone.private_key, '', 'the fixture is back');
});
test('portal: Reconnect changes what it is and LAN Bypass with the keys; LAN Bypass alone keeps them', () => {
ensure_dir(RUN_DIR);
kept([ CONFIG, ISSUED, RECONNECT, EVENTS ], () => {
let mine = { by: 'portal', person: 'alice' };
devices.reconnect('alice_phone', { ...mine, kind: 'tablet', lan_bypass: true });
let d = core.load().devices.alice_phone;
eq([ d.kind, d.lan_bypass ], [ 'tablet', true ], 'changed in the same write as the keys');
let keys = d.public_key;
devices.update('alice_phone', { lan_bypass: false }, mine);
d = core.load().devices.alice_phone;
eq([ d.lan_bypass, d.public_key ], [ false, keys ], 'LAN Bypass off, the keys as they were');
throws(() => devices.update('alice_phone', { mtu: '1400' }, mine), /^Only the admin can change how a device connects\.$/, "the MTU stays the admin's");
throws(() => devices.reconnect('alice_phone', { ...mine, kind: 'toaster' }), /^Unknown device type\.$/, 'not a kind');
throws(() => devices.update('alice_phone', { lan_bypass: true }, { by: 'portal', person: 'bob' }), /^Device not found\.$/, "another person's device");
});
});
+23 -4
View File
@@ -1,10 +1,29 @@
#!/bin/sh
# Stand-in for amneziawg-tools in the ucode tests (no kernel module in a
# container): `genkey` prints one fixed key, `show all dump` prints the fixture
# a test has put at /tmp/dawnline-tests/awg-dump (or fails, as the tool does
# when no interface is up). Anything else fails.
# container): `genkey` prints one fixed key, `pubkey` (a key on stdin) the
# fixture server's public key, its pair; `show <ifname> dump` prints that
# interface's lines of the fixture a test has put at /tmp/dawnline-tests/awg-dump
# (written as `awg show all dump` prints them: the ifname first, left out here,
# as the tool does), fails as the tool does for an interface that is not there,
# and fails with the text of /tmp/dawnline-tests/awg-fail-<ifname> when a test
# put one. Every call is appended to /tmp/dawnline-tests/awg-calls. Anything
# else fails.
T=/tmp/dawnline-tests
echo "$*" >> "$T/awg-calls"
case "$1 ${2:-} ${3:-}" in
'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;;
'show all dump') cat /tmp/dawnline-tests/awg-dump ;;
'pubkey ') cat >/dev/null; echo 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg=' ;;
'show '*' dump')
if [ -e "$T/awg-fail-$2" ]; then
cat "$T/awg-fail-$2" >&2
exit 1
fi
out="$(awk -F '\t' -v i="$2" '$1 == i { sub(/^[^\t]*\t/, ""); print }' "$T/awg-dump" 2>/dev/null)"
if [ -z "$out" ]; then
echo 'Unable to access interface: No such device' >&2
exit 1
fi
printf '%s\n' "$out"
;;
*) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;;
esac
+1 -1
View File
@@ -41,4 +41,4 @@ config device 'alice_phone'
option name 'Phone'
option kind 'phone'
option address '10.9.0.2'
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
option public_key 'AuTb2wZ8C1032Ksn76nFgXzOJgT86OgEVbEE7ClpNy8='
+60
View File
@@ -0,0 +1,60 @@
table inet dawnline {
set home_home { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } }
set home_work { type ipv4_addr; flags interval; auto-merge; elements = { 192.168.1.0/24 } }
set tun_nets { type ipv4_addr; flags interval; auto-merge; elements = { 10.9.0.0/29, 10.9.1.0/29 } }
set lan_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } }
set lan_all { type ipv4_addr; elements = { 10.9.0.2, 10.9.0.3, 10.9.1.3 } }
set lan_part { type ipv4_addr . ipv4_addr; flags interval; }
set mesh_pairs { type ipv4_addr . ipv4_addr; }
set inet_ok { type ipv4_addr; elements = { 10.9.0.2, 10.9.1.2, 10.9.0.4, 10.9.0.5, 10.9.1.3 } }
set svc_ok { type ipv4_addr . ipv4_addr . inet_service; }
set svc_host { type ipv4_addr . ipv4_addr; }
set dns_real { type ipv4_addr; elements = { 10.9.0.3 } }
chain pre {
type filter hook prerouting priority -160; policy accept;
iifname { "awghome", "awgwork" } jump guard
}
chain guard {
meta nfproto ipv6 drop
ct state related accept
ct status dnat accept
icmp type { echo-request, echo-reply } fib daddr type local accept
fib daddr type local meta l4proto { tcp, udp } th dport 53 accept
fib daddr type local tcp dport { 8443 } accept
fib daddr type local ip saddr @lan_all accept
fib daddr type local ip saddr . ip daddr @lan_part accept
fib daddr type local counter drop
ip daddr 192.168.1.250 meta l4proto { tcp, udp } th dport 53 accept
iifname "awghome" ip daddr @home_home ip daddr != @tun_nets ip saddr @lan_all accept
iifname "awgwork" ip daddr @home_work ip daddr != @tun_nets ip saddr @lan_all accept
ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept
iifname "awghome" ip saddr @lan_ok ip daddr @lan_ok accept
iifname "awgwork" ip saddr . ip daddr @mesh_pairs accept
meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept
ip saddr . ip daddr @svc_host accept
ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, 169.254.0.0/16, 224.0.0.0/3 } counter drop
ip saddr @inet_ok accept
counter drop
}
chain inbound {
type filter hook forward priority filter - 5; policy accept;
oifname { "awghome", "awgwork" } iifname != { "awghome", "awgwork" } ct state new jump to_device
}
chain to_device {
meta nfproto ipv6 drop
ct status dnat accept
oifname "awghome" ip saddr @home_home ip saddr != @tun_nets ip daddr @lan_all accept
oifname "awgwork" ip saddr @home_work ip saddr != @tun_nets ip daddr @lan_all accept
ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept
counter reject with icmpx admin-prohibited
}
chain dns {
type nat hook prerouting priority dstnat - 5; policy accept;
iifname { "awghome", "awgwork" } ip saddr @dns_real meta l4proto { tcp, udp } th dport 53 dnat ip to 169.254.77.2:53
}
chain dns_lan {
type nat hook prerouting priority dstnat + 5; policy accept;
iifname "awghome" ip daddr 10.9.0.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.250:53
iifname "awgwork" ip daddr 10.9.1.1 meta l4proto { tcp, udp } th dport 53 dnat ip to 192.168.1.1:53
}
}
Loaded 100 of 279 files, more files were not shown because too many files have changed in this diff. Show more