Compare commits

14 Commits
Author SHA1 Message Date
Aemeath 466ca6c7b0 Dawnline 0.8.0
Build packages / CI (push) Blocked by required conditions
Build packages / Version (push) Waiting to run
CI / Web (format, types, tests, bundles) (push) Blocked by required conditions
CI / ShellCheck (push) Blocked by required conditions
CI / ucode static checks (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 24.10) (push) Blocked by required conditions
CI / ucode compiles and tests pass (OpenWrt 25.12) (push) Blocked by required conditions
- Every field says what is wrong as you type, in the router's own words,
  and Save refuses what the router would: UDP port when editing a server,
  MTU, keep-alive, public address, DNS for devices, person name, device
  limit, end date and data limit, device names (the next free "Phone 2"
  is offered), home services, circles, portal title, redirect and other
  addresses, defaults, update time
- Cyrillic names give Latin ids, hostnames and file names; names are
  counted in characters, the rule names the characters it refuses; end
  dates must exist on the calendar; a mistyped extra portal address is
  refused instead of dropped
- The public address is checked on the router as it is typed: points at
  this router, at another address, behind Cloudflare, or the WAN is
  private or CGNAT; the wizard says so before the first step, never
  pre-fills a private WAN address and says where its suggestion came
  from; the Connection card says when the server was last reached from
  the internet; IPv6 names and literals work throughout
- A person can be moved to another server from their page; a server's
  tunnel network can be changed in the Danger zone (devices are
  renumbered and marked "Update config"); WAN and LAN zones come from the
  router's actual devices; when the public IPv4 changed, one click puts
  the new one in
- Over the data limit or outside the allowed hours the tunnel stays
  connected and the portal explains why nothing gets through, instead of
  a silent handshake failure; Health's "devices loaded" compares the
  peers themselves, not their count
- Portal: install links for this platform, two first steps on a first
  visit, the phone's back button closes a sheet, the file goes through
  the share sheet into the app, two QR codes (AmneziaVPN camera, AmneziaWG
  and WireGuard apps), the sheet notices the first connection
- Admin: Enter submits a dialog, arrow keys walk the menus, Find in People
  ("/" focuses it), a device of a paused, ended or over-limit person says
  so, "Keep access" past its end date is said on the Overview, Allowed
  hours enforce nothing until saved, the invite card shares the link
- Health warns when another package's policy routing (mwan3, pbr) sends
  tunnel traffic past the home-device path
- CLI: person ls, device ls, log with -n, --since, --level, --src and
  --json; exit code 2 for an unknown command and 1 when health finds an
  error; person rm asks for --yes when devices would go; devices added
  from the command line get their event and "issued" marker like the
  UI's
- Three disguises: Off, Balanced and Maximum. Standard and Strong (1.0-style
  junk only, which networks learned to spot) are no longer offered; a server
  still on one keeps running and its card says to switch. A new server gets
  the strongest disguise its router can run
- Portal: setting up a device is one sheet with two steps. Get the app
  (AmneziaVPN first; AmneziaWG, and WireGuard with the disguise off, behind
  "Another app") from the store of the device in hand, with the GitHub release
  where no store has it and the version the server needs said once; then add
  the connection (open in AmneziaVPN, copy the key, share or download the
  file). A device set up from another device gets its link to take there, as a
  QR code for a phone; a phone set up from a computer also gets the connection
  as a code, one code revealed at a time so the camera cannot read the wrong one
- Portal motion: the first visit comes in once (blocks in reading order,
  meters fill, the sun rises in the logo); a repaint glides cards to their
  new places and brings changed values into focus; sheets slide up on
  phones and can be pulled down, come into focus on a computer, follow
  their content's height and turn into the next sheet in place; tabs and
  segments slide, menus, tooltips and toasts grow out of what opened them,
  copy buttons turn into a check, buttons waiting for the router spin;
  with reduced motion only the fades remain
- Portal: while a device is set up, a card at the top shows the way from
  it to the router with a light running along it; on the first connection
  the way fills green, the steps fold away and the sheet closes by itself.
  The first connection is the first fresh handshake, so it is no longer
  missed while the watcher catches up (or after new keys), and the device's
  card goes on to Connected
- Portal: QR codes are light dots on a black card, fuller on dense keys,
  with "Show a light code" for scanners that read only dark on light (every
  code switches, the choice is kept); the link and code a set-up sheet
  hands to another device open that device's set-up there at once
- Portal: Remove and New keys ask in a small alert with the action's icon;
  the open one of two cards is not a button; device names are no longer
  repeated in every line of the set-up sheet; the code card lines up with
  the rest of its card (a class clash gave it the page's padding); text
  keeps the arrow cursor, store badges and link buttons are not underlined
2026-10-18 23:28:10 +03:00
Aemeath fd9543ce68 Dawnline 0.7.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
- Balanced, a new disguise for AmneziaWG 2.0 apps (AmneziaVPN 4.8.12 and
  newer): junk packets, padded cookie and data packets and DNS-shaped
  signature packets, for networks that learned to spot 1.0-style junk;
  offered when both the tools and the kernel module are 2.0 or newer
- The junk count and sizes in a device's configuration are the device's own
  (shifted a little, deterministically), so two phones of one family do not
  share one profile; they never require importing again
- Components remembers which AmneziaWG build was installed on which kernel;
  after a firmware upgrade Health says the build was for the old one and
  offers the build for the new firmware. A SNAPSHOT firmware is told there are
  no builds for it
- Location lookups moved off the agent's 1-second watcher to its minute tick,
  a few per minute within a time budget; the cache lives in tmpfs and goes to
  flash hourly, and addresses still shown on the map are never pushed out of
  it (and looked up again)
- The map library from the CDN is checked against its expected hash before it
  runs inside the LuCI page
- The activity log is copied to flash only when something was logged; the
  person page and the device drawer fetch only that person's events
- Admin UI: live updates survive the theme's in-page navigation, pollers stop
  with their page and sleep while the tab is hidden, the map is freed when
  leaving the Overview, a router that stops answering is said once (and when
  it is back), and an update of Dawnline under an open page asks for a reload
- Watchdog: no repairs while an update runs; a target that keeps failing keeps
  its back-off (repairs are forgotten after ten good minutes, not one); the
  LuCI link is reloaded or restarted three times at most, not every hour for
  good; the one-click "ifup" fix accepts only Dawnline's own tunnels
- Health warns when the router's flash is nearly full (settings would stop
  saving); the portal runs two processes instead of four on routers with
  little memory
- "Remove their devices" at an end date is never done on a clock that has not
  been set yet
2026-10-18 16:04:58 +03:00
Aemeath 31a2065f05 Dawnline 0.6.0
- Access rules fail closed: when the table cannot load, no device is loaded
  into the tunnels (the firewall alone would let every loaded device reach
  everything); an older table that survived a failed rebuild keeps its rules
  and a revoked device still leaves. The agent re-syncs within a minute when
  the table is gone
- A change the router saved but could not put into effect (access rules that
  did not load, a server that refused its devices) is said in the admin UI
  instead of a plain "Saved"
- The guard judges every packet, not only a connection's first: a change of
  access, a pause or a limit now cuts open connections too
- Each server's home networks are its own: with several servers, "all home"
  on one no longer reaches the other's networks where firewall zones overlap
- People limited to some home networks reach the router only on the
  addresses in those networks (LuCI and SSH on the main LAN stay closed)
- Internet-only people can open their personal portal with the VPN on
- Tunnel DNS reaches the resolver and the LAN's DNS from servers that do not
  forward to those zones on their own (Home-only names on servers without
  "like a home device", LAN DNS on servers with no home network)
- A new personal link offers to remove the devices added through the old one,
  so a leaked link is really contained
- Import and restore refuse an inconsistent file (devices with addresses
  outside their server, shared addresses, malformed keys, broken references);
  Health reports one, and the sync leaves such a device out instead of
  failing its server. A config write that did not reach flash is an error,
  not a silent success
- Backups are kept per kind (nightly ones no longer push out manual or
  pre-delete ones), nightly and pre-change backups hold the config only,
  archives are written whole or not at all, and a failed nightly backup is
  logged. A restore no longer has its history overwritten by the agent's
  in-memory counters
- Settings defaults and ranges come from one place (dawnline.schema)
- Portal: anything not shaped like a personal link is answered by a shell
  before ucode starts (a scan on the root costs nothing); 4 portal processes
  at once instead of 16; a link may make 40 changes a quarter hour; over
  plain HTTP the page shows but configurations, new devices and new keys are
  refused with the HTTPS twin of the link; the connect sheet polls only while
  the first connection is awaited, with backoff, and stops once the link
  stopped working
- Updates: after Dawnline's own package changes, a shell checks that LuCI
  reaches it and the agent runs, and puts the kept previous version back when
  they do not (automatic runs always keep it); the AmneziaWG module reload
  verifies rmmod and modprobe; installs check free space; on apk a reinstall
  that changed nothing is an error; uninstall.sh hands the update lock to the
  removal it calls; an upgrade restarts the service only where it was
  enabled; the release workflow pins the SDK images by digest and the actions
  by commit
- AmneziaWG: features count only when both the tools and the kernel module
  have them; a server whose disguise this build cannot run (a 3.1 preset
  after a rollback to 2.0) is kept down and reported; Components tells 1.0
  builds from 2.0 ones; `awg show dump` is parsed by shape; Maximum's
  DNS-shaped signature packets are made for each server and its keep-alive
  is a 25-35 s range
- CI compiles every ucode file and runs the new tests/ucode unit tests (54
  tests on the real libuci) in OpenWrt 24.10 and 25.12 rootfs containers;
  scripts/compile-ucode.sh does the same wherever ucode runs and
  scripts/ucode-container.sh locally with docker; lint-ucode checks POSIX
  regexes and module layering; a tag builds only after CI passes
2026-10-18 15:32:27 +03:00
Aemeath 2b98abdba4 Dawnline 0.5.2
- Fixed: a new server with the Maximum disguise could not be created ("jmin=10
  (64-1024)"): the 3.1 preset's small junk packets failed Dawnline's own check
- Fixed: guesses from a shared address (every visitor behind Cloudflare) could
  lock people with valid links out of the portal for 15 minutes; a valid link
  always opens now, only wrong guesses are counted
- Fixed: a disabled Dawnline still loaded every device into the tunnels when
  netifd brought them up, with nothing enforcing end dates or limits afterwards
- Fixed: an MTU of 1380 chosen by hand was deleted on every apply (the one-time
  switch to automatic MTU now runs once)
- Locations (city lookups) are off by default on new installs: they send
  people's addresses to a third party. Routers that had them on keep them on
- "Don't warn" before an end date is honoured, and the warning window is the
  one chosen for the person on the Overview, People, the person page and the
  portal alike (People and Overview used to warn 3 days before whatever was set)
- "Ends today" and "ends tomorrow" instead of "ends in 1 day"
- Renaming a person keeps the dialog open when the router refuses the name
- Settings → Portal no longer saves a listening port its own help line marks
  as taken
- "Remove Dawnline" is live only once "remove" is typed
- Downloaded .conf files are named after the device first, and two devices
  whose names only differ past the 15th character no longer get the same file
  (and tunnel name in the app)
2026-10-18 14:42:01 +03:00
Aemeath 1a2f0b327e README: new screenshots for 0.5.1
- scripts/capture-screenshots.mjs takes the raw screenshots from a live router (headless Chromium over DevTools, 2x PNG), hides the domain with --mask and public IPs
- Overview now shows the whole connection map; the separate map screenshot is gone
- frame-screenshots.py frames 2x captures
2026-10-17 07:39:24 +03:00
Aemeath 5768856d76 Dawnline 0.5.1
Build packages / Version (push) Waiting to run
- The map places everyone within their city: the IP gives the city
  alone, so each person gets a fixed spot of their own in it (1.5-5 km
  from its centre, clear of the server and of each other)
- People who would cover each other share one plate with their avatars
  and the city once, and people on top of the server ride in the
  server's plate (no more pointers, repeated labels or counts); zooming
  in they part to their own spots
- Avatars in a plate keep their device badges (round for one device);
  a click on an avatar opens that person's card, flying to them first
  when they are elsewhere, and a click on a plate brings its people into
  view, at city level when they share one, close enough to part
- Plates follow the zoom: compact far out (small avatars, no badges or
  place names), small badges at country level, full size closer in
- Plates slide, grow and shrink smoothly: avatars glide to their places,
  "+N" changes in place, and the plate's width follows
- Fixed: a hovered person could stay highlighted (everyone else faded)
  after their plate split under the pointer
- Overview's Online tile: small avatars light up with a halo round their
  ring, and the device badge no longer cuts a dark square into the hover
2026-10-17 03:55:24 +03:00
Aemeath 972e522518 Dawnline 0.5.0
Build packages / Version (push) Waiting to run
- Where people connect from is a globe map now: live arcs from each
  person to the server, grey ones for the last 24 h, 7 or 30 days, avatars
  instead of dots, the server's own marker, and a light map in light mode;
  it zooms to fit the people shown and follows them as they come and go
- Markers that overlap move apart with a pointer to their spot; people
  next to the server fold into a count on it; a click zooms in and opens a
  floating card (never clipped by the map), closing flies back
- The person page maps where they connected from, older places fading;
  the device panel lists its places in order, and connections from the LAN
  or through the router's own address stay off the maps ("LAN" in grey)
- Setup and new servers check the UDP port (taken by another program, a
  forward or another server) and the subnet (three numbers + .x, a private
  range not in use) as you type; the default port is 4500
- The personal portal can share the server's port number (TCP beside UDP);
  its port is checked against forwards and other services
- A new server comes up at once: the kernel module is loaded and the
  network restarted when OpenWrt doesn't know AmneziaWG yet
- A turned-off server is a state of its own: no "tunnel down" or DNS
  warnings, "Turned off" in yellow, a white Turn on, and people on it are
  not shown as paused
- Pause everyone is removed: turning a server off does the same (a router
  left paused keeps its servers off after the update)
- People: a stopped person's card fades and says why across its bottom,
  with the one action that lifts it (Resume, +10 GB, Extend 1 month);
  people held by a limit or end date sort below the others, paused last
- The person page shows the state as text ("Paused") with a Resume
  button, also while their server is off
- The portal tells a paused or ended person just that, even with the
  server off, and lets them change nothing until the admin lifts it (the
  router refuses too); its notices look like Overview's
- Automatic MTU: with the field empty the tunnel, computers and routers
  get 1380 minus AmneziaWG S4 (1368 on Maximum), phones and tablets 1280;
  a typed MTU still caps phones and tablets at 1280, and servers on the
  old default 1380 move to automatic (phones and tablets get "Update
  config", their old files keep working)
- Only procd's agent runs: a second copy (started by hand or left over)
  refuses to start or is ended within 5 minutes, so no more stray paused
  and resumed events; a device that leaves the tunnel is offline at once
- The installer picks the newest release (it took the lowest), DNS
  lookups can't hang, and tooltips and floating cards close on scroll and
  on leaving the page
2026-10-17 01:03:23 +03:00
Aemeath 29b1d7dfd7 Dawnline 0.4.2
Build packages / Version (push) Waiting to run
- Connections show up at once: the agent looks at the tunnels every
  second and, the moment a device connects or roams, writes it to the
  activity log, updates traffic and the map, and locates the new address
- A device counts as gone when its WireGuard session expires (1-3 min
  after it leaves), so a phone asleep no longer flaps between
  disconnect and connect
- The admin pages follow along within seconds: Overview, People, the
  person page and the device panel refresh when something happens, with
  a light check every 2 s instead of reloading everything every 10 s
- The personal portal no longer refreshes itself in the background:
  every request costs the router a CGI process, so it loads once and
  after the visitor's own changes
- Agent guidance and code standards (backend, frontend, shell, UI) now
  live in the repository: AGENTS.md and rules/
2026-10-16 03:52:21 +03:00
Aemeath 6444722d14 Dawnline 0.4.1
Build packages / Version (push) Waiting to run
- Fixed: with a transparent proxy on the router (Clash, sing-box and
  others that mark the router's own traffic for tproxy), the portal and
  AmneziaWG answered nobody outside the LAN: their replies were diverted
  into the proxy, so visitors saw timeouts (Cloudflare 522) and devices
  could not connect from outside
- Dawnline's own answers now leave by the main table through a small nft
  table (inet dawnline_reply) that clears only the proxy's mark on them;
  it follows the proxy within a minute when one starts later, and the old
  priority-90 policy rules, which never matched, are removed
- Health's "answers reach" checks read that table, and the uninstaller
  removes it
2026-10-16 03:12:48 +03:00
Aemeath 34293fb8e5 Dawnline 0.4.0
Build packages / Version (push) Waiting to run
- Components tab replaces Updates: Dawnline, the AmneziaWG build for this
  firmware (Slava-Shchipunov 2.0 or 2Grey 3.1, Russian translation) and
  the system packages Dawnline adds, each checked, installed, reinstalled
  or rolled back in place, with What's new, versions and an activity log
- Automatic updates: daily check, install at a set time or right away,
  per component; AmneziaWG is left out by default and an automatic run
  never switches its build or generation
- Downloads verified against GitHub's sha256; mirrors are used only when
  GitHub is unreachable and the hash is known
- New installer: checks firmware, clock, space and DNS, lets you pick a
  release, shows the plan and asks first; --dry-run
- New uninstaller removes everything Dawnline added (cron, nft, firewall,
  routing, interfaces, packages it installed); --dry-run
- Works without AmneziaWG on the router: Overview, the setup wizard,
  Health and Components say what is missing and offer to install it
- Overview shows failed health checks as notices with their fix
- People list no longer reads the config from the browser: private keys
  stay on the router; personal links are fetched on demand
- Config changes are serialized under one lock, the nft table loads
  atomically and fails closed, and Dawnline never touches network
  sections it did not create
- The portal never opens system ports, keeps disabled devices disabled,
  rate-limits per address and counts days by the router's clock
- Settings and Diagnostics load their heavy parts in the background
- Release notes are written from the commits since the previous release
- Backend and admin UI split into small single-purpose modules
2026-10-16 02:14:15 +03:00
Aemeath 70a932b8ea Dawnline 0.3.1
Build packages / Version (push) Waiting to run
- Find home devices (Bonjour) removed: iOS looks for services over the
  tunnel only under a search domain, and Android and Chromecast only over
  multicast, which WireGuard does not carry. Upgrading removes its server
  option and dnsmasq records
- Home services still show the ports devices announce when umdns runs
2026-10-15 19:01:15 +03:00
Aemeath e657742b52 README: new screenshots for 0.3.0, Access added 2026-10-15 18:21:27 +03:00
Aemeath aa8256bc60 Dawnline 0.3.0
Build packages / Version (push) Waiting to run
- Access split into Internet and Home network cards; network tiles inline,
  Auto-detect LAN beside them, other interfaces folded by kind
- Devices reach each other: Off, Everyone or Circles (per server); circles
  with names, colours and members; a person's own devices always see each
  other while it is not off
- Per-person home networks: people can be kept out of some of the server's
  networks (nft lan_part set, AllowedIPs follow)
- Home services moved from Settings to Access, added from the devices the
  router sees over DHCP (ports they announce over Bonjour when umdns runs)
- Who reaches what (rules summed up per access) and Check access (walks the
  same rules as nft and the client configuration, step by step)
- Find home devices (Bonjour): umdns services published as DNS-SD records in
  dnsmasq; installs umdns from Access
- Connections from home show the DHCP name with the address in brackets
- Repaints keep the scroll position
2026-10-15 18:12:47 +03:00
Aemeath 82ab86848e Dawnline 0.2.0
- Diagnostics page: Health and Log tabs in place of Health and Activity
- Watchdog: repairs the AmneziaWG module, tunnels, nft table, firewall
  rules, uhttpd portal setting, portal, resolver and rpcd after two bad
  checks in a row, with backoff; after 3 failed repairs logs once in red,
  keeps repairing quietly and logs "restored" when it works again
- Heartbeat cron job restarts a hung agent
- Service log: tunnel and service starts with reasons (restarted, router
  start, update, crash), stops Dawnline made itself vs unexpected ones,
  certificate renewal and expiry, WAN address changes
- Admin actions logged as "You ..." with their own icon and tint; every
  event has an icon tile; names kept for removed people and devices;
  server pill on events when there are several servers
- Log filters: All, Connections, People, System, Problems; search and the
  command palette removed
- Home network reaches people's devices: fw4 forwarding from the home
  zones, limited to people with home access
- "Devices reach each other" per server, in the Access card
- Portal: "This device" card first with a dotted border, key rotation and
  copy address in the menu, devices sorted Online/Offline/Not set up/Paused,
  over-limit slots in orange
- People cards: slot bar, Online / Never connected, add chip always shown
- Person and device pages: Add device tile, Connect at the bottom with
  File/Key/QR tabs, status text without dots; pulsing server tab dot
- Server pill: Running / Not running / Turned off
2026-10-15 17:05:24 +03:00
226 changed files with 29597 additions and 10711 deletions

No files matched your search

+42 -20
View File
@@ -3,16 +3,28 @@ name: Build packages
# A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk # A tag vX.Y.Z builds luci-app-dawnline as .ipk (OpenWrt 24.10, opkg) and .apk
# (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with # (OpenWrt 25.12, apk) with the OpenWrt SDK and publishes a GitHub release with
# both packages and sha256sums.txt, the files install.sh and the in-app updater # both packages and sha256sums.txt, the files install.sh and the in-app updater
# download. Run it by hand to get the packages as workflow artifacts only. # download. The release notes list what changed since the previous tag, from the
# commits (scripts/release-notes.sh). Run it by hand to get the packages as
# workflow artifacts only.
on: on:
push: push:
tags: ['v*'] tags: ['v*']
workflow_dispatch: workflow_dispatch:
# Read-only by default; only the release job may write (publish the release).
# Everything that runs here is pinned to a digest or a commit: the packages
# it publishes are installed as root on every router with automatic updates
# on, so a re-pointed tag must not be able to change what gets built.
permissions: permissions:
contents: write contents: read
jobs: jobs:
# The same checks as on main (ci.yml), on the tag itself: nothing is built or
# published until they pass.
ci:
name: CI
uses: ./.github/workflows/ci.yml
version: version:
name: Version name: Version
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
@@ -20,7 +32,9 @@ jobs:
version: ${{ steps.version.outputs.version }} version: ${{ steps.version.outputs.version }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
persist-credentials: false
- name: Read and check the version - name: Read and check the version
id: version id: version
@@ -39,19 +53,21 @@ jobs:
build: build:
name: Build ${{ matrix.type }} name: Build ${{ matrix.type }}
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
needs: version needs: [version, ci]
strategy: strategy:
fail-fast: true fail-fast: true
matrix: matrix:
include: include:
- { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6' } - { type: ipk, sdk: 'itdoginfo/openwrt-sdk-ipk:24.10.6@sha256:a6bd28c380b251ebdb1d6d5f83e55ecb0a3c1808b5a8f4841424abc8019a903f' }
- { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3' } - { type: apk, sdk: 'itdoginfo/openwrt-sdk-apk:25.12.3@sha256:6d832008ddd1b8ec4edc84f5e6e0bf22a13ba2d6888083a8e69fa26d752c276f' }
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
persist-credentials: false
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v5 uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
with: with:
node-version: '22' node-version: '22'
cache: npm cache: npm
@@ -70,7 +86,7 @@ jobs:
run: scripts/build-packages.sh ${{ matrix.type }} run: scripts/build-packages.sh ${{ matrix.type }}
- name: Upload - name: Upload
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with: with:
name: package-${{ matrix.type }} name: package-${{ matrix.type }}
path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }} path: dist/luci-app-dawnline-${{ needs.version.outputs.version }}.${{ matrix.type }}
@@ -82,9 +98,23 @@ jobs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
needs: [version, build] needs: [version, build]
if: github.ref_type == 'tag' if: github.ref_type == 'tag'
permissions:
contents: write
steps: steps:
# The whole history and the tags: the notes list the commits since the previous tag.
- name: Checkout
uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
with:
persist-credentials: false
fetch-depth: 0
- name: Release notes
run: |
sh scripts/release-notes.sh "${GITHUB_REF_NAME}" "${GITHUB_REPOSITORY}" > notes.md
cat notes.md
- name: Download packages - name: Download packages
uses: actions/download-artifact@v4 uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with: with:
pattern: package-* pattern: package-*
path: release path: release
@@ -97,17 +127,9 @@ jobs:
cat sha256sums.txt cat sha256sums.txt
- name: Publish the release - name: Publish the release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with: with:
name: Dawnline ${{ github.ref_name }} name: Dawnline ${{ github.ref_name }}
tag_name: ${{ github.ref_name }} tag_name: ${{ github.ref_name }}
files: release/* files: release/*
generate_release_notes: true body_path: notes.md
body: |
Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk):
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh)"
```
Or upgrade from LuCI → Network → Dawnline → Updates.
+71 -14
View File
@@ -1,9 +1,12 @@
name: CI name: CI
# Every push to main and every pull request; also called by build.yml, so a
# tag never publishes a release without these checks passing on it.
on: on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
workflow_call:
permissions: permissions:
contents: read contents: read
@@ -22,6 +25,8 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v5
with:
persist-credentials: false
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v5 uses: actions/setup-node@v5
@@ -41,6 +46,7 @@ jobs:
exit 1 exit 1
fi fi
# Sources and the test files (tsconfig.test.json).
- name: Type check - name: Type check
id: types id: types
run: npm run --silent typecheck run: npm run --silent typecheck
@@ -49,12 +55,17 @@ jobs:
id: tests id: tests
run: npm test 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 - name: Build bundles and check they are committed
id: build id: build
run: | run: |
npm run --silent build npm run --silent build
if ! git diff --exit-code -- ../package; then changed="$(git status --porcelain --untracked-files=all -- ../package)"
echo "::error::The committed bundles are out of date. Run 'npm run build' in web/ and commit the result." 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."
exit 1 exit 1
fi fi
@@ -78,16 +89,28 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v5
with:
persist-credentials: false
# Every shell script by its shebang (the init script's is "/bin/sh
# /etc/rc.common"), so a new hotplug or libexec script is covered the
# day it appears. Files without a shebang (keep.d lists) are not shell.
- name: ShellCheck - name: ShellCheck
run: | run: |
shellcheck --version shellcheck --version
shellcheck -S warning \ files="$(grep -rlIE '^#!(/usr)?/bin/(sh|bash|env (sh|bash))( |$)' \
install.sh \ install.sh uninstall.sh package/luci-app-dawnline/root scripts tests | sort)"
package/luci-app-dawnline/root/etc/init.d/dawnline \ echo "$files"
package/luci-app-dawnline/root/etc/uci-defaults/90_dawnline \ for f in package/luci-app-dawnline/root/etc/init.d/dawnline \
package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \ package/luci-app-dawnline/root/etc/hotplug.d/iface/95-dawnline \
scripts/*.sh package/luci-app-dawnline/root/usr/libexec/dawnline/resolver \
package/luci-app-dawnline/root/usr/libexec/dawnline/heartbeat \
package/luci-app-dawnline/root/usr/libexec/dawnline/postupdate \
package/luci-app-dawnline/root/usr/share/dawnline/portal/www/cgi-bin/portal; do
echo "$files" | grep -qx "$f" || { echo "::error file=$f::not found by the shebang scan"; exit 1; }
done
# shellcheck disable=SC2086
shellcheck -S warning $files
ucode: ucode:
name: ucode static checks name: ucode static checks
@@ -95,21 +118,55 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v5
with:
persist-credentials: false
- name: Use before definition - name: Lint (use before definition, exports, POSIX regexes, rpcd methods)
run: python3 scripts/lint-ucode.py run: python3 scripts/lint-ucode.py
- name: Executables keep their mode - name: Executables keep their mode
run: | run: |
cd package/luci-app-dawnline/root for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver usr/libexec/dawnline/heartbeat usr/libexec/dawnline/postupdate \
for f in usr/bin/dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/libexec/dawnline/resolver \ etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal usr/share/dawnline/portal/cgi.uc; do
etc/init.d/dawnline etc/uci-defaults/90_dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do [ -x "package/luci-app-dawnline/root/$f" ] || { echo "::error file=package/luci-app-dawnline/root/$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
done
for f in scripts/check-ucode.sh scripts/compile-ucode.sh scripts/ucode-container.sh tests/ucode/run.sh tests/ucode/fixtures/bin/awg; do
[ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; } [ -x "$f" ] || { echo "::error file=$f::not executable (git update-index --chmod=+x $f)"; exit 1; }
done done
- name: Versions agree - name: Versions agree
run: | run: |
v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)" v="$(sed -n 's/^PKG_VERSION:=//p' package/luci-app-dawnline/Makefile)"
grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc grep -q "^export const VERSION = '$v';" package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc ||
grep -q "\"version\": \"$v\"" web/package.json { echo "::error::util.uc VERSION differs from the Makefile ($v)"; exit 1; }
grep -q "\"version\": \"$v\"" web/package.json ||
{ echo "::error::web/package.json version differs from the Makefile ($v)"; exit 1; }
python3 - "$v" <<'PY'
import json, sys
v = sys.argv[1]
lock = json.load(open('web/package-lock.json'))
got = (lock.get('version'), lock.get('packages', {}).get('', {}).get('version'))
if got != (v, v):
print(f"::error::web/package-lock.json says {got}, the Makefile {v}: run 'npm install' in web/")
sys.exit(1)
PY
echo "Version $v" echo "Version $v"
ucode-compile:
# scripts/compile-ucode.sh and tests/ucode on the release's own ucode and
# libuci, in the OpenWrt rootfs containers scripts/ucode-container.sh pins
# by digest (24.10 = opkg, 25.12 = apk: the two the packages are built for).
name: ucode compiles and tests pass (OpenWrt ${{ matrix.release }})
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
release: ['24.10', '25.12']
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Compile every ucode file and run tests/ucode
run: scripts/ucode-container.sh ${{ matrix.release }}
+38
View File
@@ -0,0 +1,38 @@
# AGENTS.md — Dawnline
Guidance for coding agents working in this repository (`tickcount/luci-app-dawnline`): an AmneziaWG access server for OpenWrt with a LuCI admin UI and a personal portal. `CLAUDE.md` points here.
## Rules
- `rules/code-standards.md` — how all code is written: decomposition, one locked writer, fail closed, validation at the boundary, comments and commits.
- `rules/backend.md` — ucode on the router: module layers, conventions, what things cost there (CGI portal, rpcd, the agent's watcher).
- `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.
This repo usually sits inside the router-admin workspace (`../AGENTS.md`). Its rules apply to anything that touches the router: read-only first, backup before mutating, router shell as a literal stdin heredoc over SSH (`../rules/`).
## Layout
- `package/luci-app-dawnline/root/` — what lands on the router: ucode modules in `usr/share/ucode/dawnline/` (`rpc/` for the LuCI backend), the agent and updater in `usr/libexec/dawnline/`, the portal in `usr/share/dawnline/portal/`, the init script, rpcd ACL.
- `web/` — TypeScript sources of the admin UI (`src/admin`) and the portal (`src/portal`), shared code in `src/shared`; the built bundles are committed under `package/`.
- `install.sh`, `uninstall.sh` — the standalone installer and uninstaller (both have `--dry-run`).
- `scripts/` — `lint-ucode.py`, `compile-ucode.sh` (compiles every ucode file of a tree wherever ucode runs), `check-ucode.sh` (the same on the router, without installing), `ucode-container.sh` (compile and unit tests in the OpenWrt rootfs containers CI uses), `deploy.sh` (dev deploy over SSH), `build-packages.sh`, `build-release.sh`, `release-notes.sh`.
- `tests/ucode/` — unit tests of the ucode modules (`run.uc` runs every `*.test.uc`; fixtures for `/etc/config` and a stand-in `awg`), run in a container by `run.sh`.
## Checks before a commit or deploy
- `python3 scripts/lint-ucode.py` (use before definition, exports, POSIX regexes, rpcd methods; layering notes are informational).
- `scripts/ucode-container.sh` (needs docker): compiles every ucode file and runs `tests/ucode` on OpenWrt 24.10 and 25.12, exactly what CI does. `scripts/check-ucode.sh` compiles on the router instead when there is no docker. New ucode entry points are added to the compile list in `scripts/compile-ucode.sh`, to `lint-ucode.py`, and to the executables list in `.github/workflows/ci.yml`; a pure function gets a case in `tests/ucode/<module>.test.uc`.
- In `web/`: `npm run format:check`, `npm run typecheck` (sources and tests), `npm test`, `npm run build` — and commit the rebuilt bundles (CI fails on a changed or new file under `package/`).
- `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`).
## Releases
- A release is one commit on `main` titled `Dawnline X.Y.Z`; its body is `- ` points, which become the GitHub release notes and the Components "What's new". Work from a branch is squashed into that one commit.
- Bump the version in `package/luci-app-dawnline/Makefile` (`PKG_VERSION`), `util.uc` (`VERSION`), `web/package.json` and `web/package-lock.json` (CI checks they agree).
- No `Co-Authored-By` or other agent attribution in commits.
- Push `main`, then an annotated tag `vX.Y.Z` ("Dawnline X.Y.Z"); the "Build packages" workflow publishes the `.ipk`, `.apk` and `sha256sums.txt`.
- Re-cutting a release (fixes before anyone installs) rewrites `main`: force-push, `gh release delete vX.Y.Z --cleanup-tag`, cancel a running build of the old tag, tag again. Only with the user's go-ahead.
- On the router, install a release the way Components does: `/usr/libexec/dawnline/updater install app@vX.Y.Z` (verified against the release's sha256).
+91 -25
View File
@@ -20,9 +20,9 @@ limits, live traffic and a LuCI admin that follows a modern design.
|---|---| |---|---|
| ![People](docs/screenshots/people.png) | ![Person](docs/screenshots/person.png) | | ![People](docs/screenshots/people.png) | ![Person](docs/screenshots/person.png) |
| Personal portal | Where people connect from | | Personal portal | Home network access |
|---|---| |---|---|
| ![Personal portal](docs/screenshots/portal.png) | ![Map](docs/screenshots/map.png) | | ![Personal portal](docs/screenshots/portal.png) | ![Access](docs/screenshots/access.png) |
## Features ## Features
@@ -34,14 +34,20 @@ limits, live traffic and a LuCI admin that follows a modern design.
accounts, no sessions, and a new link locks the old one out at once. People accounts, no sessions, and a new link locks the old one out at once. People
add, rename and remove their devices and get each one as a QR code, add, rename and remove their devices and get each one as a QR code,
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change "Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
access or limits. Links work on 443 with a Let's Encrypt certificate (via access or limits. Links work on the portal's own port with a Let's Encrypt
ACME), several addresses at once (a Cloudflare-proxied name, a plain IP), the certificate (via ACME), several addresses at once (a Cloudflare-proxied name,
same link at home, and wrong links can redirect to your website. a plain IP), the same link at home, and wrong links can redirect to your
website. Behind Cloudflare, pick a port it proxies (2053, 2083, 2087, 2096 or
8443).
- **Access per person**, enforced in an `inet dawnline` nftables table on the - **Access per person**, enforced in an `inet dawnline` nftables table on the
tunnel interface: home network only, internet only, or both, and optionally tunnel interface: home network only, internet only, or both, and optionally
only some home services. only some home networks or home services (picked from the devices the router
sees over DHCP). Devices of different people reach each other never, always,
or within circles (family sees family, guests see guests). "Who reaches what"
sums up the rules and "Check access" walks them step by step for a device
and an address.
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly - **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
or total data limits, allowed hours, pause one person or everyone. Devices or total data limits, allowed hours, pause anyone. Devices
drop off the tunnel at once (`awg syncconf`, no interface restart). drop off the tunnel at once (`awg syncconf`, no interface restart).
- **Disguise presets** for AmneziaWG obfuscation (junk packets, - **Disguise presets** for AmneziaWG obfuscation (junk packets,
header and padding parameters), with what each preset needs from the apps. header and padding parameters), with what each preset needs from the apps.
@@ -52,9 +58,14 @@ limits, live traffic and a LuCI admin that follows a modern design.
per-tool integration. per-tool integration.
- **Overview.** Who is online with what, speed now, today and the last 30 days, - **Overview.** Who is online with what, speed now, today and the last 30 days,
and a map of where people connect from (city level). and a map of where people connect from (city level).
- **Health** checks with one-click fixes, including the ones that matter for - **Diagnostics.** Health checks with one-click fixes, including the ones that
reaching the portal from outside (DNS, port forwards, reply routing behind matter for reaching the portal from outside (DNS, port forwards, reply
proxies such as SSClash/Mihomo, certificate coverage). routing behind proxies such as SSClash/Mihomo, certificate coverage). A
watchdog checks the tunnels, access rules, portal, resolver and LuCI link
every minute and repairs them on its own (a cron job looks after the agent
itself). One log holds people's activity and the service log: tunnel starts
and stops with netifd's reasons, repairs and errors (`dawnline log` on the
router).
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose - **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt) between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
@@ -77,17 +88,45 @@ On the router:
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)" sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
``` ```
The installer checks the firmware, installs AmneziaWG for it if needed, then The installer checks the firmware, the clock, free space and DNS, lets you pick
downloads the Dawnline package for your package manager from the latest a release (the latest is the default), shows the plan and asks before it
release, checks it against `sha256sums.txt` and installs it with its changes anything. It downloads the Dawnline package for your package manager,
dependencies. Then open **LuCI → Network → Dawnline** and run the setup wizard. checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware
if it is missing, then installs Dawnline with its dependencies and checks that
LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup
wizard.
Options: Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
and the service state to `/etc/dawnline/installer-backups/` (the newest three
are kept); if a step fails, it puts them back. Packages are not rolled back: to
return to an older release, run the installer with `--tag`. Everything it does
is logged to `/tmp/dawnline-install.log`.
With options, download it first:
```sh ```sh
sh install.sh 0.1.0 # a given release wget -O /tmp/dawnline-install.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh
DAWNLINE_AWG=grey sh install.sh # AmneziaWG from 2Grey (default: Slava-Shchipunov, then 2Grey) sh /tmp/dawnline-install.sh --dry-run # check everything, change nothing
DAWNLINE_AWG=skip sh install.sh # never install AmneziaWG sh /tmp/dawnline-install.sh -y --tag 0.3.1 # a given release, no questions
sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
```
| Option | |
|---|---|
| `-y`, `--yes` | No questions: the latest release (or `--tag`) and the recommended choices |
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same |
| `--no-awg` | Same as `--awg skip` |
When GitHub is slow or blocked, the installer retries downloads through
`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
through a mirror:
```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
``` ```
By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases): By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases):
@@ -100,8 +139,32 @@ apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # Open
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings, **Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
keys and history are kept, and a backup is made first. keys and history are kept, and a backup is made first.
**Remove**: **Settings → Remove Dawnline from this router** (keeps a backup), **Remove** on the router:
then `opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
```
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
removal (the same as **Settings → Remove Dawnline from this router**), removes
the package and cleans up what is left. AmneziaWG stays installed, since other
tunnels may use it. After installing Dawnline again, restore the backup in
**Settings → Backups**. With options, download it first:
```sh
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
sh /tmp/dawnline-uninstall.sh --dry-run
```
| Option | |
|---|---|
| `-y`, `--yes` | Do not ask for confirmation |
| `-p`, `--purge` | Also delete the configuration, keys, history and every backup (`/etc/config/dawnline`, `/etc/dawnline`); no backup is made |
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
| `-n`, `--dry-run` | Show what would be removed; change nothing |
By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then
`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
## What Dawnline changes on the router ## What Dawnline changes on the router
@@ -110,8 +173,9 @@ sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
latter a port of the LAN bridge), policy rules for the tunnel interfaces with latter a port of the LAN bridge), policy rules for the tunnel interfaces with
one routing table, a second dnsmasq instance on port 5354 one routing table, a second dnsmasq instance on port 5354
(`/var/etc/dawnline-dns.conf`) and, while the portal is on, a uhttpd instance (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check
for it. `dawnline teardown` removes all of them. and, while the portal is on, a uhttpd instance for it. `dawnline teardown`
removes all of them.
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters `/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
@@ -121,10 +185,11 @@ are kept in `/var/run/dawnline` and flushed to flash at most hourly.
``` ```
package/luci-app-dawnline/ package/luci-app-dawnline/
root/usr/share/ucode/dawnline/ ucode library (model, apply, live, ops, view, loop) root/usr/share/ucode/dawnline/ ucode library: model (core), AmneziaWG (awg), apply, live,
ops, view, loop, portal
root/usr/share/rpcd/ucode/ luci.dawnline RPC object root/usr/share/rpcd/ucode/ luci.dawnline RPC object
root/usr/libexec/dawnline/ agent (usage, limits, presence) and updater root/usr/libexec/dawnline/ agent (usage, limits, presence) and updater
root/usr/share/dawnline/portal/ portal CGI and its (minified) assets root/usr/share/dawnline/portal/ portal CGI wrapper and its (minified) assets
root/usr/bin/dawnline command line (`dawnline help`) root/usr/bin/dawnline command line (`dawnline help`)
htdocs/ LuCI views and the generated module dawnline/app.js htdocs/ LuCI views and the generated module dawnline/app.js
web/ TypeScript sources of the admin UI and the portal web/ TypeScript sources of the admin UI and the portal
@@ -142,7 +207,8 @@ scripts/lint-ucode.py # static ucode checks
scripts/check-ucode.sh root@router # compile every ucode file on a router scripts/check-ucode.sh root@router # compile every ucode file on a router
scripts/deploy.sh root@router # install the working tree (backs up configs first) scripts/deploy.sh root@router # install the working tree (backs up configs first)
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
scripts/frame-screenshots.py # frame docs/screenshots/raw/*.png for this README scripts/capture-screenshots.mjs # capture docs/screenshots/raw/*.png from a router
scripts/frame-screenshots.py # frame them for this README
``` ```
The web bundles are committed: CI fails when they are out of date. Pushing a The web bundles are committed: CI fails when they are out of date. Pushing a
Binary file not shown.

After

Width:  |  Height:  |  Size: 525 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 418 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 277 KiB

After

Width:  |  Height:  |  Size: 908 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 639 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 301 KiB

After

Width:  |  Height:  |  Size: 825 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 291 KiB

After

Width:  |  Height:  |  Size: 615 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 328 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

After

Width:  |  Height:  |  Size: 394 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 159 KiB

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

After

Width:  |  Height:  |  Size: 327 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

After

Width:  |  Height:  |  Size: 170 KiB

+1298 -104
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -6,13 +6,13 @@
include $(TOPDIR)/rules.mk include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-dawnline PKG_NAME:=luci-app-dawnline
PKG_VERSION:=0.1.1 PKG_VERSION:=0.8.0
PKG_RELEASE:=1 PKG_RELEASE:=1
PKG_LICENSE:=MIT PKG_LICENSE:=MIT
LUCI_TITLE:=Dawnline - AmneziaWG access server LUCI_TITLE:=Dawnline - AmneziaWG access server
# AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not # AmneziaWG itself (kmod-amneziawg, amneziawg-tools, luci-proto-amneziawg) is not
# in the OpenWrt feeds: install.sh and the Updates page install a build made for # in the OpenWrt feeds: install.sh and the Components page install a build made for
# the router's firmware. The portal's HTTPS needs any libustream TLS module and # the router's firmware. The portal's HTTPS needs any libustream TLS module and
# openssl-util; Settings offers to install them when the portal is turned on. # openssl-util; Settings offers to install them when the portal is turned on.
# Runtime dependencies only (control file Depends): the package ships scripts # Runtime dependencies only (control file Depends): the package ships scripts
@@ -34,6 +34,10 @@ define Package/luci-app-dawnline/conffiles
/etc/config/dawnline /etc/config/dawnline
endef endef
# /etc/dawnline (keys, backups, usage, history) survives a sysupgrade too:
# root/lib/upgrade/keep.d/dawnline-data (the package's own keep.d file is
# generated from conffiles).
define Package/luci-app-dawnline/prerm define Package/luci-app-dawnline/prerm
#!/bin/sh #!/bin/sh
[ -n "$${IPKG_INSTROOT}" ] && exit 0 [ -n "$${IPKG_INSTROOT}" ] && exit 0
@@ -41,6 +45,11 @@ define Package/luci-app-dawnline/prerm
[ "$$1" = "upgrade" ] && exit 0 [ "$$1" = "upgrade" ] && exit 0
/etc/init.d/dawnline stop 2>/dev/null /etc/init.d/dawnline stop 2>/dev/null
/usr/bin/dawnline teardown 2>/dev/null /usr/bin/dawnline teardown 2>/dev/null
# The heartbeat check would point at a removed file.
grep -qs /usr/libexec/dawnline/ /etc/crontabs/root && {
sed -i '\#/usr/libexec/dawnline/#d' /etc/crontabs/root
/etc/init.d/cron restart 2>/dev/null
}
exit 0 exit 0
endef endef
@@ -2,18 +2,28 @@
'use strict'; 'use strict';
'require baseclass'; 'require baseclass';
'require dom'; 'require dom';
'require form';
'require poll'; 'require poll';
'require rpc'; 'require rpc';
'require uci';
'require ui'; 'require ui';
var yn=Object.create;var Ft=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var _n=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty;var Ln=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var Sn=(o,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $n(t))!Mn.call(o,i)&&i!==n&&Ft(o,i,{get:()=>t[i],enumerable:!(a=kn(t,i))||a.enumerable});return o};var Tn=(o,t,n)=>(n=o!=null?yn(_n(o)):{},Sn(t||!o||!o.__esModule?Ft(n,"default",{value:o,enumerable:!0}):n,o));var Jt=Ln((Vt,Yt)=>{"use strict";var Kt=(function(){var o=function(y,D){var T=236,f=17,g=y,_=n[D],c=null,u=0,C=null,v=[],b={},j=function(M,S){u=g*4+17,c=(function(x){for(var E=new Array(x),A=0;A<x;A+=1){E[A]=new Array(x);for(var B=0;B<x;B+=1)E[A][B]=null}return E})(u),q(0,0),q(u-7,0),q(0,u-7),ee(),Z(),he(M,S),g>=7&&ie(M),C==null&&(C=yt(g,_,v)),fe(C,S)},q=function(M,S){for(var x=-1;x<=7;x+=1)if(!(M+x<=-1||u<=M+x))for(var E=-1;E<=7;E+=1)S+E<=-1||u<=S+E||(0<=x&&x<=6&&(E==0||E==6)||0<=E&&E<=6&&(x==0||x==6)||2<=x&&x<=4&&2<=E&&E<=4?c[M+x][S+E]=!0:c[M+x][S+E]=!1)},I=function(){for(var M=0,S=0,x=0;x<8;x+=1){j(!0,x);var E=i.getLostPoint(b);(x==0||M>E)&&(M=E,S=x)}return S},Z=function(){for(var M=8;M<u-8;M+=1)c[M][6]==null&&(c[M][6]=M%2==0);for(var S=8;S<u-8;S+=1)c[6][S]==null&&(c[6][S]=S%2==0)},ee=function(){for(var M=i.getPatternPosition(g),S=0;S<M.length;S+=1)for(var x=0;x<M.length;x+=1){var E=M[S],A=M[x];if(c[E][A]==null)for(var B=-2;B<=2;B+=1)for(var G=-2;G<=2;G+=1)B==-2||B==2||G==-2||G==2||B==0&&G==0?c[E+B][A+G]=!0:c[E+B][A+G]=!1}},ie=function(M){for(var S=i.getBCHTypeNumber(g),x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[Math.floor(x/3)][x%3+u-8-3]=E}for(var x=0;x<18;x+=1){var E=!M&&(S>>x&1)==1;c[x%3+u-8-3][Math.floor(x/3)]=E}},he=function(M,S){for(var x=_<<3|S,E=i.getBCHTypeInfo(x),A=0;A<15;A+=1){var B=!M&&(E>>A&1)==1;A<6?c[A][8]=B:A<8?c[A+1][8]=B:c[u-15+A][8]=B}for(var A=0;A<15;A+=1){var B=!M&&(E>>A&1)==1;A<8?c[8][u-A-1]=B:A<9?c[8][15-A-1+1]=B:c[8][15-A-1]=B}c[u-8][8]=!M},fe=function(M,S){for(var x=-1,E=u-1,A=7,B=0,G=i.getMaskFunction(S),U=u-1;U>0;U-=2)for(U==6&&(U-=1);;){for(var te=0;te<2;te+=1)if(c[E][U-te]==null){var de=!1;B<M.length&&(de=(M[B]>>>A&1)==1);var W=G(E,U-te);W&&(de=!de),c[E][U-te]=de,A-=1,A==-1&&(B+=1,A=7)}if(E+=x,E<0||u<=E){E-=x,x=-x;break}}},Te=function(M,S){for(var x=0,E=0,A=0,B=new Array(S.length),G=new Array(S.length),U=0;U<S.length;U+=1){var te=S[U].dataCount,de=S[U].totalCount-te;E=Math.max(E,te),A=Math.max(A,de),B[U]=new Array(te);for(var W=0;W<B[U].length;W+=1)B[U][W]=255&M.getBuffer()[W+x];x+=te;var me=i.getErrorCorrectPolynomial(de),ge=r(B[U],me.getLength()-1),qt=ge.mod(me);G[U]=new Array(me.getLength()-1);for(var W=0;W<G[U].length;W+=1){var Ut=W+qt.getLength()-G[U].length;G[U][W]=Ut>=0?qt.getAt(Ut):0}}for(var Gt=0,W=0;W<S.length;W+=1)Gt+=S[W].totalCount;for(var kt=new Array(Gt),st=0,W=0;W<E;W+=1)for(var U=0;U<S.length;U+=1)W<B[U].length&&(kt[st]=B[U][W],st+=1);for(var W=0;W<A;W+=1)for(var U=0;U<S.length;U+=1)W<G[U].length&&(kt[st]=G[U][W],st+=1);return kt},yt=function(M,S,x){for(var E=l.getRSBlocks(M,S),A=d(),B=0;B<x.length;B+=1){var G=x[B];A.put(G.getMode(),4),A.put(G.getLength(),i.getLengthInBits(G.getMode(),M)),G.write(A)}for(var U=0,B=0;B<E.length;B+=1)U+=E[B].dataCount;if(A.getLengthInBits()>U*8)throw"code length overflow. ("+A.getLengthInBits()+">"+U*8+")";for(A.getLengthInBits()+4<=U*8&&A.put(0,4);A.getLengthInBits()%8!=0;)A.putBit(!1);for(;!(A.getLengthInBits()>=U*8||(A.put(T,8),A.getLengthInBits()>=U*8));)A.put(f,8);return Te(A,E)};b.addData=function(M,S){S=S||"Byte";var x=null;switch(S){case"Numeric":x=h(M);break;case"Alphanumeric":x=m(M);break;case"Byte":x=p(M);break;case"Kanji":x=$(M);break;default:throw"mode:"+S}v.push(x),C=null},b.isDark=function(M,S){if(M<0||u<=M||S<0||u<=S)throw M+","+S;return c[M][S]},b.getModuleCount=function(){return u},b.make=function(){if(g<1){for(var M=1;M<40;M++){for(var S=l.getRSBlocks(M,_),x=d(),E=0;E<v.length;E++){var A=v[E];x.put(A.getMode(),4),x.put(A.getLength(),i.getLengthInBits(A.getMode(),M)),A.write(x)}for(var B=0,E=0;E<S.length;E++)B+=S[E].dataCount;if(x.getLengthInBits()<=B*8)break}g=M}j(!1,I())},b.createTableTag=function(M,S){M=M||2,S=typeof S>"u"?M*4:S;var x="";x+='<table style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: "+S+"px;",x+='">',x+="<tbody>";for(var E=0;E<b.getModuleCount();E+=1){x+="<tr>";for(var A=0;A<b.getModuleCount();A+=1)x+='<td style="',x+=" border-width: 0px; border-style: none;",x+=" border-collapse: collapse;",x+=" padding: 0px; margin: 0px;",x+=" width: "+M+"px;",x+=" height: "+M+"px;",x+=" background-color: ",x+=b.isDark(E,A)?"#000000":"#ffffff",x+=";",x+='"/>';x+="</tr>"}return x+="</tbody>",x+="</table>",x},b.createSvgTag=function(M,S,x,E){var A={};typeof arguments[0]=="object"&&(A=arguments[0],M=A.cellSize,S=A.margin,x=A.alt,E=A.title),M=M||2,S=typeof S>"u"?M*4:S,x=typeof x=="string"?{text:x}:x||{},x.text=x.text||null,Line truncated var Va=Object.create;var Eo=Object.defineProperty;var Ya=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,Xa=Object.prototype.hasOwnProperty;var ei=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ti=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Za(e))!Xa.call(n,a)&&a!==o&&Eo(n,a,{get:()=>e[a],enumerable:!(r=Ya(e,a))||r.enumerable});return n};var ni=(n,e,o)=>(o=n!=null?Va(Qa(n)):{},ti(e||!n||!n.__esModule?Eo(o,"default",{value:n,enumerable:!0}):o,n));var Qo=ei((Yo,Zo)=>{"use strict";var Vo=(function(){var n=function(x,v){var $=236,E=17,y=x,z=o[v],h=null,f=0,T=null,S=[],N={},G=function(P,D){f=y*4+17,h=(function(_){for(var B=new Array(_),M=0;M<_;M+=1){B[M]=new Array(_);for(var j=0;j<_;j+=1)B[M][j]=null}return B})(f),q(0,0),q(f-7,0),q(0,f-7),J(),R(),le(P,D),y>=7&&Q(P),T==null&&(T=ne(y,z,S)),he(T,D)},q=function(P,D){for(var _=-1;_<=7;_+=1)if(!(P+_<=-1||f<=P+_))for(var B=-1;B<=7;B+=1)D+B<=-1||f<=D+B||(0<=_&&_<=6&&(B==0||B==6)||0<=B&&B<=6&&(_==0||_==6)||2<=_&&_<=4&&2<=B&&B<=4?h[P+_][D+B]=!0:h[P+_][D+B]=!1)},V=function(){for(var P=0,D=0,_=0;_<8;_+=1){G(!0,_);var B=a.getLostPoint(N);(_==0||P>B)&&(P=B,D=_)}return D},R=function(){for(var P=8;P<f-8;P+=1)h[P][6]==null&&(h[P][6]=P%2==0);for(var D=8;D<f-8;D+=1)h[6][D]==null&&(h[6][D]=D%2==0)},J=function(){for(var P=a.getPatternPosition(y),D=0;D<P.length;D+=1)for(var _=0;_<P.length;_+=1){var B=P[D],M=P[_];if(h[B][M]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[B+j][M+Z]=!0:h[B+j][M+Z]=!1}},Q=function(P){for(var D=a.getBCHTypeNumber(y),_=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[Math.floor(_/3)][_%3+f-8-3]=B}for(var _=0;_<18;_+=1){var B=!P&&(D>>_&1)==1;h[_%3+f-8-3][Math.floor(_/3)]=B}},le=function(P,D){for(var _=z<<3|D,B=a.getBCHTypeInfo(_),M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<6?h[M][8]=j:M<8?h[M+1][8]=j:h[f-15+M][8]=j}for(var M=0;M<15;M+=1){var j=!P&&(B>>M&1)==1;M<8?h[8][f-M-1]=j:M<9?h[8][15-M-1+1]=j:h[8][15-M-1]=j}h[f-8][8]=!P},he=function(P,D){for(var _=-1,B=f-1,M=7,j=0,Z=a.getMaskFunction(D),Y=f-1;Y>0;Y-=2)for(Y==6&&(Y-=1);;){for(var ce=0;ce<2;ce+=1)if(h[B][Y-ce]==null){var xe=!1;j<P.length&&(xe=(P[j]>>>M&1)==1);var ee=Z(B,Y-ce);ee&&(xe=!xe),h[B][Y-ce]=xe,M-=1,M==-1&&(j+=1,M=7)}if(B+=_,B<0||f<=B){B-=_,_=-_;break}}},ue=function(P,D){for(var _=0,B=0,M=0,j=new Array(D.length),Z=new Array(D.length),Y=0;Y<D.length;Y+=1){var ce=D[Y].dataCount,xe=D[Y].totalCount-ce;B=Math.max(B,ce),M=Math.max(M,xe),j[Y]=new Array(ce);for(var ee=0;ee<j[Y].length;ee+=1)j[Y][ee]=255&P.getBuffer()[ee+_];_+=ce;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[Y],De.getLength()-1),ko=Ae.mod(De);Z[Y]=new Array(De.getLength()-1);for(var ee=0;ee<Z[Y].length;ee+=1){var $o=ee+ko.getLength()-Z[Y].length;Z[Y][ee]=$o>=0?ko.getAt($o):0}}for(var Co=0,ee=0;ee<D.length;ee+=1)Co+=D[ee].totalCount;for(var On=new Array(Co),Qt=0,ee=0;ee<B;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<j[Y].length&&(On[Qt]=j[Y][ee],Qt+=1);for(var ee=0;ee<M;ee+=1)for(var Y=0;Y<D.length;Y+=1)ee<Z[Y].length&&(On[Qt]=Z[Y][ee],Qt+=1);return On},ne=function(P,D,_){for(var B=l.getRSBlocks(P,D),M=c(),j=0;j<_.length;j+=1){var Z=_[j];M.put(Z.getMode(),4),M.put(Z.getLength(),a.getLengthInBits(Z.getMode(),P)),Z.write(M)}for(var Y=0,j=0;j<B.length;j+=1)Y+=B[j].dataCount;if(M.getLengthInBits()>Y*8)throw"code length overflow. ("+M.getLengthInBits()+">"+Y*8+")";for(M.getLengthInBits()+4<=Y*8&&M.put(0,4);M.getLengthInBits()%8!=0;)M.putBit(!1);for(;!(M.getLengthInBits()>=Y*8||(M.put($,8),M.getLengthInBits()>=Y*8));)M.put(E,8);return ue(M,B)};N.addData=function(P,D){D=D||"Byte";var _=null;switch(D){case"Numeric":_=d(P);break;case"Alphanumeric":_=p(P);break;case"Byte":_=u(P);break;case"Kanji":_=w(P);break;default:throw"mode:"+D}S.push(_),T=null},N.isDark=function(P,D){if(P<0||f<=P||D<0||f<=D)throw P+","+D;return h[P][D]},N.getModuleCount=function(){return f},N.make=function(){if(y<1){for(var P=1;P<40;P++){for(var D=l.getRSBlocks(P,z),_=c(),B=0;B<S.length;B++){var M=S[B];_.put(M.getMode(),4),_.put(M.getLength(),a.getLengthInBits(M.getMode(),P)),M.write(_)}for(var j=0,B=0;B<D.length;B++)j+=D[B].dataCount;if(_.getLengthInBits()<=j*8)break}y=P}G(!1,V())},N.createTableTag=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _="";_+='<table style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: "+D+"px;",_+='">',_+="<tbody>";for(var B=0;B<N.getModuleCount();B+=1){_+="<tr>";for(var M=0;M<N.getModuleCount();M+=1)_+='<td style="',_+=" border-width: 0px; border-style: none;",_+=" border-collapse: collapse;",_+=" padding: 0px; margin: 0px;",_+=" width: "+P+"px;",_+=" height: "+P+"px;",_+=" background-color: ",_+=N.isDark(B,M)?"#000000":"#ffffff",_+=";",_+='"/>';_+="</tr>"}return _+="</tbody>",_+="</table>",_},N.createSvgTag=function(P,D,_,B){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,B=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{Line truncated
`}return x%2&&M>0?ge.substring(0,ge.length-x-1)+Array(x+1).join("▀"):ge.substring(0,ge.length-1)};return b.createASCII=function(M,S){if(M=M||1,M<2)return se(S);M-=1,S=typeof S>"u"?M*2:S;var x=b.getModuleCount()*M+S*2,E=S,A=x-S,B,G,U,te,de=Array(M+1).join("██"),W=Array(M+1).join(" "),me="",ge="";for(B=0;B<x;B+=1){for(U=Math.floor((B-E)/M),ge="",G=0;G<x;G+=1)te=1,E<=G&&G<A&&E<=B&&B<A&&b.isDark(U,Math.floor((G-E)/M))&&(te=0),ge+=te?de:W;for(U=0;U<M;U+=1)me+=ge+` `}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return F(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,B=D,M=_-D,j,Z,Y,ce,xe=Array(P+1).join("██"),ee=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(Y=Math.floor((j-B)/P),Ae="",Z=0;Z<_;Z+=1)ce=1,B<=Z&&Z<M&&B<=j&&j<M&&N.isDark(Y,Math.floor((Z-B)/P))&&(ce=0),Ae+=ce?xe:ee;for(Y=0;Y<P;Y+=1)De+=Ae+`
`}return me.substring(0,me.length-1)},b.renderTo2dContext=function(M,S){S=S||2;for(var x=b.getModuleCount(),E=0;E<x;E++)for(var A=0;A<x;A++)M.fillStyle=b.isDark(E,A)?"black":"white",M.fillRect(E*S,A*S,S,S)},b};o.stringToBytesFuncs={default:function(y){for(var D=[],T=0;T<y.length;T+=1){var f=y.charCodeAt(T);D.push(f&255)}return D}},o.stringToBytes=o.stringToBytesFuncs.default,o.createStringToBytes=function(y,D){var T=(function(){for(var g=Y(y),_=function(){var Z=g.read();if(Z==-1)throw"eof";return Z},c=0,u={};;){var C=g.read();if(C==-1)break;var v=_(),b=_(),j=_(),q=String.fromCharCode(C<<8|v),I=b<<8|j;u[q]=I,c+=1}if(c!=D)throw c+" != "+D;return u})(),f=63;return function(g){for(var _=[],c=0;c<g.length;c+=1){var u=g.charCodeAt(c);if(u<128)_.push(u);else{var C=T[g.charAt(c)];typeof C=="number"?(C&255)==C?_.push(C):(_.push(C>>>8),_.push(C&255)):_.push(f)}}return _}};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},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},i=(function(){var y=[[],[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]],D=1335,T=7973,f=21522,g={},_=function(c){for(var u=0;c!=0;)u+=1,c>>>=1;return u};return g.getBCHTypeInfo=function(c){for(var u=c<<10;_(u)-_(D)>=0;)u^=D<<_(u)-_(D);return(c<<10|u)^f},g.getBCHTypeNumber=function(c){for(var u=c<<12;_(u)-_(T)>=0;)u^=T<<_(u)-_(T);return c<<12|u},g.getPatternPosition=function(c){return y[c-1]},g.getMaskFunction=function(c){switch(c){case a.PATTERN000:return function(u,C){return(u+C)%2==0};case a.PATTERN001:return function(u,C){return u%2==0};case a.PATTERN010:return function(u,C){return C%3==0};case a.PATTERN011:return function(u,C){return(u+C)%3==0};case a.PATTERN100:return function(u,C){return(Math.floor(u/2)+Math.floor(C/3))%2==0};case a.PATTERN101:return function(u,C){return u*C%2+u*C%3==0};case a.PATTERN110:return function(u,C){return(u*C%2+u*C%3)%2==0};case a.PATTERN111:return function(u,C){return(u*C%3+(u+C)%2)%2==0};default:throw"bad maskPattern:"+c}},g.getErrorCorrectPolynomial=function(c){for(var u=r([1],0),C=0;C<c;C+=1)u=u.multiply(r([1,s.gexp(C)],0));return u},g.getLengthInBits=function(c,u){if(1<=u&&u<10)switch(c){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:"+c}else if(u<27)switch(c){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:"+c}else if(u<41)switch(c){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:"+c}else throw"type:"+u},g.getLostPoint=function(c){for(var u=c.getModuleCount(),C=0,v=0;v<u;v+=1)for(var b=0;b<u;b+=1){for(var j=0,q=c.isDark(v,b),I=-1;I<=1;I+=1)if(!(v+I<0||u<=v+I))for(var Z=-1;Z<=1;Z+=1)b+Z<0||u<=b+Z||I==0&&Z==0||q==c.isDark(v+I,b+Z)&&(j+=1);j>5&&(C+=3+j-5)}for(var v=0;v<u-1;v+=1)for(var b=0;b<u-1;b+=1){var ee=0;c.isDark(v,b)&&(ee+=1),c.isDark(v+1,b)&&(ee+=1),c.isDark(v,b+1)&&(ee+=1),c.isDark(v+1,b+1)&&(ee+=1),(ee==0||ee==4)&&(C+=3)}for(var v=0;v<u;v+=1)for(var b=0;b<u-6;b+=1)c.isDark(v,b)&&!c.isDark(v,b+1)&&c.isDark(v,b+2)&&c.isDark(v,b+3)&&c.isDark(v,b+4)&&!c.isDark(v,b+5)&&c.isDark(v,b+6)&&(C+=40);for(var b=0;b<u;b+=1)for(var v=0;v<u-6;v+=1)c.isDark(v,b)&&!c.isDark(v+1,b)&&c.isDark(v+2,b)&&c.isDark(v+3,b)&&c.isDark(v+4,b)&&!c.isDark(v+5,b)&&c.isDark(v+6,b)&&(C+=40);for(var ie=0,b=0;b<u;b+=1)for(var v=0;v<u;v+=1)c.isDark(v,b)&&(ie+=1);var he=Math.abs(100*ie/u/u-50)/5;return C+=he*10,C},g})(),s=(function(){for(var y=new Array(256),D=new Array(256),T=0;T<8;T+=1)y[T]=1<<T;for(var T=8;T<256;T+=1)y[T]=y[T-4]^y[T-5]^y[T-6]^y[T-8];for(var T=0;T<255;T+=1)D[y[T]]=T;var f={};return f.glog=function(g){if(g<1)throw"glog("+g+")";return D[g]},f.gexp=function(g){for(;g<0;)g+=255;for(;g>=256;)g-=255;return y[g]},f})();function r(y,D){if(typeof y.length>"u")throw y.length+"/"+D;var T=(function(){for(var g=0;g<y.length&&y[g]==0;)g+=1;for(var _=new Array(y.length-g+D),c=0;c<y.length-g;c+=1)_[c]=y[c+g];return _})(),f={};return f.getAt=function(g){return T[g]},f.getLength=function(){return T.length},f.multiply=function(g){for(var _=new Array(f.getLength()+g.getLength()-1),c=0;c<f.getLength();c+=1)for(var u=0;u<g.getLength();u+=1)_[c+u]^=s.gexp(s.glog(f.getAt(c))+s.glog(g.getAt(u)));return r(_,0)},f.mod=function(g){if(f.g Line truncated `}return De.substring(0,De.length-1)},N.renderTo2dContext=function(P,D){D=D||2;for(var _=N.getModuleCount(),B=0;B<_;B++)for(var M=0;M<_;M++)P.fillStyle=N.isDark(B,M)?"black":"white",P.fillRect(B*D,M*D,D,D)},N};n.stringToBytesFuncs={default:function(x){for(var v=[],$=0;$<x.length;$+=1){var E=x.charCodeAt($);v.push(E&255)}return v}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(x,v){var $=(function(){for(var y=m(x),z=function(){var R=y.read();if(R==-1)throw"eof";return R},h=0,f={};;){var T=y.read();if(T==-1)break;var S=z(),N=z(),G=z(),q=String.fromCharCode(T<<8|S),V=N<<8|G;f[q]=V,h+=1}if(h!=v)throw h+" != "+v;return f})(),E=63;return function(y){for(var z=[],h=0;h<y.length;h+=1){var f=y.charCodeAt(h);if(f<128)z.push(f);else{var T=$[y.charAt(h)];typeof T=="number"?(T&255)==T?z.push(T):(z.push(T>>>8),z.push(T&255)):z.push(E)}}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},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var x=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,$=7973,E=21522,y={},z=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return y.getBCHTypeInfo=function(h){for(var f=h<<10;z(f)-z(v)>=0;)f^=v<<z(f)-z(v);return(h<<10|f)^E},y.getBCHTypeNumber=function(h){for(var f=h<<12;z(f)-z($)>=0;)f^=$<<z(f)-z($);return h<<12|f},y.getPatternPosition=function(h){return x[h-1]},y.getMaskFunction=function(h){switch(h){case r.PATTERN000:return function(f,T){return(f+T)%2==0};case r.PATTERN001:return function(f,T){return f%2==0};case r.PATTERN010:return function(f,T){return T%3==0};case r.PATTERN011:return function(f,T){return(f+T)%3==0};case r.PATTERN100:return function(f,T){return(Math.floor(f/2)+Math.floor(T/3))%2==0};case r.PATTERN101:return function(f,T){return f*T%2+f*T%3==0};case r.PATTERN110:return function(f,T){return(f*T%2+f*T%3)%2==0};case r.PATTERN111:return function(f,T){return(f*T%3+(f+T)%2)%2==0};default:throw"bad maskPattern:"+h}},y.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),T=0;T<h;T+=1)f=f.multiply(s([1,i.gexp(T)],0));return f},y.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},y.getLostPoint=function(h){for(var f=h.getModuleCount(),T=0,S=0;S<f;S+=1)for(var N=0;N<f;N+=1){for(var G=0,q=h.isDark(S,N),V=-1;V<=1;V+=1)if(!(S+V<0||f<=S+V))for(var R=-1;R<=1;R+=1)N+R<0||f<=N+R||V==0&&R==0||q==h.isDark(S+V,N+R)&&(G+=1);G>5&&(T+=3+G-5)}for(var S=0;S<f-1;S+=1)for(var N=0;N<f-1;N+=1){var J=0;h.isDark(S,N)&&(J+=1),h.isDark(S+1,N)&&(J+=1),h.isDark(S,N+1)&&(J+=1),h.isDark(S+1,N+1)&&(J+=1),(J==0||J==4)&&(T+=3)}for(var S=0;S<f;S+=1)for(var N=0;N<f-6;N+=1)h.isDark(S,N)&&!h.isDark(S,N+1)&&h.isDark(S,N+2)&&h.isDark(S,N+3)&&h.isDark(S,N+4)&&!h.isDark(S,N+5)&&h.isDark(S,N+6)&&(T+=40);for(var N=0;N<f;N+=1)for(var S=0;S<f-6;S+=1)h.isDark(S,N)&&!h.isDark(S+1,N)&&h.isDark(S+2,N)&&h.isDark(S+3,N)&&h.isDark(S+4,N)&&!h.isDark(S+5,N)&&h.isDark(S+6,N)&&(T+=40);for(var Q=0,N=0;N<f;N+=1)for(var S=0;S<f;S+=1)h.isDark(S,N)&&(Q+=1);var le=Math.abs(100*Q/f/f-50)/5;return T+=le*10,T},y})(),i=(function(){for(var x=new Array(256),v=new Array(256),$=0;$<8;$+=1)x[$]=1<<$;for(var $=8;$<256;$+=1)x[$]=x[$-4]^x[$-5]^x[$-6]^x[$-8];for(var $=0;$<255;$+=1)v[x[$]]=$;var E={};return E.glog=function(y){if(y<1)throw"glog("+y+")";return v[y]},E.gexp=function(y){for(;y<0;)y+=255;for(;y>=256;)y-=255;return x[y]},E})();function s(x,v){if(typeof x.length>"u")throw x.length+"/"+v;var $=(function(){for(var y=0;y<x.length&&x[y]==0;)y+=1;for(var z=new Array(x.length-y+v),h=0;h<x.length-y;h+=1)z[h]=x[h+y];return z})(),E={};return E.getAt=function(y){return $[y]},E.getLength=function(){return $.length},E.multiply=function(y){for(var z=new Array(E.getLength()+y.getLength()-1),h=0;h<E.getLength();h+=1)for(var f=0;f<y.getLength();f+=1)z[h+f]^=i.gexp(i.glog(E.getAt(h))+i.glog(y.getAt(f)));return s(z,0)},E.mod=function(y){if(E.getLength() Line truncated
`),hostName:s,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(r),port:String(n.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:s};return n.dns[0]&&(l.dns1=n.dns[0]),n.dns[1]&&(l.dns2=n.dns[1]),l}function On(o){let t="";for(let n=0;n<o.length;n+=32768)t+=String.fromCharCode(...o.subarray(n,n+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qn(o){let t=globalThis;if(typeof t.CompressionStream>"u")return null;try{let n=new t.Blob([o]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(n).arrayBuffer()),i=new Uint8Array(4+a.length);return new DataView(i.buffer).setUint32(0,o.length,!1),i.set(a,4),i}catch{return null}}async function Zt(o,t,n=!0){let a=new TextEncoder().encode(JSON.stringify(jn(o,t))),i=n?await qn(a):null;return`vpn://${On(i??a)}`}function V(o){if(!o||o<0)return"0 B";let t=["B","KB","MB","GB","TB"],n=0,a=o;for(;a>=1024&&n<t.length-1;)a/=1024,n++;return`${a>=100||n===0?Math.round(a):a.toFixed(1)} ${t[n]}`}function $e(o){let t=o*8;return t<1e3?`${Math.round(t)} bit/s`:t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)} kbit/s`:t<1e9?`${(t/1e6).toFixed(t<1e7?1:0)} Mbit/s`:`${(t/1e9).toFixed(1)} Gbit/s`}function ce(o,t=Date.now()/1e3){if(!o)return"never";let n=Math.max(0,Math.round(t-o));return n<60?"just now":n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<86400*30?`${Math.floor(n/86400)} d ago`:new Date(o*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Xt(o){if(!o||o<0)return"—";let t=Math.floor(o/86400),n=Math.floor(o%86400/3600),a=Math.floor(o%3600/60);return t?`${t}d ${n}h`:n?`${n}h ${a}m`:`${a}m`}function St(o){let t=new Date(o*1e3),n=new Date,a=t.toDateString()===n.toDateString(),i=t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return a?i:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${i}`}function _e(o){if(!o)return"";let[t,n,a]=o.split("-").map(Number);return new Date(t,n-1,a).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function ze(o,t=Date.now()){if(!o)return null;let[n,a,i]=o.split("-").map(Number),s=new Date(n,a-1,i,23,59,59).getTime();return Math.ceil((s-t)/864e5)}var je={lan:"Home network",internet:"Internet",both:"Home network + Internet"},en={lan:"LAN",internet:"Internet",both:"LAN + Internet"},tn=["computer","phone","tablet","router","other"],Me={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Tt={active:"Active",paused:"Paused",paused_all:"Paused (everyone)",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server"};function Le(o){let t=o.trim().split(/\s+/).filter(Boolean);if(!t.length)return"?";let n=t[0][0]??"",a=t.length>1?t[t.length-1][0]??"":t[0][1]??"";return(n+a).toUpperCase()}var Ne=null;function le(o,t){let n=a=>{Ne??(Ne=document.body.appendChild(e("div",{class:"dl-tip dl-tip-float dl-root"}))),Ne.replaceChildren(...t().map(i=>typeof i=="string"?document.createTextNode(i):i)),Ne.style.display="",Ne.style.left=`${a.clientX}px`,Ne.style.top=`${a.clientY-10}px`};o.addEventListener("mouseenter",n),o.addEventListener("mousemove",n),o.addEventListener("mouseleave",()=>Ne&&(Ne.style.display="none"))}function nn(o,t=120,n=26){let a=Math.max(1,...o),i=e("div",{class:"dl-spark"});i.style.width=`${t}px`,i.style.height=`${n}px`;let s=Date.now();return o.forEach((r,l)=>{let d=e("i");d.style.height=`${Math.max(6,r/a*100)}%`,r||d.classList.add("zero");let h=o.length-1-l,m=new Date(s-h*864e5);le(d,()=>[e("div",{class:"dl-tip-title"},h===0?"Today":h===1?"Yesterday":m.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),e("div",{class:"dl-muted"},V(r))]),i.appendChild(d)}),i}var Un={connect:"connections",disconnect:"connections",roam:"connections",device_added:"devices",device_removed:"devices",devices_removed:"devices",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",paused_all:"people",resumed_all:"people",server_down:"problems",server_up:"problems",portal_blocked:"problems"},Oe=["connections","devices","people","problems"],qe={connections:"Connections",devices:"Devices",people:"People",problems:"Problems"},an={connections:"Connects, disconnects and IP changes",devices:"Devices added and removed",people:"People added, changed, paused",problems:"Tunnel down, blocked portal sign-ins"},rt=o=>Un[o]??"problems";function Gn(o){let t=new Map(o.people.map(a=>[a.id,a.name])),n=new Map(o.people.flatMap(a=>a.devices.map(i=>[i.id,i.name])));return{people:t,devices:n}}function Fn(o){let t=o==null?"":String(o);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function be(o,t,n,a=""){let i=Gn(o),s=t. Line truncated `)}function $i(n){let e=new Map(n.people.map(r=>[r.id,r.name])),o=new Map(n.people.flatMap(r=>r.devices.map(a=>[a.id,a.name])));return{people:e,devices:o}}function Fe(n,e,o,r="",a=[]){let i=$i(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
`);ve(l,h,"text/csv")}var Wn=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]];function Ee(o,t,n,a,i){let s=e("select",{class:"cbi-input-select"},[e("option",{value:""},"All categories"),...Oe.map(l=>e("option",{value:l,selected:l===i?"selected":null},qe[l]))]),r=e("select",{class:"cbi-input-select"},Wn.map(([l,d])=>e("option",{value:l},d)));ne(o,[e("p",{class:"dl-muted"},`${t} This cannot be undone; export first if you want a copy.`),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Category"),s]),e("label",{class:"dl-fld"},[e("span",{class:"dl-fld-label"},"Which events"),r])],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",N("Clear",async()=>{let l=await O(()=>P.logsClear({...n,category:s.value,older_days:r.value}));l&&(J(),X(l.removed?`${l.removed} event${l.removed===1?"":"s"} removed`:"Nothing matched","success",3e3),a())},"negative")])}function Ue(o,t,n,a){let i=o==="device"?`Clears ${n}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:o==="person"?`Clears ${n}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ne(o==="all"?"Reset all traffic history?":`Reset traffic history for ${n}?`,[e("p",{class:"dl-muted"},i)],[e("button",{class:"cbi-button cbi-button-neutral",click:J},"Cancel")," ",N("Reset",async()=>{await O(()=>P.usageClear(o,t),"Traffic history reset")&&(J(),a())},"negative")])}var lt=null;function Kn(o){return o?new Date(o*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function on(o,t,n=!0){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},o),e("button",{type:"button",class:`dl-kvrow-v copy${n?" dl-mono":""}`,title:"Copy",click:()=>re(t,`${o} copied`)},[e("span",{},t),w("copy")])])}function dt(o,t){return e("div",{class:"dl-kvrow"},[e("span",{class:"dl-kvrow-k"},o),e("span",{class:"dl-kvrow-v"},t)])}function sn(o,t){if(/^\s*\[.+\]\s*$/.test(o))return e("span",{class:"dl-conf-sec"},o);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(o);if(!n)return document.createTextNode(o);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(o);return e("span",{},[e("span",{class:"dl-conf-k"},n[1])," ",a&&!t?e("span",{class:"dl-conf-mask"},"••••••••••••••••"):n[2]])}function Vn(o){let t=!1,n=e("pre",{class:"dl-conf"}),a=()=>dom.content(n,o.conf.split(` ${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${r?`-${r}`:""}-${l}.${o}`;if(o==="json"){Se(c,JSON.stringify(s,null,2),"application/json");return}Se(c,rr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ci=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],ar=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,o,r,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Et.map(c=>t("option",{value:c,selected:c===a?"selected":null},pt[c])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ci.map(([c,d])=>t("option",{value:c},d)));te(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ae()," ",H("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await A.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){U(be(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await A.serviceLogClear(l.value)).removed}catch(d){oe(),U(`${s.value==="system"?"":`Activity: ${ar(c).toLowerCase()}. `}The service log was not cleared: ${be(d)}`,"error",1e4),r();return}oe(),U(ar(c),"success",3e3),r()},"negative")])}function Lt(n,e,o,r){let a=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";te(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},a)],[ae()," ",H("Reset",async()=>{await W(()=>A.usageClear(n,e),"Traffic history reset")&&(oe(),r())},"negative")])}function ve(n,e,o){let r=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!r.classList.contains("on");Qn(r,a),o?.(a)}},t("i"));return r}function Qn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let r=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),a=()=>r.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===r.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)r.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==r.dataset.value&&(o.optimistic!==!1&&(r.dataset.value=i,a()),o.onChange?.(i))}},s));return a(),r}function qe(n,e,o,r={}){return t("button",{type:"button",...r,class:`dl-chipbtn${e?" on":""}${r.class?` ${r.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function pn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function ie(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Ei={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:""},Li={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 Mi(n){let e={};for(let[o,r]of Object.entries(Li))n[o]!=null&&n[o]!==""&&(e[r]=String(n[o]));return e}function Ti(n,e){let o=n.amnezia,r=o.obfuscation??{},a=c=>r[c]!=null&&r[c]!==""?String(r[c]):Ei[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Mi(r),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
`).flatMap((r,l)=>l?[` `),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function Si(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 _i(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(o).arrayBuffer()),a=new Uint8Array(4+r.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(r,4),a}catch{return null}}async function Xn(n,e,o=!0){let r=new TextEncoder().encode(JSON.stringify(Ti(n,e))),a=o?await _i(r):null;return`vpn://${Si(a??r)}`}var sr=[{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"}],jt=n=>sr.find(e=>e.id===n),un=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Pi={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Di={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ir(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function mn(n,e,o,r,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,sr.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},b(l.ic)),t("b",{},l.title),l.id===r?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[ir(l.stealth,"Stealth"),ir(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Pi:Di)[l.needs])])])}));return s(),i}function lr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var dr=[["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 Ai(n){let e=d=>n[d]!=null&&n[d]!=="",o=dr.filter(([d])=>e(d));if(!o.length)return null;let r=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),a=(d,p,u,w)=>{let C=dr.filter(([g])=>w.includes(g)&&e(g));return C.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},C.map(([g,m])=>r(g,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
`,sn(r,t)]:[sn(r,t)])),i=e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),t=!t,dom.content(i,[w(t?"x":"key"),t?"Hide key":"Show key"]),a()}},[w("key"),"Show key"]);a();let s=new Blob([o.conf]).size;return e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-filecard"},[e("span",{class:"dl-filecard-ic"},".conf"),e("span",{class:"dl-stack"},[e("span",{class:"dl-mono dl-ellipsis"},o.filename),e("span",{class:"dl-sub"},`AmneziaWG · ${s} bytes · import it in the app`)]),N([w("download")," Download"],()=>ve(o.filename,o.conf,"application/octet-stream"),"positive")]),e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Configuration"),e("span",{class:"dl-spacer"}),i,e("button",{type:"button",class:"dl-chipbtn",click:r=>{r.preventDefault(),re(o.conf,"Configuration copied")}},[w("copy"),"Copy"])]),n])])}async function Et(o){if(!o.has_private_key)return e("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let t=await Zt(o,`${o.server} · ${o.person} · ${o.name}`),n={qr:()=>e("div",{class:"dl-qr-pane"},[Pe(Be(o.conf),"dl-qr"),e("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>e("div",{class:"dl-stack gap8"},[e("div",{class:"dl-linkbox"},[e("span",{class:"dl-mono"},t),N("Copy",()=>re(t,"Key copied"))]),e("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Vn(o)},a=e("div",{class:"dl-connect-body"}),i=e("div",{class:"dl-seg"}),s=r=>{i.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.id===r)),dom.content(a,n[r]())};for(let[r,l]of[["qr","QR code"],["key","Key"],["file","File"]])i.appendChild(e("button",{type:"button","data-id":r,click:()=>s(r)},l));return s("qr"),e("div",{class:"dl-stack gap12"},[i,a])}function Yn(o,t,n,a){lt?.close();let i=e("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[e("div",{class:"dl-drawer-head"},[o,e("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>l()},w("x"))]),e("div",{class:"dl-drawer-body"},t),n?e("div",{class:"dl-drawer-foot"},n):""]),s=e("div",{class:"dl-drawer-overlay dl-root",click:h=>{h.target===s&&l()}},i),r=h=>{h.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&l()};function l(){document.removeEventListener("keydown",r),s.classList.remove("open"),setTimeout(()=>s.remove(),220),lt===d&&(lt=null),a()}let d={close:l,panel:i};return document.addEventListener("keydown",r),document.body.appendChild(s),requestAnimationFrame(()=>s.classList.add("open")),lt=d,d}var rn={connect:["ok","Connected"],disconnect:["","Went offline"],roam:["","Changed network"],device_added:["accent","Added"],device_removed:["","Removed"]};function Jn(o,t){let n=o.filter(a=>a.device===t&&rn[a.type]).reverse().slice(0,12);return n.length?e("div",{class:"dl-dev-log"},n.map(a=>{let[i,s]=rn[a.type],r=a.type==="connect"?[a.detail?e("span",{class:"dl-mono"},` ${a.detail}`):"",a.where?e("span",{class:"dl-faint"},` · ${a.where}`):""]:a.type==="roam"?[e("span",{class:"dl-mono dl-faint"},` ${a.detail??""}`)]:a.type==="device_added"?[e("span",{class:"dl-faint"},(a.detail??"").includes("(portal)")?" from the portal":" by you")]:[],l=new Date(a.ts*1e3);return e("div",{class:"dl-dev-log-row"},[e("span",{class:`dl-ev-dot ${i}`}),e("span",{class:"dl-row-main"},[e("span",{},s),...r]),e("span",{class:"dl-faint dl-nowrap",title:l.toLocaleString()},ce(a.ts))])})):e("div",{class:"dl-sub"},"No activity yet.")}function Qn(o){return o.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):o.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online from ${o.endpoint}`]):o.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(o.handshake)}`]):e("span",{class:"dl-dstat warn"},[e("i",{class:"dot warn"}),"Waiting for the first connection"])}async function Ce(o,t,n,a){let i=await O(()=>P.deviceConfig(t.id));if(!i)return;let s=t,r=o,l=await Et(i),d=e("div",{class:"dl-drawer-title"}),h=e("div",{}),m=e("div",{}),p=e("div",{class:"dl-live"}),$=e("div",{},e("div",{class:"dl-sub"},"Loading…")),k=[],z=async()=>{let g=await P.events(5e3).catch(()=>null);g&&(k=g.events.filter(_=>_.device===s.id),dom.content($,Jn(g.events,s.id)))},Y=()=>{let g=a?.points.find(c=>c.device===s.id&&c.ip===s.endpoint);dom.content(d,[e("span",{class:`dl-dcard-ic${s.online?" on":""}`},w(s.kind)),e("div",{class:"dl-stack"},[e("div",{class:"dl-title-row"},[e("h3",{},s.name),N([w("edit")],()=>H(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),e("span",{class:"dl-sub"},[`${r.name} · ${Me[s.kind]}`])])]);let _=s.spark.reduce((c,u)=>c+u,0);dom.content(h,e("div",{class:"dl-dstats"},[e("div",{class:"dl-dstats-cell wide"},[e("span",{class:"dl-metric-label"},"Status"),Qn(s)]),e("div",{class:"dl-dstats-cell"},[e("span",{class:"dl-metric-label"},"This month"),e("b",{},V(s.month[0]+s.month[1])),e("span", Line truncated `),c=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),pe(l,"Parameters copied")}},"Copy as config")]),c])}function cr(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 r=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",r&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function Hi(n){let e=!1,o=t("pre",{class:"dl-conf"}),r=()=>dom.content(o,n.conf.split(`
`),d=e("div",{class:"dl-pgrid"},[i("Junk packets","zap",s?`${s} random packet${s===1?"":"s"} of ${o.jmin}–${o.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),i("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),i("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),i("Signatures","globe",r,["i1","i2","i3","i4","i5"]),i("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"]),i("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 e("details",{class:"dl-params"},[e("summary",{},[w("chevron"),e("span",{},"Current parameters"),e("span",{class:"dl-pcount"},String(n.length)),e("span",{class:"dl-spacer"}),e("button",{type:"button",class:"dl-linkbtn",click:h=>{h.preventDefault(),re(l,"Parameters copied")}},"Copy as config")]),d])}var Rt=(o,t)=>{let n=new URLSearchParams;o&&n.set("server",o),t&&t!=="overview"&&n.set("section",t);let a=n.toString();return`${L.url("admin/network/dawnline/server")}${a?`?${a}`:""}`},at=class{constructor(){this.noFooter=!0;this.root=e("div",{class:"dl-root"});this.section="overview";this.srvId="";this.ov={};this.pp={};this.tabsEl=e("div",{});this.headEl=e("div",{});this.secEl=e("div",{});this.bodyEl=e("div",{class:"dl-srvbody"})}async load(){let t=await P.status(31),n=t.servers.length?null:await P.setupDefaults();return[t,n]}render([t,n]){if(this.st=t,!t.servers.length&&n)return this.wizard(n);let a=new URLSearchParams(location.search),i=a.get("section")??"",s=Ma[i]??i;return mn.some(([r])=>r===s)&&(this.section=s),this.srvId=(t.servers.find(r=>r.id===a.get("server"))??t.servers[0]).id,we(t),dom.content(this.root,[this.tabsEl,this.headEl,this.secEl,this.bodyEl]),this.paint(),poll.add(async()=>{if(this.section!=="overview")return;let r=await P.status(31).catch(()=>null);if(!r||!r.servers.length)return;this.st=r;let l=this.current();dom.content(this.headEl,this.head(l)),this.paintTabs(),this.ov[l.id]?.update(r)},10),this.root}current(){return this.st.servers.find(t=>t.id===this.srvId)??this.st.servers[0]}async refresh(){let t=await P.status(31).catch(()=>null);t&&(this.st=t,t.servers.length?this.paint():location.href=Rt())}paint(){this.paintTabs(),dom.content(this.headEl,this.head(this.current())),this.paintSections(),this.showSection(this.section)}paintTabs(){let t=this.current();dom.content(this.tabsEl,e("div",{class:"dl-srvtabs",role:"tablist","aria-label":"Servers"},[...this.st.servers.map(n=>e("button",{type:"button",role:"tab",class:`dl-srvtab${n.id===t.id?" on":""}`,"aria-selected":n.id===t.id?"true":"false",click:()=>{n.id!==this.srvId&&(this.srvId=n.id,this.paint())}},[e("i",{class:`dot ${n.up?"ok":"bad"}`}),e("b",{},n.name),e("span",{class:"dl-mono dl-faint"},`:${n.port}`)])),e("button",{type:"button",class:"dl-srvtab add",click:()=>this.addServer()},[w("plus"),"Add server"])]))}paintSections(){dom.content(this.secEl,e("div",{class:"dl-seg dl-srvsections",role:"tablist","aria-label":"Server"},mn.map(([t,n])=>e("button",{type:"button",role:"tab","data-section":t,class:t===this.section?"on":"","aria-selected":t===this.section?"true":"false",click:()=>this.showSection(t)},n))))}go(t,n){let a=this.pp[this.current().id];if(n&&a)a.filter=n,a.el&&a.decorate();else if(n){let i=this.pp[this.current().id]=new He;i.filter=n}this.showSection(t),window.scrollTo({top:0,behavior:"smooth"})}detachKept(){let t=[...Object.values(this.ov).map(n=>n.el),...Object.values(this.pp).map(n=>n.el)];for(let n of t)n&&this.bodyEl.contains(n)&&n.remove()}showSection(t){this.section=t,this.secEl.querySelectorAll("[data-section]").forEach(r=>{let l=r.dataset.section===t;r.classList.toggle("on",l),r.setAttribute("aria-selected",l?"true":"false")});let n=this.st,a=this.current(),s={overview:()=>{let r=this.ov[a.id];return r?(r.update(n),r.el):(this.ov[a.id]=new ft(a.id,(l,d)=>this.go(l,d))).mount(n)},people:()=>{var h,m;let r=this.pp[a.id];if(r?.el)return r.poll(),r.el;let l=e("div",{},e("p",{class:"dl-muted"},"Loading people…"));return((h=this.pp)[m=a.id]??(h[m]=new He)).embed(n,a.id).then(p=>{l.isConnected?dom.content(l,p):l.replaceChildren(p)}),l},connection:()=>this.connection(a),access:()=>this.access(a),disguise:()=>this.disguise(a),tunnel:()=>this.tunnel(a)}[t]();this.detachKept(),dom.content(this.bodyEl,s)}head(t){let n=this.st,a=(l,d)=>e("span",{class:"dl-addrbar-seg"},[w(l),...d]),i=`${t.endpoint||"—"}:${t.port}`,s=!t.enabled||n.settings.paused_all,r=e("div",{class:"dl-actions"},[N([w("search")," Search ",e("kbd",{},"⌘K")],()=>Ct(),"neutral",{class:"cbi-button cbi-button-neutral dl-searchbtn"}),s?N([w("play")," Turn o Line truncated `).flatMap((s,l)=>l?[`
`))]):"",u=g.length+(s?.update?1:0)+(r?.update?1:0),C=[i?.version?`OpenWrt ${i.version} · ${i.target}`:"",t.check?u?`${u} update${u===1?"":"s"} ready`:"everything is current":"not checked yet",t.check?`checked ${St(t.check.time)}`:""].filter(Boolean).join(" · ");dom.content(this.root,[e("div",{class:"dl-pagehead"},[e("div",{class:"dl-stack"},[e("h2",{class:"dl-h1"},"Updates"),e("span",{class:"dl-faint"},C)]),N([w("refresh")," Check now"],()=>this.run("check"),"neutral",d)]),k,H,_,c])}async runAwg(t,n,a){await ae(a?`Install AmneziaWG ${a}?`:"Install AmneziaWG?","Every AmneziaWG tunnel on the router restarts for a few seconds, HomeTunnel too. Devices stay configured.","Install")&&this.start(`amneziawg:${t}${n?":ru":""}`)}async runPkgs(t,n,a=t){await ae(`Update ${n}?`,`${a.join(", ")} from the OpenWrt feeds. Services that use them restart for a moment.`,"Update")&&this.start(`pkgs:${t.join(",")}`)}async run(t){t!=="check"&&!await ae(`Update ${t==="app"?"Dawnline":t}?`,"A backup is made first. The page reloads when it finishes.","Update")||this.start(t)}async start(t){if(await O(()=>P.updatesRun(t))){this.running=!0;let n=await P.updatesStatus().catch(()=>null);n&&this.paint(n)}}};function Ot(o){return`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}-${String(o.getDate()).padStart(2,"0")}`}function Aa(o,t,n,a=30){let i=o?new Date(`${o}T12:00:00`):new Date;return t==="day"?i.setDate(i.getDate()+n):t==="week"?i.setDate(i.getDate()+7*n):t==="month"?i.setMonth(i.getMonth()+n):t==="year"?i.setFullYear(i.getFullYear()+n):i.setDate(i.getDate()+a*n),Ot(i)}var Pa={internet:"Browse the internet through your router. No access to devices at home.",lan:"Reach devices at home. Internet stays on their own connection.",both:"Home devices and the internet, all through your router."},wt=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.refreshSeq=0;this.refreshShown=0}async load(){this.id=new URLSearchParams(location.search).get("id")??"";let[t,n,a]=await Promise.all([P.status(30),P.events(5e3).catch(()=>({events:[]})),P.personUsage(this.id,30).catch(()=>null)]);return this.series=a?.person??[],this.devSeries=a?.devices??{},[t,n.events]}render([t,n]){this.st=t,this.events=n,we(t);let a=t.people.find(l=>l.id===this.id);if(!a)return e("div",{class:"dl-empty"},[e("h3",{},"Person not found"),e("p",{},"They may have been removed."),e("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=a;for(let l of["head","devices","traffic","places","activity","limits"])this.parts[l]=e("div",{});this.parts.devices.className="dl-person-devices";let i=e("div",{},[e("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[e("a",{href:Ze(a.server)},t.servers.find(l=>l.id===a.server)?.name??"Servers"),e("span",{},"/"),e("a",{href:Ze(a.server)},"People"),e("span",{},"/"),e("span",{},a.name)]),this.parts.head,e("div",{class:"dl-grid-person"},[e("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),e("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let s=new URLSearchParams(location.search),r=s.get("device")&&a.devices.find(l=>l.id===s.get("device"));return r?setTimeout(()=>Ce(this.p,r,()=>this.refresh(),this.st.geo),50):s.get("add")&&setTimeout(()=>Re(this.p,()=>this.refresh()),50),poll.add(()=>this.refresh(!0),15),i}async refresh(t=!1){let n=++this.refreshSeq,[a,i,s]=await Promise.all([P.status(30).catch(()=>null),P.events(5e3).catch(()=>null),P.personUsage(this.id,30).catch(()=>null)]);if(!a||n<this.refreshShown)return;this.refreshShown=n,this.st=a,i&&(this.events=i.events),s&&(this.series=s.person,this.devSeries=s.devices);let r=a.people.find(l=>l.id===this.id);if(!r){t||(location.href=Ze(this.p?.server));return}this.p=r,this.paint(),this.map?.update(this.mapData())}async patch(t,n){var s;let a=await O(()=>P.personUpdate(this.p.id,t),n);if(!a)return;let i=this.st.people.findIndex(r=>r.id===this.p.id);(s=a.person).rate??(s.rate=this.p.rate),i>=0&&(this.st.people[i]=a.person),this.p=a.person,this.paint()}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}mapCard(){let t=e("div",{class:"dl-panel-head pad"},[e("h3",{},"Locations"),e("span",{class:"dl-spacer"}),this.st.geo.enabled?ut("30d",n=>this.map?.setRange(n),!1):"",N("Hide",()=>{this.mapOpen=!1,this.map?.destroy(),this.map=null,this.paintPlaces()},"neutral")]);return this.st.geo.enabled?(this.map=new Fe({openPerson:()=>{},openDevice:(n,a)=>{let i=this.p.devices.find(s=>s.id===a);i&&Ce(this.p,i,()=>this.refresh(),this.st.geo)}},"30d",280),requestAnimationFrame(()=>this.map.mount(this.mapData())),e("div",{class:"dl-panel flush"},[t,this.map.el])):e("div",{class:"dl-panel flush"},[t,e("div",{class:"dl-map-off"},["Locations are off. ",e("a",{href:L.url("admin/network/dawnline/settings")},"Turn them on in Settings"),"."])])}paint(){let t=this.p,n=this.st,a=t.online?"online now": Line truncated `,cr(s,e)]:[cr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),r()}},[b("key"),"Show key"]);r();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),H([b("download")," Download"],()=>Se(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),pe(n.conf,"Configuration copied")}},[b("copy"),"Copy"])]),o])])}function eo(n){let e=n.amnezia.obfuscation??{},o={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([r,a])=>a==null||a===""||a===(o[r]??"0"))}async function zi(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 Xn(n,`${n.server} · ${n.person} · ${n.name}`),r={qr:()=>t("div",{class:"dl-qr-pane"},[Xe(Ct(n.conf),"dl-qr"),t("span",{class:"dl-sub"},eo(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),H("Copy",()=>pe(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>Hi(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(a,r[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function Ni(n,e,o,r){let a=jt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await se(r?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${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&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,r?"Generate and apply":"Switch and apply",!0)&&await W(()=>A.serverObfuscation(e.id,o),r?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Ri(n,e){let o=n.st,r=ie(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=ie(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=ie(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??un(o.awg),c=H("",()=>Ni(n,e,l,l===s),"neutral"),d=()=>dom.content(c,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);d();let p=o.awg_state?.tools!==!1,u=[],w=fe("UDP port",r,()=>It(Number(r.value),u,`Opened on the WAN firewall automatically.${Number(r.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],w.refresh()}).catch(()=>{});let C=fe("MTU",a,()=>Bo(a.value,e.mtus)),g=fe("Keep-alive",i,()=>Oo(i.value));return Rt("",[lr("AmneziaWG",e.ifname),ge("globe","Listening","Where devices reach this core from the internet",[w]),ge("file","In every device configuration","Changing these marks devices “Update config” until they import again",[C,g]),ge("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Ut(e.preset)?ct("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",mn(o.awg,l,m=>{l=m,d()},s,p),p&&!o.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Ai(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),c])]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[de("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),de("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet) Line truncated
`)}d.push(z),p+=k-1}let m=N([w("more")],()=>ke(m,[{label:"Export CSV",icon:w("download"),run:()=>be(this.st,l,"csv",t.id)},{label:"Export JSON",icon:w("download"),run:()=>be(this.st,l,"json",t.id)},null,{label:`Clear ${t.name}'s activity`,icon:w("trash"),danger:!0,run:()=>Ee(`Clear ${t.name}'s activity`,`Removes events about ${t.name} and their devices.`,{person:t.id},()=>this.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});dom.content(this.parts.activity,e("div",{class:"dl-panel flush"},[e("div",{class:"dl-panel-head pad"},[e("h3",{},"Activity"),e("span",{class:"dl-sub"},l.length>10?`latest 10 of ${l.length}`:""),e("span",{class:"dl-spacer"}),m]),d.length?d:e("div",{class:"dl-row dl-muted"},"Nothing yet.")]))}deviceStatus(t){return t.disabled?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),"Disabled"]):t.online?e("span",{class:"dl-dstat ok"},[e("i",{class:"dot ok"}),`Online · ${ce(t.handshake,this.st.now).replace(" ago","")}`]):t.handshake?e("span",{class:"dl-dstat"},[e("i",{class:"dot"}),`Last seen ${ce(t.handshake,this.st.now)}`]):e("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},[e("i",{class:"dot warn"}),"Not set up yet"])}addrs(t){if(!t.online||!t.endpoint)return"";let n=this.st.geo?.points.find(s=>s.device===t.id&&s.ip===t.endpoint),a=n?.city?`Client IP · ${n.city}${n.org?` · ${n.org}`:""}`:"Client IP",i=e("button",{type:"button",class:"dl-addr wan","aria-label":`Copy ${t.endpoint}`,click:()=>re(t.endpoint,"Client IP copied")},[w("globe"),e("span",{},t.endpoint)]);return le(i,()=>[e("div",{class:"dl-tip-title"},a),e("div",{class:"dl-muted"},"Click to copy")]),e("div",{class:"dl-addrs"},i)}deviceBars(t){let n=(this.devSeries[t]??[]).slice(-30),a=n.map(r=>r.rx+r.tx),i=Math.max(1,...a),s=r=>new Date(`${r}T12:00:00`).toLocaleDateString("en-GB",{day:"numeric",month:"short"});return e("div",{class:"dl-dbars"},n.map((r,l)=>{let d=e("i",{class:`${a[l]?"":"zero"}${l===n.length-1?" hi":""}`});return d.style.height=`${Math.max(8,a[l]/i*100)}%`,le(d,()=>[e("div",{class:"dl-tip-title"},l===n.length-1?`Today · ${s(r.day)}`:s(r.day)),e("div",{},V(a[l]))]),d}))}paintDevices(){let t=this.p,n=()=>this.refresh(),a=t.devices.map(s=>{let r=()=>Ce(t,s,n,this.st.geo);return e("article",{class:`dl-dcard${s.online?" online":""}${s.disabled?" off":""}`},[e("div",{class:"dl-dcard-head"},[e("span",{class:"dl-dcard-ic"},w(s.kind)),e("button",{type:"button",class:"dl-dcard-title",click:r},[e("b",{},s.name),this.deviceStatus(s),s.config_stale?e("span",{class:"dl-pill warn dl-stale"},"Update config"):""]),N([w("more")],r,"neutral",{title:`${s.name}: connect, rename, keys, remove`,class:"cbi-button cbi-button-neutral dl-icon-only"})]),s.handshake?e("div",{class:"dl-dcard-trend"},[e("div",{class:"dl-stack"},[e("b",{},V(s.month[0]+s.month[1])),e("span",{class:"dl-sub"},"this month")]),this.deviceBars(s.id)]):s.disabled?e("div",{class:"dl-sub"},`${Me[s.kind]} · created ${ce(s.created,this.st.now)} ${s.created_by==="portal"?"in the portal":"by you"}.`):e("div",{class:"dl-chips-row"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>this.showDeviceQr(s)},[w("qr"),"Show QR"]),e("button",{type:"button",class:"dl-chipbtn",click:()=>this.downloadConfig(s)},[w("download"),"Config"])]),this.addrs(s)])}),i=Math.max(0,t.device_limit-t.devices.length);i&&a.push(e("button",{type:"button",class:"dl-dslot add",click:()=>Re(t,n)},[e("span",{class:"dl-dslot-ic"},w("plus")),e("b",{},"Add device")])),dom.content(this.parts.devices,e("section",{class:"dl-devsec"},[e("div",{class:"dl-panel-head"},[e("h3",{},"Devices"),e("span",{class:"dl-sub"},`${t.online} online`),e("span",{class:"dl-spacer"}),i?"":N([w("plus")," Add device"],()=>Re(t,n),"neutral",{title:"Over the limit — admins can still add"})]),e("div",{class:"dl-dgrid"},a)]))}paintLimits(){let t=this.p,n=e("div",{class:"dl-seg wide",role:"radiogroup","aria-label":"Access"},["internet","lan","both"].map(c=>e("button",{type:"button",role:"radio",class:t.access===c?"on":"","aria-checked":t.access===c?"true":"false",click:()=>t.access!==c&&this.patch({access:c},`Access: ${je[c]}`)},[w(c==="internet"?"globe":c==="lan"?"home":"shield"),c==="internet"?"Internet":c==="lan"?"Home":"Both"]))),a=ze(t.expires),i=e("input",{type:"date",class:"dl-date-hidden",value:t.expires,tabindex:"-1","aria-hidden":"true"});i.addEventListener("change",()=>i.value&&this.patch({expires:i.value},`Access until ${_e(i.value)}`));let s=(c,u,C)=>{let v=Aa(t.expires&&(a??-1)>=0?t.expires:"",c,u);return this.patch({expires:v},`Access until ${_e(v)}`),C},r=[["week",1,"+1 week"],["month",1,"+1 month"],["month",3,"+3 months"],["year",1,"+1 year"]].map(([c,u,C])=>e("button",{type:"button",class:"dl-chipbtn",click:()=>s(c,u,C)},C)),l=e("span",{class:"dl-datechip"},[e("button",{type:"button",class:"dl-chipbtn",click:()=>{try{i.showPicker()}catch{i.focus()}}},[w("calendar"),t.expires?_e(t.expires):"Date"]),i]),d={pause:"pause access",notify:"keep acc Line truncated `),"Log copied"))]),p,u]),[w],"wide"),g([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let k=o??null,I=o?.id,x,v=0,$=h=>{I!==h.id&&(I=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await A.updatesStatus().catch(()=>null);x=h?.job?.id,v=h?.now??0;let f=await A.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==x&&(k=f.job,$(f.job))}catch(h){return C=[be(h)],p.textContent=C[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},be(h))])),g([m(!0)]),U(be(h),"error"),null}let E=null,y=0;for(;;){if(await Br(1e3),E=await A.updatesStatus().catch(()=>null),!E){if(++y>60)break;continue}y=0;let h=E.job;if(!h||!Ir(h,I,x,v)){if(Date.now()-i>15e3)break;continue}if($(h),k=h,h.log.length){C=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=C.join(`
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=Nr(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=zr((h.finished??E.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!k||k.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[b("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),g([m()]),e.onDone?.(E),k;if(k.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[b("x"),t("span",{},[t("b",{},k.error??"Operation failed"),a?"":". Nothing else was changed."])])),g([H("Copy log",()=>pe(C.join(`
`),"Log copied")),m(!0)]),U(`${Cn[r]??"Update"}: ${k.error??"failed"}`,"error"),e.onDone?.(E),k;if(c.className="dl-pill ok",c.textContent="Finished",a&&E){let h=Rr(E,r);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[b(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),U(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(E),h.update&&e.onUpdate){let f=E;g([m(),H(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else g([m()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&oe(),1200);return k}if(r==="app"&&k.to){let h=k.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let T=()=>{ui.menu?.flushCache(),location.reload()};g([m(),H("Reload now",T,"positive")]),U(`Dawnline updated to ${h}`,"success",6e3);for(let S=1;S<=30;S++)if(f.textContent=`Waiting for the router to restart its services (${S} of 30)…`,await Br(1500),(await A.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(T,800),k;return f.textContent="Services restarted. Reload the page to use the new version.",k}let z=r==="pkgs"?`Updated ${[...k.result?.pkgs?.updated??[],...k.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:r==="amneziawg"?`AmneziaWG${k.to?` ${k.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[b("check"),t("span",{},z)])),g([m()]),U(z,"success"),e.onDone?.(E),k}var ss={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function Or(n,e,o,r){return!await se(`Install ${e}?`,o,"Install")||(await Jt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>r?.(),4e3),!0)}function Ln(n){return Or("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Vt(n,e,o){return n==="awg"?Ln(o):e.length?Or(`pkgs:${e.join(",")}`,ss[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function jr(n,e){if(n==="awg")return Ln(e);let o=await W(()=>A.updatesStatus());return o?Vt(n,o.needs?.[n]??[],e):!1}var ls=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],ds={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function Ur(n,e,o){let r=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,C=Dr(a,r,o),g=new Set,m="",k=()=>JSON.stringify([p,l,l?"":c,d,[...g].sort()]),I=()=>s.detected.lan||s.saved.lan||"",x=()=>(l?s.detected.wan||s.saved.wan:c)||"",v=()=>new Map(s.devices.map(R=>[R.name,R])),$=()=>{let R=v();return[...d&&I()?[I()]:[],...[...g].filter(Q=>Q!==I())].filter(Q=>Q!==x()).map(Q=>R.get(Q)??{name:Q,nets:[],missing:!0})},E=(R,J)=>{s=R,J&&(l=R.config.auto_wan,c=R.config.wan_device||R.detected.wan||R.saved.wan||"",d=R.config.auto_lan,p=R.config.lan_like,u=R.config.mesh??(R.config.device_mesh?"all":"off"),g=new Set(R.config.lan_devices),m=k()),q()},y=async R=>{let J=await A.interfaces(r).catch(Q=>(U(Q.message,"error"),null));J&&E(J,R)};function z(R){let J=d&&R.name===I(),Q=!!R.own||!!R.master||R.name===x()||J;return J||g.has(R.name)||!Q&&(R.nets.length>0||!!R.missing)}function h(R){let J=d&&R.name===I(),Q=R.name===x(),le=!J&&g.has(R.name),ue=!(!!R.own||!!R.master||Q||J)&&(R.nets.length>0||le||!!R.missing),ne=(le||J)&&!R.zone&&!R.missing,O=R.missing?"Not present right now":R.own?"This server":R.master?`Port of ${R.master}`:Q?`Internet${R.zone?` · zone ${R.zone}`:""}`:R.nets.length?R.nets.join(", "):"No IPv4 network",F=t("button",{type:"button",class:`dl-if${le?" sel":""}${J?" auto":""}${!ue&&!le&&!J?" off":""}${ne?" warn":""}`,"aria-pressed":le||J?"true":"false","aria-disabled":ue?null:"true",click:()=>{ue&&(g.has(R.name)?g.delete(R.name):g.add(R.name),q())}},[t("span",{class:"dl-if-ic"},b(ds[R.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},R.name),t("span",{class:"dl-if-sub"},O)]),J?t("span",{class:"dl-if-badge ok"},"Auto"):le?t("span",{class:"dl-if-check"},b("check")):""]);return me(F,()=>[t("div",{class:"dl-tip-title"},R.name),t("div",{class:"dl-muted"},[R.logical?`Interface ${R.logical}`:"No netifd interface",R.zone?` · zone ${R.zone}`:" · no firewall zone"]),R.members.length?t("div",{class:"dl-muted"},`Ports: ${R.members.join(", ")}`):"",R.nets.length?t("div",{class:"dl-mono"},R.nets.join(", ")):"",ne?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",R.master?t("div",{class:"dl-muted"},`Choose ${R.master} to include it.`):""]),F}function f(){let R=s.like_home;return!p||!s.config.lan_ Line truncated
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(`
`))),i=null):i.push(l);continue}if(/^```/.test(c.trim())){s(),i=[];continue}let d=/^(#{1,6})\s+(.*)$/.exec(c),p=/^\s*[-*+]\s+(.*)$/.exec(c)??/^\s*\d+[.)]\s+(.*)$/.exec(c);d?(s(),e.push(t("h5",{},o(d[2])))):p?(a.length&&s(),r||(r=t("ul",{}),e.push(r)),r.appendChild(t("li",{},o(p[1])))):c.trim()?(r&&(r=null),a.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
`))),s(),e}function ia(n){let e=[],o=!1;for(let r of n.replace(/\r/g,"").split(`
`)){let a=/^#{1,6}\s+(.*)$/.exec(r);if(a){if(o=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(r)&&(o=!1);o||e.push(r)}return e.join(`
`).replace(/\n{3,}/g,`
`).trim()}async function Zt(n,e,o,r){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";te(o,[i,a],[H([b("copy")," Copy"],()=>pe(s,"Release notes copied"))," ",ae("Close")],"wide");try{let l=await A.updatesNotes(n,e,r??"");s=ia(l.body||"");let c=ra(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",b("open")]):""]),dom.content(a,s.trim()?aa(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},bo=n=>n?Ue(n):"";function Cs(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function da(n,e){let o=n.st,r=o.policy,a=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Zt("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Es(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=r.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[r.interval]??24)*3600:0,p=(w,C)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},C)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},b("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${bo(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${bo(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[H("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),H("What’s new",s(i))]):"",Ls(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[b("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[r.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},r.auto?r.mode==="immediate"?"as soon as found":`${sa[r.interval]==="weekly"?"weekly":"daily"} at ${r.time}`:r.check?`checks ${sa[r.interval]}`:"checks off")]),p("Last check",o.check?[re(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${vt(d-o.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},r.keep?"Kept after the next update":"Off")])])])}function Es(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let r=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await A.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await A.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Cs(r(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ls(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",{},[b("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&An(n,e)}),n.versOpen&&An(n,e),o}async function An(n,e){let o=ie("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),r=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");la(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),r(o.value))});let a=t("div",{class:"dl-comp-tag"},[o,H("Install",()=>r(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),An(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await A.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),H("Try again",()=>An(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[a,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},bo(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?Ee("ok","Installed"):H("Install",()=>la(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function la(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function ca(n,e){let o=n.st,r=o.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),r&&u.push({label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${r.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:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,T)=>h!==null||f>0&&T[f-1]!==null),C=o.tunnels??[],g=C.length?`Switching restarts ${C.length===1?"the tunnel":`${C.length} tunnels`} for a few seconds: ${C.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=C.length>1?`${C.slice(0,-1).join(", ")} and ${C[C.length-1]}`:C[0],k=C.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",I=async h=>{let f=a[h];await se(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${g}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},x=h=>{let f=a[h],T=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},T?Ee("ok","Active"):f.version?H(p?"Switch":"Install",()=>I(h),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},v=i.map(h=>a[h]?.newer?`${a[h].label} moves to ${a[h].newer.gen} with OpenWrt ${a[h].newer.tag.replace( Line truncated
`)}a.push(p),l+=d-1}let s=H([b("more")],()=>Ce(s,[{label:"Export CSV",icon:b("download"),run:()=>Fe(o,r,"csv",e.id)},{label:"Export JSON",icon:b("download"),run:()=>Fe(o,r,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:b("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},r.length>10?`latest 10 of ${r.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var zn=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,r,a]=await Promise.all([A.status(30),e?A.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?A.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:r?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let r=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&o.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>We(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>r.isConnected,apply:(s,l)=>this.apply(s,l)}),r}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 r=this.st.people.find(a=>a.id===this.id);if(!r){o||(location.href=St(this.p?.server));return}this.p=r,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let r=await W(()=>A.personUpdate(this.p.id,e),o);if(!r)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=r.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=r.person),this.p=r.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return Mt(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:St(e.server)},this.st.servers.find(o=>o.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:St(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Te(this.parts.crumbs,this.crumbs(),e),Te(this.parts.head,wa(this),e),Te(this.parts.traffic,ya(this),e),Te(this.parts.devices,ka(this),e),Te(this.parts.limits,Sa(this),e),this.paintPlaces(e),Te(this.parts.activity,Pa(this),e)}paintPlaces(e=!1){let o=_a(this);o&&Te(this.parts.places,o,e&&!this.mapOpen)}};var Ns={ok:"check",warn:"alert",error:"x",skip:"pause"},Nn=class{constructor(e,o,r,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=r,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,r)}async run(e){let o=e?await _n(e):await A.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,r=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ct("error",`${o} problem${o>1?"s":""} need attention.`):r?ct("warn",`${r} warnLine truncated
`);function Ka(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=el,n}function mt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async r=>{let a=await e.render(r),i=document.createElement("div");return i.className="dl-root",i.append(Ka(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var Iv=mt(Yt),Bv=mt(ut),Ov=mt(Yt),jv=mt(Dn),Uv=mt(zn),Wv=mt(Bn),Gv=mt(Hn);function Ja(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 Fv=Ja(""),qv=Ja("log");return baseclass.extend({ activity: qv, diagnostics: Wv, health: Fv, overview: Iv, people: Bv, person: Uv, server: Ov, settings: jv, updates: Gv });
@@ -0,0 +1,5 @@
'use strict';
'require view';
'require dawnline.app as app';
return view.extend(app.diagnostics());
+9 -3
View File
@@ -1,5 +1,11 @@
#!/bin/sh #!/bin/sh
# Load devices into a Dawnline tunnel whenever netifd (re)creates it. # Dawnline tunnels: log starts and stops to the service log, and load devices
[ "$ACTION" = ifup ] || exit 0 # whenever netifd (re)creates one.
case "$ACTION" in ifup|ifdown|ifup-failed) ;; *) exit 0 ;; esac
[ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0 [ -n "$(uci -q get "network.$INTERFACE._dawnline")" ] || exit 0
/usr/bin/dawnline sync >/dev/null 2>&1 & # In order (a quick down/up must not log up first).
/usr/bin/dawnline iface-event "$ACTION" "$INTERFACE" >/dev/null 2>&1
# A disabled Dawnline leaves the tunnels empty: nothing would enforce end
# dates, limits or hours once the devices were loaded.
[ "$ACTION" = ifup ] && /etc/init.d/dawnline enabled && /usr/bin/dawnline sync >/dev/null 2>&1 &
exit 0
@@ -21,9 +21,15 @@ start_portal() {
hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)" hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport" [ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"
# Portal processes at once: each loads the whole model (a burst of 16 could
# empty a 128 MB router), so four, and two on a router with little memory;
# the rest of 64 connections wait their turn.
local procs=4 mem
mem="$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)"
[ -n "$mem" ] && [ "$mem" -le 160 ] && procs=2
procd_open_instance portal procd_open_instance portal
procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \ procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \
-D -n 16 -N 64 -t 20 -T 30 -k 10 -A 1 \ -D -n "$procs" -N 64 -t 20 -T 30 -k 10 -A 1 \
-s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http -s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http
procd_set_param file "$cert" procd_set_param file "$cert"
procd_set_param respawn 3600 5 0 procd_set_param respawn 3600 5 0
@@ -36,7 +42,8 @@ start_resolver() {
procd_open_instance dns procd_open_instance dns
procd_set_param command /usr/libexec/dawnline/resolver procd_set_param command /usr/libexec/dawnline/resolver
procd_set_param file /var/etc/dawnline-dns.conf procd_set_param file /var/etc/dawnline-dns.conf
procd_set_param respawn 3600 5 0 # A new config kills it (dawnline.resolver): back within a second, not five.
procd_set_param respawn 3600 1 0
procd_close_instance procd_close_instance
} }
@@ -55,6 +62,14 @@ start_service() {
start_resolver start_resolver
} }
# Noted for the service log: the next agent start is a restart, not a crash or a boot.
stop_service() {
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.
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' | xargs -r kill 2>/dev/null
}
reload_service() { reload_service() {
/usr/bin/dawnline apply >/dev/null 2>&1 /usr/bin/dawnline apply >/dev/null 2>&1
start start
@@ -1,6 +1,13 @@
#!/bin/sh #!/bin/sh
# Dawnline first-run / upgrade housekeeping. # Dawnline first-run / upgrade housekeeping.
# Locations are off by default since 0.5.2 (lookups send addresses to a third
# party); a router that had them on by the old default keeps them on.
if [ -f /etc/config/dawnline ] && [ -z "$(uci -q get dawnline.settings.geo_enabled)" ]; then
uci -q set dawnline.settings.geo_enabled=1
uci -q commit dawnline
fi
[ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG' [ -f /etc/config/dawnline ] || cat > /etc/config/dawnline <<'CFG'
config settings 'settings' config settings 'settings'
option portal_enabled '0' option portal_enabled '0'
@@ -17,17 +24,45 @@ uci -q commit dawnline
rm -f /etc/dawnline/alerts.json rm -f /etc/dawnline/alerts.json
# Backups moved into Settings. # Backups moved into Settings.
rm -f /www/luci-static/resources/view/dawnline/backups.js rm -f /www/luci-static/resources/view/dawnline/backups.js
# "Pause everyone" is gone: turning a server off does the same, so a
# router left paused keeps its servers off instead of letting everyone in.
if [ "$(uci -q get dawnline.settings.paused_all)" = 1 ]; then
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.=]*\)=server$/\1/p'); do uci -q set "dawnline.$s.enabled=0"; done
fi
uci -q delete dawnline.settings.paused_all
uci -q commit dawnline
# Portal assets moved out of the web root (served only with a valid code). # Portal assets moved out of the web root (served only with a valid code).
rm -rf /usr/share/dawnline/portal/www/assets rm -rf /usr/share/dawnline/portal/www/assets
# "Find home devices" (0.3.0) is gone: its option and dnsmasq records too.
for s in $(uci -q show dawnline | sed -n 's/^dawnline\.\([^.]*\)\.bonjour=.*/\1/p'); do uci -q delete "dawnline.$s.bonjour"; done
uci -q commit dawnline
if ls /tmp/dnsmasq*.d/dawnline-bonjour.conf >/dev/null 2>&1; then
rm -f /tmp/dnsmasq*.d/dawnline-bonjour.conf /var/run/dawnline/bonjour.json
/etc/init.d/dnsmasq restart 2>/dev/null
fi
# LuCI caches: menu index, and module URLs (?v= follows the opkg status time). # LuCI caches: menu index, and module URLs (?v= follows the opkg status time).
rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null
touch /usr/lib/opkg/status 2>/dev/null touch /usr/lib/opkg/status 2>/dev/null
# Cron restarts the agent when it stops ticking (Health → Watchdog).
mkdir -p /etc/crontabs
grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root || {
echo '*/5 * * * * /usr/libexec/dawnline/heartbeat' >> /etc/crontabs/root
/etc/init.d/cron restart 2>/dev/null
}
/etc/init.d/rpcd reload /etc/init.d/rpcd reload
# A reload keeps LuCI logins but sometimes misses the plugin; restart only then. # A reload keeps LuCI logins but sometimes misses the plugin; restart only then.
sleep 2 sleep 2
ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; } ubus list luci.dawnline >/dev/null 2>&1 || { /etc/init.d/rpcd restart; sleep 2; }
/etc/init.d/dawnline enable # A fresh install starts the service; an upgrade restarts it only where the
/etc/init.d/dawnline restart # admin had it on (a disabled Dawnline stays that way).
if [ "$PKG_UPGRADE" = 1 ]; then
/etc/init.d/dawnline enabled && /etc/init.d/dawnline restart
else
/etc/init.d/dawnline enable
/etc/init.d/dawnline restart
fi
exit 0 exit 0
@@ -0,0 +1 @@
/etc/dawnline/
+262 -46
View File
@@ -6,10 +6,37 @@ import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
import * as view from 'dawnline.view'; import * as view from 'dawnline.view';
import * as ops from 'dawnline.ops'; import * as health from 'dawnline.health';
import { VERSION } from 'dawnline.util'; import * as backup from 'dawnline.backup';
import * as pc from 'dawnline.portalcert';
import * as watchdog from 'dawnline.watchdog';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as devices from 'dawnline.devices';
import {
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
} from 'dawnline.util';
const args = ARGV; /** Options that take no value. */
const FLAGS = [ 'json', 'yes', 'conf' ];
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
const opts = {};
const args = [];
for (let i = 0; i < length(ARGV); i++) {
let a = ARGV[i];
if (a == '-n')
a = '--n';
if (substr(a, 0, 2) == '--') {
let name = substr(a, 2);
if (index(FLAGS, name) >= 0)
opts[name] = true;
else
opts[name] = ARGV[++i] ?? '';
}
else
push(args, a);
}
const cmd = args[0] ?? 'help'; const cmd = args[0] ?? 'help';
function out(v) { function out(v) {
@@ -17,10 +44,41 @@ function out(v) {
} }
function opt(name, dflt) { function opt(name, dflt) {
for (let i = 1; i < length(args); i++) return opts[name] ?? dflt;
if (args[i] == `--${name}`) }
return args[i + 1];
return dflt; /** Fixed-width columns: a header, then one line per row. */
function table(cols, rows) {
let w = map(cols, (c) => length(c));
for (let r in rows)
for (let i, v in r)
w[i] = max(w[i], length(`${v}`));
let line = (r) => rtrim(join(' ', map(r, (v, i) => sprintf(`%-${w[i]}s`, `${v}`))));
out(line(cols));
for (let r in rows)
out(line(r));
}
/** `--since 30m|2h|3d|YYYY-MM-DD` as a time, or null. */
function since_time(s) {
if (!s)
return null;
let m = match(s, /^([0-9]+)([mhd])$/);
if (m)
return time() - +m[1] * { m: 60, h: 3600, d: 86400 }[m[2]];
m = match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/);
if (m)
return timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 0, min: 0, sec: 0 });
die('--since takes 30m, 2h, 3d or a date like 2026-10-18.');
}
/** "5m", "3h", "2d": how long ago, for the lists. */
function ago(secs) {
return secs < 3600 ? `${int(secs / 60)}m` : secs < 86400 ? `${int(secs / 3600)}h` : `${int(secs / 86400)}d`;
}
function the_person(m, slug) {
return m.people[slug ?? ''] ?? die(slug ? `Unknown person: ${slug}.` : 'Which person? Give their id (dawnline person ls).');
} }
function help() { function help() {
@@ -29,26 +87,70 @@ function help() {
Usage: dawnline <command> Usage: dawnline <command>
apply Reconcile router configuration and runtime state apply Reconcile router configuration and runtime state
sync Push devices and access rules to the tunnel sync Push devices and access rules to the tunnels
status People and devices with live state (JSON) status People and devices with live state (JSON)
health Run health checks (JSON) health Run health checks (JSON)
person ls [--json] Everyone: id, name, access, state, devices, last seen
person add <name> [--slug s] [--access lan|internet|both] [--devices n] person add <name> [--slug s] [--access lan|internet|both] [--devices n]
[--expires YYYY-MM-DD] [--quota GB] [--expires YYYY-MM-DD] [--quota GB] [--server id]
person link <slug> Print the personal portal link person link <id> Print the personal portal link
person rm <slug> Remove a person and their devices person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
device add <slug> <name> [--kind phone|computer|tablet|router] device ls [person] [--json]
device conf <id> Print a device configuration device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
device conf <id> Print a device configuration (.conf)
device rm <id> Remove a device device rm <id> Remove a device
backup Create a backup in /etc/dawnline/backups backup Create a backup in /etc/dawnline/backups
portal-cert Print the certificate and key the portal uses portal-cert Print the certificate and key the portal uses
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
Service log: tunnel and service starts, stops, repairs (newest first)
teardown Remove everything Dawnline created on the router teardown Remove everything Dawnline created on the router
version`); version
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
} }
function commit(c) { /*
c.commit('dawnline'); * netifd retries a tunnel that fails to start every few seconds (a kernel
system('chmod 600 /etc/config/dawnline'); * module that won't load, AmneziaWG removed): one line per interface every
* 10 minutes, with how many attempts failed meanwhile. A start clears it.
*/
const FAILS = `${RUN_DIR}/ifup-failed.json`;
const FAIL_EVERY = 600;
function ifup_failed(ifname, who) {
let now = time();
// Attempts since the last line (a quiet spell starts a new count), and over how long.
let r = with_lock('ifup-failed', () => {
let all = read_json(FAILS, {});
let f = all[ifname];
if (!f || now - f.last > FAIL_EVERY)
f = all[ifname] = { logged: 0, count: 0, since: now };
f.count++;
f.last = now;
let out = null;
if (now - f.logged >= FAIL_EVERY) {
out = { n: f.count, mins: int((now - f.since) / 60) };
f.logged = f.since = now;
f.count = 0;
}
ensure_dir(RUN_DIR);
write_json(FAILS, all, 0o600);
return out;
});
if (r)
slog('awg', 'error', r.n > 1 ? `couldn't start · ${r.n} failed attempts in ${r.mins} min` : "couldn't start",
watchdog.iface_errors(ifname), who);
}
function ifup_ok(ifname) {
with_lock('ifup-failed', () => {
let all = read_json(FAILS, {});
if (all[ifname]) {
delete all[ifname];
write_json(FAILS, all, 0o600);
}
});
} }
try { try {
@@ -57,54 +159,108 @@ try {
else if (cmd == 'sync') else if (cmd == 'sync')
out(apply.sync()); out(apply.sync());
else if (cmd == 'status') { else if (cmd == 'status') {
let m = core.load(), u = core.load_usage(), d = live.dump(), st = view.states(m, u); let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true }))); out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
} }
else if (cmd == 'health') else if (cmd == 'health') {
out(ops.health()); let checks = health.health();
out(checks);
if (length(filter(checks, (c) => c.status == 'error')))
exit(1);
}
else if (cmd == 'person' && args[1] == 'ls') {
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
if (opts.json)
out(people);
else
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
]));
}
else if (cmd == 'person' && args[1] == 'add') { else if (cmd == 'person' && args[1] == 'add') {
let c = core.open_cursor(), m = core.load(c); let id = store.transact((c, m) => core.create_person(c, m, {
let id = core.create_person(c, m, { name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'), device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
}); }));
commit(c);
let m2 = core.load(); let m2 = core.load();
out(core.portal_url(m2, m2.people[id]) ?? id); live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
out(`Added ${m2.people[id].name} (${id})`);
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
} }
else if (cmd == 'person' && args[1] == 'link') { else if (cmd == 'person' && args[1] == 'link') {
let m = core.load(); let m = core.load();
let p = m.people[args[2]] ?? die('Unknown person.'); let p = the_person(m, args[2]);
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.'); out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
} }
else if (cmd == 'person' && args[1] == 'rm') { else if (cmd == 'person' && args[1] == 'rm') {
let c = core.open_cursor(), m = core.load(c); let m = core.load();
core.delete_person(c, m, args[2]); let p = the_person(m, args[2]);
commit(c); let n = length(p.devices);
apply.sync(); if (n && !opts.yes)
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
store.transact((c, m) => core.delete_person(c, m, p.id));
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
let s = apply.sync();
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
if (s.warning)
warn(`dawnline: ${s.warning}\n`);
}
else if (cmd == 'device' && args[1] == 'ls') {
let m = core.load(), d = live.dump(m);
let who = args[2] ? the_person(m, args[2]) : null;
let rows = [];
for (let id, dev in m.devices) {
let p = m.people[dev.person];
if (!p || (who && p.id != who.id))
continue;
let peer = d.peers[dev.public_key];
let online = live.online(d, id, peer);
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
online, handshake: +(peer?.handshake ?? 0) });
}
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
if (opts.json)
out(rows);
else
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
r.id, r.person, r.name, r.kind, r.address,
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
]));
} }
else if (cmd == 'device' && args[1] == 'add') { else if (cmd == 'device' && args[1] == 'add') {
let c = core.open_cursor(), m = core.load(c); // Through the same door as LuCI and the portal: event, "issued" marker, capability check.
let id = core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin' }); let m = core.load();
commit(c); let p = the_person(m, args[2]);
apply.sync(); if (!args[3])
out(id); die('Which name? dawnline device add <person> <name>.');
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
if (opts.conf)
print(r.config.conf);
else
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
} }
else if (cmd == 'device' && args[1] == 'conf') { else if (cmd == 'device' && args[1] == 'conf') {
let m = core.load(); let m = core.load();
let d = m.devices[args[2]] ?? die('Unknown device.'); let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
print(core.client_config(m, d).conf); awg.mark_issued(m, d.id);
print(awg.client_config(m, d).conf);
} }
else if (cmd == 'device' && args[1] == 'rm') { else if (cmd == 'device' && args[1] == 'rm') {
let c = core.open_cursor(), m = core.load(c); let m = core.load();
core.delete_device(c, m, args[2]); let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
commit(c); let r = devices.remove(d.id, { by: 'admin' });
apply.sync(); out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
if (r.warning)
warn(`dawnline: ${r.warning}\n`);
} }
else if (cmd == 'backup') else if (cmd == 'backup')
out(ops.backup_create(opt('reason'))); out(backup.backup_create(opt('reason')));
else if (cmd == 'portal-cert') { else if (cmd == 'portal-cert') {
let c = ops.portal_cert(core.load().settings); let c = pc.portal_cert(core.load().settings);
out(`${c.cert} ${c.key}`); out(`${c.cert} ${c.key}`);
} }
else if (cmd == 'portal-http-port') { else if (cmd == 'portal-http-port') {
@@ -112,12 +268,72 @@ try {
if (core.portal_http(m)) if (core.portal_http(m))
out(`${core.portal_http_port(m)}`); out(`${core.portal_http_port(m)}`);
} }
else if (cmd == 'log') {
let n = +opt('n', 0) || 0;
let since = since_time(opt('since'));
let level = opt('level'), src = opt('src');
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
die('--level takes error, down, repair, up or info.');
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
die('--src takes awg, dawnline or portal.');
let log = filter(slog_read(n && !since && !level && !src ? n : null),
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
if (n && length(log) > n)
log = slice(log, 0, n);
if (opts.json) {
out(log);
exit(0);
}
for (let e in log) {
let t = localtime(e.ts);
let text = e.by == 'admin'
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
: (e.who ? e.who + ' ' : '') + e.msg;
out(sprintf('%02d-%02d %02d:%02d %-8s %-6s %s', t.mon, t.mday, t.hour, t.min, e.src, e.level, text));
if (e.detail)
out(' ' + replace(e.detail, '\n', '\n '));
}
}
else if (cmd == 'iface-event') {
// From the iface hotplug script: a tunnel started, stopped or failed to start.
let ifname = args[2] ?? '';
if (!match(ifname, /^[a-z][a-z0-9_]{0,15}$/))
die('Bad interface.');
// Dawnline leaves a note before it takes a tunnel down itself; anything else is unexpected.
let it = args[1] == 'ifdown' ? take_iface_intent(ifname) : null;
let who = it?.name ?? ifname;
for (let id, srv in core.load().servers)
if (srv.ifname == ifname)
who = srv.name;
if (args[1] == 'ifup') {
ifup_ok(ifname);
let port = sh_out(`awg show ${q(ifname)} listen-port 2>/dev/null`);
slog('awg', 'up', port ? `started · accepting connections on port ${port}` : 'started', null, who);
}
else if (args[1] == 'ifdown') {
// Stops Dawnline made itself are explained by the admin's own line
// (changed, turned off, removed); only an AmneziaWG update gets one here.
if (it?.reason == 'update')
slog('awg', 'info', 'restarting for the AmneziaWG update', null, who);
else if (!it)
slog('awg', 'down', 'stopped unexpectedly', join('\n', filter([
"Dawnline didn't stop it: the router's network restarted, someone stopped it by hand, or it failed.",
watchdog.iface_errors(ifname),
], (x) => x)), who);
}
else if (args[1] == 'ifup-failed')
ifup_failed(ifname, who);
}
else if (cmd == 'teardown') else if (cmd == 'teardown')
apply.teardown(); apply.teardown();
else if (cmd == 'version') else if (cmd == 'version')
out(VERSION); out(VERSION);
else else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
help(); help();
else {
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
exit(2);
}
} }
catch (e) { catch (e) {
warn(`dawnline: ${e.message}\n`); warn(`dawnline: ${e.message}\n`);
@@ -1,39 +1,69 @@
#!/usr/bin/ucode #!/usr/bin/ucode
// Dawnline agent (procd instance). Every minute it: // Dawnline agent (procd instance). Every second its watcher reads the tunnels
// * folds AmneziaWG counters into usage (tmpfs; flushed to flash hourly) // 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:
// * folds the tunnels' counters into usage (tmpfs; flushed to flash hourly)
// * saves the activity log to flash as often as Settings says (or never) // * 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 // * keeps the "like a home device" path and the Home-only resolver up
// * logs connects, disconnects and roaming
// * enforces end dates, quotas, schedules and pauses (peers + nft sets) // * enforces end dates, quotas, schedules and pauses (peers + nft sets)
// * watches the tunnel interfaces // * watches the tunnel interfaces and repairs what it can (dawnline.watchdog)
'use strict'; 'use strict';
import * as uloop from 'uloop'; import * as uloop from 'uloop';
import { readfile, stat, unlink } from 'fs'; import { open, readfile, writefile, stat, unlink } from 'fs';
import { read_json, write_json, ensure_dir, sh_out, q, DATA_DIR, RUN_DIR } from 'dawnline.util'; import {
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply'; import * as apply from 'dawnline.apply';
import * as ops from 'dawnline.ops'; import * as backup from 'dawnline.backup';
import * as pc from 'dawnline.portalcert';
import * as geo from 'dawnline.geo'; import * as geo from 'dawnline.geo';
import * as watchdog from 'dawnline.watchdog';
import * as net from 'dawnline.net';
import * as store from 'dawnline.store';
import * as upd from 'dawnline.updates';
import * as awg from 'dawnline.awg';
const TICK = 60 * 1000; const TICK = 60 * 1000;
const WATCH = 1000;
const FLUSH_EVERY = 3600; const FLUSH_EVERY = 3600;
const LOG_FLUSH = { '10min': 600, hourly: 3600 }; const LOG_FLUSH = { '10min': 600, hourly: 3600 };
const RESYNC_EVERY = 600; const RESYNC_EVERY = 600;
const CONFIG_FILE = '/etc/config/dawnline';
// One agent, procd's. A second copy would run forever beside it with the code
// it started with: its own events (pauses and resumes from stale states), its
// own counters and syncs. It takes no arguments: the commands are `dawnline`'s.
if (length(ARGV)) {
warn(`The agent takes no arguments (procd runs it). For commands use: dawnline ${join(' ', ARGV)}\n`);
exit(2);
}
ensure_dir(RUN_DIR);
// Held as long as the process lives; close-on-exec, so children don't keep it.
let instance = open(`${RUN_DIR}/agent.lock`, 'we');
if (!instance?.lock('xn')) {
warn(`The agent is already running (${RUN_DIR}/agent.lock is held). Use /etc/init.d/dawnline restart.\n`);
exit(1);
}
let usage = live.load_usage(); let usage = live.load_usage();
let last_states = null; let last_states = null;
// Who was online, kept in tmpfs so an agent restart (update, reload) does not // Who was online, kept in tmpfs so an agent restart (update, reload) does not
// swallow connects that happened in between. // swallow connects that happened in between.
let presence = read_json(`${RUN_DIR}/presence.json`, {}); let presence = read_json(live.PRESENCE, {});
let last_online = presence.online ?? {}; let last_online = presence.online ?? {};
let last_endpoint = presence.endpoint ?? {}; let last_endpoint = presence.endpoint ?? {};
let offline_ticks = {}; let rev = +(presence.rev ?? 0);
let iface_down = {}; let person_rev = presence.people ?? {};
let last_flush = time(); let last_flush = time();
let last_log_flush = time(); let last_log_flush = time();
let last_net = null; // The network as apply() last saw it (apply.NET_SIG; this when it never ran),
// and a different one seen on the previous tick.
let base_net = null;
let pending_net = null;
let rate_prev = null; let rate_prev = null;
/** /**
@@ -92,27 +122,32 @@ function record_rate(m) {
write_json(`${RUN_DIR}/rate_people.json`, people, 0o644); write_json(`${RUN_DIR}/rate_people.json`, people, 0o644);
} }
let last_sync = 0; let last_sync = 0;
let conf_mtime = null;
let cert_mtime = null; let cert_mtime = null;
const REASON = { const REASON = {
paused: 'paused by admin', paused_all: 'everyone paused', expired: 'end date reached', paused: 'paused by admin', expired: 'end date reached',
quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', active: 'active', quota: 'data limit reached', hours: 'outside allowed hours', no_server: 'no server', server_off: 'server turned off',
active: 'active',
}; };
function check_people(m, states, events) { function check_people(m, states, events) {
let ts = time(); let ts = time();
for (let id, p in m.people) { for (let id, p in m.people) {
let st = states[id], prev = last_states?.[id]; let st = states[id], prev = last_states?.[id];
if (prev != null && prev != st) // The admin's own pauses (and turning a server off or on) are logged by
// rpcd when they happen; here only what changes on its own (end date,
// data limit, allowed hours).
let by_admin = (x) => x == 'paused' || x == 'server_off';
if (prev != null && prev != st && !by_admin(prev) && !by_admin(st))
push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st }); push(events, { type: st == 'active' ? 'resumed' : 'paused', person: id, detail: REASON[st] ?? st });
// "Remove their devices" when the end date passes. // "Remove their devices" when the end date passes: irreversible, so never
if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices)) { // on a clock that has not been set yet (a router before NTP is in 1970).
let c = core.open_cursor(); if (core.person_expired(p, ts) && p.expire_action == 'remove' && length(p.devices) && localtime(ts).year >= 2025) {
let mm = core.load(c); store.transact((c, mm) => {
for (let d in mm.people[id]?.devices ?? []) for (let d in mm.people[id]?.devices ?? [])
core.delete_device(c, mm, d); core.delete_device(c, mm, d);
c.commit('dawnline'); });
system('chmod 600 /etc/config/dawnline');
push(events, { type: 'devices_removed', person: id, detail: 'end date reached' }); push(events, { type: 'devices_removed', person: id, detail: 'end date reached' });
last_sync = 0; last_sync = 0;
} }
@@ -120,17 +155,26 @@ function check_people(m, states, events) {
} }
let last_home = 0; let last_home = 0;
// Addresses the watcher saw connect since the last tick: looked up first.
let geo_pending = {};
/** Locate new client addresses for the admin map (a couple per minute). */ /**
* Locate client addresses for the admin map: the ones that just connected
* first, then anything still shown that is missing or stale — a few per
* minute, within a time budget, so a slow service never holds the tick.
*/
function check_geo(m) { function check_geo(m) {
if (!m.settings.geo_enabled) if (!m.settings.geo_enabled) {
geo_pending = {};
return; return;
}
let cache = geo.load(); let cache = geo.load();
let ips = []; let ips = keys(geo_pending);
geo_pending = {};
for (let id, rec in usage.devices) for (let id, rec in usage.devices)
for (let ip in keys(rec.ips ?? {})) for (let ip in keys(rec.ips ?? {}))
push(ips, ip); push(ips, ip);
let changed = geo.resolve(m.settings, cache, ips, 2); let changed = geo.resolve(m.settings, cache, uniq(ips), 3, 12);
if (time() - last_home > 3600) { if (time() - last_home > 3600) {
last_home = time(); last_home = time();
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address; let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
@@ -145,71 +189,197 @@ function place_of(ip) {
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null; return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
} }
function check_devices(m, lv, events) { /** Connections from home: the DHCP name of the address, as it is now. */
for (let id, d in lv) { function named(e) {
let dev = m.devices[id]; let h = net.event_hosts(e, net.lan_names());
let was = last_online[id]; if (h)
// A device we have never seen before that is online now counts as a connect. e.hosts = h;
if (was == null && d.online && d.present) return e;
was = false; }
// Debounce: a device has to look offline on two ticks in a row before
// a disconnect is logged (handshakes are renewed only every 2-3 min). /* ---------- the watcher ---------- */
if (was && !d.online) {
offline_ticks[id] = (offline_ticks[id] ?? 0) + 1; // Per device: its latest real handshake, kept when apply re-adds the peer
if (offline_ticks[id] < 2) // (its counters and handshake restart from zero, or it is briefly missing).
continue; let last_hs = {};
// The model, read again only when the config file changes (the watcher runs every second).
let wm = null, wm_sig = null;
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;
if (wm == null || sig != wm_sig) {
wm = core.load();
wm_sig = sig;
}
return wm;
}
/** Move the revisions (all, and these people's) and save who is online. */
function save_presence(people) {
rev++;
for (let pid in people)
person_rev[pid] = rev;
ensure_dir(RUN_DIR);
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
}
/*
* 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.
*/
function watch() {
let d = awg.dump();
if (!d.ok)
return;
let m = watch_model();
let now = time();
let events = [], people = {}, ips = [];
for (let id, dev in m.devices) {
let peer = d.peers[dev.public_key];
let ep = '';
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 else
delete offline_ticks[id]; last_hs[id] = 0;
if (was != null && was != d.online) { let on = last_hs[id] > 0 && now - last_hs[id] < live.ONLINE_WINDOW;
if (d.online) let was = last_online[id];
push(events, { type: 'connect', person: dev.person, device: id, detail: d.endpoint, where: place_of(d.endpoint) }); if (on && !was) {
else push(events, { type: 'connect', person: dev.person, device: id, detail: ep });
push(events, { type: 'disconnect', person: dev.person, device: id }); push(ips, ep);
} }
else if (d.online && last_endpoint[id] && d.endpoint && last_endpoint[id] != d.endpoint) else if (!on && was)
push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${d.endpoint}` }); push(events, { type: 'disconnect', person: dev.person, device: id });
last_online[id] = d.online; else if (on && ep && last_endpoint[id] && ep != last_endpoint[id]) {
if (d.endpoint) push(events, { type: 'roam', person: dev.person, device: id, detail: `${last_endpoint[id]} → ${ep}` });
last_endpoint[id] = d.endpoint; push(ips, ep);
}
if (on != !!was || (ep && ep != last_endpoint[id]))
people[dev.person] = true;
last_online[id] = on;
if (ep)
last_endpoint[id] = ep;
} }
for (let id in keys(last_online)) for (let id in keys(last_online))
if (!m.devices[id]) { if (!m.devices[id]) {
delete last_online[id]; delete last_online[id];
delete last_endpoint[id]; delete last_endpoint[id];
delete last_hs[id];
} }
ensure_dir(RUN_DIR); if (!length(keys(people)))
write_json(`${RUN_DIR}/presence.json`, { online: last_online, endpoint: last_endpoint }, 0o600); return;
save_presence(keys(people));
if (!length(events))
return;
live.collect(m, usage, d);
live.save_usage(usage, false);
// A location lookup waits on the network: never here, on the next tick
// (check_geo). The event carries the place when the cache already knows it.
if (m.settings.geo_enabled)
for (let ip in ips)
geo_pending[ip] = true;
for (let e in events)
if (e.type == 'connect')
e.where = place_of(e.detail);
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
save_presence(keys(people));
} }
function check_servers(m, dmp, events) { // What the service log was already told. On flash: the public address often
for (let id, srv in m.servers) { // changes with a reboot (PPPoE), and that is when it matters. Written rarely.
if (!srv.enabled || !srv.private_key) const NOTES = `${DATA_DIR}/notes.json`;
let notes = read_json(NOTES, {});
let last_cert_check = 0;
function note(k, v) {
notes[k] = v;
ensure_dir(DATA_DIR, 0o700);
write_json(NOTES, notes, 0o600);
}
/*
* End dates in the activity log: a heads-up once per end date when its
* warning window opens, and "keep access" passing it (which changes no
* state, so nothing else would say it). Not on a clock that is not set.
*/
function check_expiry(m, events) {
let ts = time();
if (localtime(ts).year < 2025)
return;
for (let id, p in m.people) {
if (!p.expires)
continue; continue;
let up = dmp.ifaces[srv.ifname] != null; let end = date_end(p.expires);
if (!up) { if (end == null)
iface_down[id] = (iface_down[id] ?? 0) + 1; continue;
if (iface_down[id] == 2) { let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
push(events, { type: 'server_down', server: id, detail: srv.ifname }); if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
} note(`warned:${id}`, p.expires);
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
} }
else { if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
if ((iface_down[id] ?? 0) >= 2) { note(`kept:${id}`, p.expires);
push(events, { type: 'server_up', server: id, detail: srv.ifname }); push(events, { type: 'expired_kept', person: id, detail: p.expires });
}
iface_down[id] = 0;
} }
} }
} }
/** "Jan 1 2027" from the certificate, or null. */
function cert_end(path) {
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
return m ? `${m[1]} ${m[2]} ${m[3]}` : null;
}
function check_cert(m) { function check_cert(m) {
if (!m.settings.portal_enabled) if (!m.settings.portal_enabled)
return; return;
let c = ops.portal_cert(m.settings); let c = pc.portal_cert(m.settings);
let mt = stat(c.cert)?.mtime; let mt = stat(c.cert)?.mtime;
if (cert_mtime != null && mt != null && mt != cert_mtime) if (cert_mtime != null && mt != null && mt != cert_mtime) {
slog('portal', 'up', `certificate renewed · valid until ${cert_end(c.cert) ?? '?'}`, null, 'Personal portal');
system('/etc/init.d/dawnline reload >/dev/null 2>&1 &'); system('/etc/init.d/dawnline reload >/dev/null 2>&1 &');
}
cert_mtime = mt; cert_mtime = mt;
// Running out soon (ACME did not renew it): once per certificate, checked hourly.
if (mt == null || c.self_signed || time() - last_cert_check < 3600)
return;
last_cert_check = time();
if (notes.cert_warned != mt && system(`openssl x509 -checkend 604800 -noout -in ${q(c.cert)} >/dev/null 2>&1`) != 0) {
slog('portal', 'error', `certificate expires ${cert_end(c.cert) ?? 'within 7 days'}`,
'Browsers will refuse the portal after that. Renew it with ACME, or choose another certificate in Settings.', 'Personal portal');
note('cert_warned', mt);
}
}
/**
* The router's public IPv4 changed. Devices whose configuration holds the
* address itself (a server's public address is an IP) cannot connect until
* they get a new one; with a hostname only the DNS record must follow.
*/
function check_wan(m) {
let srv = filter(values(m.servers), (x) => x.enabled && x.private_key)[0];
let ip = srv ? net.wan_address(srv) : null;
if (!ip || ip == notes.wan)
return;
let was = notes.wan;
note('wan', ip);
if (!was)
return;
let stuck = map(filter(values(m.servers), (x) => core.endpoint_host(m, x) == was), (x) => x.name);
if (length(stuck))
slog('dawnline', 'error', `public address changed · ${was} → ${ip}`,
`${join(', ', stuck)} still give${length(stuck) == 1 ? 's' : ''} devices the old address: set the public address in the server settings (a DDNS name keeps working), then devices need new configurations.`, 'Router');
else
slog('dawnline', 'info', `public address changed · ${was} → ${ip}`, null, 'Router');
} }
let last_backup_day = null; let last_backup_day = null;
@@ -223,13 +393,25 @@ function nightly_backup() {
let st = read_json(`${DATA_DIR}/backup-state.json`, {}); let st = read_json(`${DATA_DIR}/backup-state.json`, {});
if (sum && sum != st.auto) { if (sum && sum != st.auto) {
try { try {
ops.backup_create('auto'); backup.backup_create('auto');
write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600); write_json(`${DATA_DIR}/backup-state.json`, { auto: sum }, 0o600);
} }
catch (e) {} catch (e) {
// Tried again tomorrow; meanwhile the admin should know (a full flash, mostly).
slog('dawnline', 'error', `nightly backup failed: ${e.message}`, null, 'Backup');
}
} }
} }
/**
* Settings → Updates: an automatic check or update when one is due. The
* updater does the work in its own process; this only decides when.
*/
function check_updates(m) {
if (upd.due(m.settings.updates, upd.auto_state()) && !upd.busy())
system('start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- auto');
}
/** /**
* Traffic history resets requested from LuCI (rpcd cannot touch the * Traffic history resets requested from LuCI (rpcd cannot touch the
* counters this process holds in memory). Applied, then saved to flash. * counters this process holds in memory). Applied, then saved to flash.
@@ -246,72 +428,182 @@ function check_usage_reset(m) {
return true; return true;
} }
function tick() { /*
// A restore or import drops the live counters; start over from flash. * Push devices and access rules when people's states changed, the config
if (!stat(`${RUN_DIR}/usage.json`) && usage.updated) * file was written (by anyone: rpcd, the portal, the CLI, a restore), the
usage = live.load_usage(); * access table is gone (a flushed ruleset: the firewall alone would let every
let m = core.load(); * device reach everything, so the sync unloads them until it is back), or
let reset = check_usage_reset(m); * every RESYNC_EVERY seconds anyway. apply.sync reads the model again itself.
let pol = live.policy(m.settings.retention); */
let dmp = live.dump(); function sync_runtime(t) {
let lv = live.collect(m, usage, dmp); // uci commits replace the file: a new inode even within the same second.
try { let st = stat(CONFIG_FILE);
record_rate(m); let mt = st ? `${st.mtime}/${st.inode}` : null;
} let changed = last_states == null || sprintf('%J', t.states) != sprintf('%J', last_states) ||
catch (e) {} (conf_mtime != null && mt != conf_mtime);
let states = apply.states_for(m, usage); if (changed || time() - last_sync > RESYNC_EVERY || (length(t.m.servers) && !apply.table_present())) {
let events = []; apply.sync(t.m, usage);
check_devices(m, lv, events);
check_people(m, states, events);
check_servers(m, dmp, events);
let changed = last_states == null || sprintf('%J', states) != sprintf('%J', last_states);
if (changed || time() - last_sync > RESYNC_EVERY) {
apply.sync(m, usage);
last_sync = time(); last_sync = time();
} }
last_states = states; conf_mtime = mt;
last_states = t.states;
}
live.add_events(events, pol); /*
* The router's network changed under us: re-derive everything. Only a change
let persist = reset || time() - last_flush >= FLUSH_EVERY; * seen on two ticks in a row (a bridge recreated or an interface restarting
live.save_usage(usage, persist); * passes), compared with what the last apply() used.
if (persist) */
last_flush = time(); function check_network(t) {
if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) { let sig = apply.net_signature(t.m);
live.persist_events(pol); let applied = readfile(apply.NET_SIG) ?? base_net;
last_log_flush = time(); if (applied == null || sig == applied) {
base_net ??= sig;
pending_net = null;
return;
} }
if (pending_net != sig) {
pending_net = sig;
return;
}
pending_net = null;
slog('dawnline', 'info', 'network changed — Dawnline set itself up again', null, 'Router');
apply.apply();
base_net = readfile(apply.NET_SIG) ?? apply.net_signature(core.load());
}
/*
* One tick is a list of steps, each on its own: a failing step is logged
* (each new message once in the service log, every time in syslog) and the
* others still run. Steps that need the model wait for it; the counters and
* the logs are saved at the end whatever happened.
*/
const STEPS = [
{ who: 'Dawnline', run: (t) => {
t.m = core.load();
t.pol = live.policy(t.m.settings.retention);
} },
{ who: 'Traffic', run: (t) => {
t.reset = check_usage_reset(t.m);
live.collect(t.m, usage, live.dump(t.m));
} },
{ who: 'Speed', quiet: true, run: (t) => record_rate(t.m) },
{ who: 'People', run: (t) => {
t.states = apply.states_for(t.m, usage);
check_people(t.m, t.states, t.events);
check_expiry(t.m, t.events);
} },
{ who: 'Access rules', run: (t) => {
if (t.states)
sync_runtime(t);
} },
// Tunnels going down and up are in the service log (hotplug, watchdog), with names and reasons.
{ who: 'Activity', run: (t) => {
live.add_events(t.events, t.pol);
// Pauses and resumes on their own: the UI shows them without waiting for its next poll.
if (length(t.events))
save_presence(uniq(map(filter(t.events, (e) => e.person), (e) => e.person)));
} },
{ who: 'Internet like a home device', run: (t) => apply.sync_loop(t.m, usage) },
{ who: 'Router', run: check_network },
{ who: 'Watchdog', run: (t) => watchdog.run(core.load()) },
{ who: 'Personal portal', run: (t) => check_cert(t.m) },
{ who: 'Router', quiet: true, run: (t) => check_wan(t.m) },
{ who: 'Backup', run: (t) => nightly_backup() },
{ who: 'updates', quiet: true, run: (t) => check_updates(t.m) },
{ who: 'geo', quiet: true, run: (t) => check_geo(t.m) },
];
// Step → the last error it logged (cleared when it works again).
let step_err = {};
function step(i, s, fn) {
try { try {
apply.sync_loop(m, usage); fn();
// The router's network changed under us: re-derive everything. delete step_err[i];
let sig = apply.net_signature(m); }
if (last_net != null && sig != last_net) { catch (e) {
system(`logger -t dawnline-agent 'network changed, re-applying'`); system(`logger -t dawnline-agent ${q(`${s.who}: ${e.message}`)}`);
apply.apply(); if (!s.quiet && step_err[i] != e.message)
sig = apply.net_signature(core.load()); slog('dawnline', 'error', `failed: ${e.message}`, e.stacktrace?.[0]?.context, s.who);
step_err[i] = e.message;
}
}
function tick() {
ensure_dir(RUN_DIR);
writefile(watchdog.BEAT, `${time()}`);
// A restore or import put other counters on flash (dawnline.backup leaves
// a marker): start over from them, whatever the watcher wrote since.
if (stat(live.USAGE_RELOAD)) {
unlink(live.USAGE_RELOAD);
usage = live.load_usage(true);
}
else if (!stat(`${RUN_DIR}/usage.json`) && usage.updated)
usage = live.load_usage();
let t = { m: null, pol: null, reset: false, events: [] };
for (let i, s in STEPS)
if (i == 0 || t.m)
step(i, s, () => s.run(t));
let persist = t.reset || time() - last_flush >= FLUSH_EVERY;
step('save', { who: 'Traffic' }, () => {
live.save_usage(usage, persist);
if (persist) {
last_flush = time();
geo.flush();
} }
last_net = sig; });
} step('slog', { who: 'Dawnline', quiet: true }, () => slog_trim(persist));
catch (e) { step('events', { who: 'Activity' }, () => {
system(`logger -t dawnline-agent ${q('like-home: ' + e.message)}`); let pol = t.pol ?? live.policy();
} if (pol.persist == 'off' || time() - last_log_flush >= LOG_FLUSH[pol.persist]) {
check_cert(m); live.persist_events(pol);
nightly_backup(); last_log_flush = time();
try { }
check_geo(m); });
}
catch (e) {
system(`logger -t dawnline-agent ${q('geo: ' + e.message)}`);
}
} }
function shutdown() { function shutdown() {
live.save_usage(usage, true); live.save_usage(usage, true);
live.persist_events(); live.persist_events();
geo.flush();
slog_trim(true);
// A clean stop: the next start is not a crash.
unlink(watchdog.BEAT);
} }
// Why this start: the heartbeat file outlives an agent that died (crash, out
// of memory, kill -9); the init script notes a stop; the version on flash
// changes with an update; a fresh uptime means the router just booted.
let crashed = stat(watchdog.BEAT) != null;
let stopped = +(readfile(`${RUN_DIR}/agent.stopped`) ?? 0);
unlink(`${RUN_DIR}/agent.stopped`);
let was = trim(readfile(`${DATA_DIR}/version`) ?? '');
if (was != VERSION) {
ensure_dir(DATA_DIR, 0o700);
writefile(`${DATA_DIR}/version`, VERSION);
}
slog_restore();
// postupdate put this (kept) version back because the new one did not come up.
let rolled = trim(readfile(`${RUN_DIR}/update-rolled-back`) ?? '');
unlink(`${RUN_DIR}/update-rolled-back`);
if (rolled)
slog('dawnline', 'error', `update to ${rolled} failed its check — rolled back to ${VERSION}`,
'The new version did not answer in LuCI or its agent did not start. Try again from Components, or install it with install.sh to see why.', 'Dawnline');
else if (was && was != VERSION)
slog('dawnline', 'up', `updated · ${was} → ${VERSION}`, null, 'Dawnline');
else if (crashed)
slog('dawnline', 'repair', 'stopped unexpectedly — started again',
// Why, when syslog knows: procd, the kernel (out of memory, segfault), ucode errors.
sh_out('logread -l 400 2>/dev/null | grep -iE "kernel:.*(out of memory|killed process|oom-kill|segfault)|procd:.*dawnline|dawnline/agent" | tail -n 6'), 'Dawnline');
else if (stopped && time() - stopped < 300)
slog('dawnline', 'info', `restarted · version ${VERSION}`, null, 'Dawnline');
else if (live.uptime() < 600)
slog('dawnline', 'info', `started with the router · version ${VERSION}`, null, 'Dawnline');
else
slog('dawnline', 'info', `started · version ${VERSION}`, null, 'Dawnline');
uloop.init(); uloop.init();
let timer; let timer;
@@ -320,11 +612,17 @@ timer = uloop.timer(1000, function() {
tick(); tick();
} }
catch (e) { catch (e) {
system(`logger -t dawnline-agent ${q('tick failed: ' + e.message)}`); slog('dawnline', 'error', `background check failed: ${e.message}`, e.stacktrace?.[0]?.context, 'Dawnline');
} }
timer.set(TICK); timer.set(TICK);
}); });
let watcher;
watcher = uloop.timer(WATCH, function() {
step('watch', { who: 'Connections' }, watch);
watcher.set(WATCH);
});
if (type(uloop.signal) == 'function') { if (type(uloop.signal) == 'function') {
uloop.signal('TERM', () => { shutdown(); uloop.end(); }); uloop.signal('TERM', () => { shutdown(); uloop.end(); });
uloop.signal('INT', () => { shutdown(); uloop.end(); }); uloop.signal('INT', () => { shutdown(); uloop.end(); });
@@ -0,0 +1,32 @@
#!/bin/sh
# Cron, every 5 minutes: the watchdog lives in the agent, so this looks after
# the agent itself: ends any copy that isn't procd's, and kills procd's when it
# runs but has stopped ticking (procd starts it again; that part is off with
# the watchdog, Health → Watchdog).
pid="$(ubus call service list '{"name":"dawnline"}' 2>/dev/null | jsonfilter -q -e '@.dawnline.instances.agent.pid')"
# Only procd's agent: any other copy (started by hand, or left by an older version that let
# it start) runs stale code beside it, with its own events and syncs. Always ended.
for p in $(pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent'); do
[ "$p" = "$pid" ] || kill -9 "$p" 2>/dev/null
done
[ "$(uci -q get dawnline.settings.watchdog)" = 0 ] && exit 0
[ -n "$pid" ] && [ -r "/proc/$pid/stat" ] || exit 0
now="$(date +%s)"
last="$(cat /var/run/dawnline/agent.beat 2>/dev/null)"
# Seconds the agent has been running: uptime minus its start time (field 22, in 1/100 s).
age="$(awk -v up="$(cut -d. -f1 /proc/uptime)" '{ print up - int($22 / 100) }' "/proc/$pid/stat")"
[ "${age:-0}" -gt 300 ] || exit 0
[ $((now - ${last:-0})) -gt 300 ] || exit 0
kill -9 "$pid"
# Logged here; the restarted agent should not report a crash as well.
rm -f /var/run/dawnline/agent.beat
if [ -n "$last" ]; then detail="No check for $((now - last)) s."
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"
@@ -0,0 +1,51 @@
#!/bin/sh
# Dawnline — after its own package was replaced: restart, check that the new
# version answers (the LuCI link and the agent), and put the kept previous
# version back when it does not. Started detached by the updater
# (usr/libexec/dawnline/updater) with the version being installed.
# postupdate <version>
# Plain shell on purpose: a release whose ucode does not compile cannot check
# or repair itself, and the admin cannot click Roll back in a page that this
# same backend serves.
RUN=/var/run/dawnline
KEEP=/etc/dawnline/keep/app
to="${1:-?}"
sleep 2
/etc/init.d/rpcd reload >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
up() {
ubus list luci.dawnline >/dev/null 2>&1 || return 1
ubus -t 10 call luci.dawnline rev >/dev/null 2>&1 || return 1
pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' >/dev/null 2>&1
}
i=0
while [ "$i" -lt 12 ]; do
sleep 5
i=$((i + 1))
up && exit 0
done
logger -t dawnline "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"
exit 1
fi
if command -v apk >/dev/null 2>&1; then
apk add --allow-untrusted "$@" >/dev/null 2>&1
else
opkg install --force-reinstall --force-downgrade "$@" >/dev/null 2>&1
fi
/etc/init.d/rpcd restart >/dev/null 2>&1
/etc/init.d/dawnline restart >/dev/null 2>&1
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"
exit 0
@@ -1,64 +1,52 @@
#!/usr/bin/ucode #!/usr/bin/ucode
// Dawnline background update worker, started detached by luci.dawnline. // Dawnline background update worker, started detached by luci.dawnline and
// by the agent (automatic runs).
// //
// updater check // updater check [app|amneziawg|packages]
// updater install app|amneziawg[:slava|grey[:ru]]|pkgs:<name,…>|all // updater install app | app@<tag> | app:reinstall | app:rollback
// updater install amneziawg[:auto|slava|grey[:ru]] | amneziawg:rollback
// updater install pkgs:<name,…>
// updater auto (Settings → Updates: check, then install)
// //
// Progress: /var/run/dawnline/update-job.json; check results: // One job at a time: the job holds the update lock (dawnline.updates) until
// /var/run/dawnline/update-check.json. The Updates tab polls both. // it exits. Progress: /var/run/dawnline/update-job.json; check results:
// /var/run/dawnline/update-check.json. The Components tab polls both. The
// components themselves are dawnline.upd_app, upd_awg and upd_pkgs.
'use strict'; 'use strict';
import * as fs from 'fs'; import * as fs from 'fs';
import { cursor } from 'uci'; import { slog, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
import { connect } from 'ubus'; import * as core from 'dawnline.core';
import { VERSION, REPO } from 'dawnline.util'; import * as upd from 'dawnline.updates';
import * as app from 'dawnline.upd_app';
import * as awg from 'dawnline.upd_awg';
import * as pkgs from 'dawnline.upd_pkgs';
const STATE_DIR = '/var/run/dawnline'; const PID = +split(fs.readfile('/proc/self/stat') ?? '0', ' ')[0];
const JOB_FILE = `${STATE_DIR}/update-job.json`; const POL = core.load().settings.updates;
const CHECK_FILE = `${STATE_DIR}/update-check.json`; const CHECKS = { app: app.check, amneziawg: awg.check, packages: pkgs.check };
const WORK_DIR = '/tmp/dawnline-update'; const INSTALLS = { app: app.install, amneziawg: awg.install, pkgs: pkgs.install };
// Builds per OpenWrt release (tag = firmware version); the kernel module must match the firmware. const WHO = { app: 'Dawnline', amneziawg: 'AmneziaWG', pkgs: 'System packages', packages: 'System packages' };
// Which AmneziaWG a build carries (2.0 or 3.1) is read from the package, per firmware.
const AWG_SOURCES = {
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
};
const AWG_PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
const AWG_RU = 'luci-i18n-amneziawg-ru';
// OpenWrt packages Dawnline runs on (the Updates tab groups and names them).
// What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the
// stock system): the home-like link, and HTTPS plus certificates for the personal portal.
const SYS_PKGS = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
// half old and half new.
const PKG_FAMILY = [
[ /^ip-full$/, /^ip-/ ],
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
[ /^(acme|luci-app-acme$)/, /^acme/ ],
];
function family(p) {
for (let f in PKG_FAMILY)
if (match(p, f[0]))
return f[1];
return null;
}
let job = { let job = {
action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null, id: `${time()}-${PID}`, action: ARGV[0], component: ARGV[1] ?? null, state: 'running', started: time(), finished: null,
phase: '', log: [], error: null, result: null, pid: PID, auto: false, phase: '', from: null, to: null, log: [], error: null, result: null,
}; };
// An automatic run only shows up as a job once it installs something.
let quiet = ARGV[0] == 'auto';
// What to restart once the job is over (never in the middle of it).
let after = {};
function save() { function save() {
fs.writefile(`${JOB_FILE}.tmp`, sprintf('%J', job)); if (!quiet)
fs.rename(`${JOB_FILE}.tmp`, JOB_FILE); write_json(upd.JOB_FILE, job, 0o644);
} }
function log(msg) { function log(msg) {
let t = localtime(); let t = localtime();
push(job.log, sprintf('%02d:%02d:%02d %s', t.hour, t.min, t.sec, msg)); push(job.log, sprintf('%02d:%02d:%02d %s', t.hour, t.min, t.sec, msg));
if (length(job.log) > 300) if (length(job.log) > 400)
splice(job.log, 0, length(job.log) - 300); splice(job.log, 0, length(job.log) - 400);
save(); save();
} }
@@ -67,455 +55,270 @@ function phase(p) {
log(p); log(p);
} }
function q(s) { /** A command, its output in the log: { code, out }. */
return "'" + replace(`${s ?? ''}`, "'", "'\\''") + "'";
}
function run(cmd) { function run(cmd) {
let p = fs.popen(cmd + ' 2>&1', 'r'); let p = fs.popen(cmd + ' 2>&1', 'r');
if (!p) if (!p)
return { code: 127, out: '' }; return { code: 127, out: '' };
let out = p.read('all') ?? ''; let out = p.read('all') ?? '';
return { code: p.close(), out }; let r = { code: p.close(), out };
} for (let line in split(trim(out), '\n'))
function run_logged(cmd) {
let r = run(cmd);
for (let line in split(trim(r.out), '\n'))
if (length(trim(line))) if (length(trim(line)))
log(` ${line}`); log(` ${line}`);
return r; return r;
} }
function repo() { const ctx = {
return REPO; pol: POL,
work: `/tmp/dawnline-update.${PID}`,
log, phase, run, save,
// An automatic run (nobody is watching: the previous version is always kept).
auto: () => job.auto,
versions: (from, to) => {
job.from = from;
job.to = to;
save();
},
after: (what) => after[what] = true,
};
/* ---------- check results ---------- */
function checks_file() {
return read_json(upd.CHECK_FILE, null)?.components ?? {};
} }
function have_curl() { /** Components' results into the check file (the others stay as they were). */
return fs.access('/usr/bin/curl', 'x'); function save_check(res) {
let c = read_json(upd.CHECK_FILE, null) ?? {};
c.components ??= {};
for (let k, v in res)
c.components[k] = { ...v, time: time() };
c.time = time();
write_json(upd.CHECK_FILE, c, 0o644);
} }
function download(url, dest) { /** What a check found, as short names ("Dawnline 0.3.3", "2 system packages"). */
let r = have_curl() function found_in(res) {
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 2 -o ${q(dest)} ${q(url)}`) let found = [];
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(url)}`); if (res.app?.update)
return r.code == 0 && (fs.stat(dest)?.size ?? 0) > 0; push(found, `Dawnline ${res.app.latest}`);
if (res.amneziawg?.update && res.amneziawg.installed)
push(found, `AmneziaWG ${res.amneziawg.latest}`);
if (res.packages?.updates)
push(found, `${res.packages.updates} system package${res.packages.updates == 1 ? '' : 's'}`);
return found;
} }
/** Latest release tag; the /releases/latest redirect avoids API rate limits. */ function run_checks(which) {
function latest_tag(rp) { let res = {};
if (have_curl()) { for (let name in which) {
let r = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`); phase(`Checking ${WHO[name]}`);
let m = match(trim(r.out), /\/releases\/tag\/([^\/?#]+)$/); try {
if (m) res[name] = CHECKS[name](ctx);
return m[1];
}
let r = run(`uclient-fetch -q -T 20 -O - ${q('https://api.github.com/repos/' + rp + '/releases/latest')}`);
try {
return json(r.out)?.tag_name;
}
catch (e) {
return null;
}
}
function version_cmp(a, b) {
let pa = split(replace(`${a}`, /^v/, ''), /[.~+-]/), pb = split(replace(`${b}`, /^v/, ''), /[.~+-]/);
for (let i = 0; i < length(pa) || i < length(pb); i++) {
let x = pa[i] ?? '0', y = pb[i] ?? '0';
if (match(x, /^[0-9]+$/) && match(y, /^[0-9]+$/)) {
if (int(x) != int(y))
return int(x) < int(y) ? -1 : 1;
} }
else if (x != y) catch (e) {
return x < y ? -1 : 1; log(`Error: ${e.message}`);
} res[name] = { error: e.message, status: '' };
return 0;
}
function is_apk() {
return fs.access('/usr/bin/apk', 'x');
}
function pkg_version(name) {
let esc = replace(name, /[.+]/g, '\\$&');
if (is_apk()) {
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
return m ? m[1] : null;
}
// Libraries carry their ABI in the name (libustream-openssl20201210).
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
for (let line in split(run('opkg list-installed').out, '\n')) {
let m = match(trim(line), re);
if (m && (found == null || m[1] == null))
found = m;
}
return found ? trim(found[2]) : null;
}
function pkg_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];
}
function workdir() {
run(`rm -rf ${WORK_DIR}`);
fs.mkdir(WORK_DIR, 0o700);
}
/* ---------- Dawnline itself ---------- */
function check_app() {
let rp = repo();
let tag = latest_tag(rp);
if (!tag)
return { installed: VERSION, latest: null, update: false, note: `No published release in ${rp}` };
let latest = replace(tag, /^v/, '');
return { installed: VERSION, latest, tag, repo: rp, update: version_cmp(VERSION, latest) < 0 };
}
function install_app() {
let c = check_app();
if (!c.latest)
die(c.note);
if (!c.update) {
log('Dawnline is up to date');
return { installed: VERSION };
}
// Releases carry luci-app-dawnline-<version>.ipk and .apk plus sha256sums.txt.
let asset = `luci-app-dawnline-${c.latest}.${is_apk() ? 'apk' : 'ipk'}`;
let base = `https://github.com/${c.repo}/releases/download/${c.tag}`;
workdir();
phase(`Downloading ${asset}`);
let f = `${WORK_DIR}/${asset}`, sums = `${WORK_DIR}/sha256sums.txt`;
if (!download(`${base}/${asset}`, f))
die(`Download failed: ${asset}`);
phase('Verifying package');
if (!download(`${base}/sha256sums.txt`, sums))
die('The release has no sha256sums.txt');
let want = null;
for (let line in split(fs.readfile(sums) ?? '', '\n')) {
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
if (m && m[2] == asset)
want = m[1];
}
let got = match(run(`sha256sum ${q(f)}`).out, /^([0-9a-f]{64})/)?.[1];
if (!want || got != want)
die(`Checksum mismatch for ${asset}`);
phase('Backing up configuration');
run('/usr/bin/dawnline backup --reason pre-update');
phase('Installing package');
if (run_logged(is_apk() ? `apk add --allow-untrusted ${q(f)}` : `opkg install ${q(f)}`).code != 0)
die('Installation failed');
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
// Restart after this job has saved its final state.
run('( sleep 3; /etc/init.d/rpcd reload; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
return { installed: c.latest };
}
/* ---------- AmneziaWG ---------- */
function awg_release() {
let u = connect();
let b = u?.call('system', 'board') ?? {};
u?.disconnect();
let rel = b.release ?? {};
let target = split(rel.target ?? '', '/');
let arch = rel.arch ?? trim(run("sed -n \"s/^DISTRIB_ARCH='\\(.*\\)'/\\1/p\" /etc/openwrt_release").out);
if (!rel.version || length(target) != 2 || !arch)
return null;
return {
tag: `v${rel.version}`,
postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`,
ext: is_apk() ? 'apk' : 'ipk',
};
}
function awg_download(r, name, rp) {
let file = `${name}${r.postfix}.${r.ext}`;
let dest = `${WORK_DIR}/${replace(rp, '/', '_')}_${file}`;
return download(`https://github.com/${rp}/releases/download/${r.tag}/${file}`, dest) ? dest : null;
}
/** When the build for this firmware was published (best effort). */
function release_date(rp, tag) {
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases/tags/${tag}`)}`);
try {
return json(r.out)?.published_at ?? null;
}
catch (e) {
return null;
}
}
/** AmneziaWG generation of a tools version: 3.x packages carry 3.1, older ones (1.0.x) 2.0. */
function awg_gen(version) {
return version == null ? null : match(version, /^3\./) ? '3.1' : '2.0';
}
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
function newer_series_tag(rp, tag) {
let r = run(`uclient-fetch -q -T 20 -O - ${q(`https://api.github.com/repos/${rp}/releases?per_page=30`)}`);
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
let best = null;
try {
for (let x in json(r.out) ?? []) {
let t = x.tag_name;
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && version_cmp(t, tag) > 0 && (!best || version_cmp(t, best) > 0))
best = t;
} }
} }
catch (e) {} save_check(res);
return best; return res;
} }
function awg_installed() { /** One line in Activity per new finding (the same finding is not repeated). */
let r = {}; function note_found(res, st, auto) {
for (let p in AWG_PKGS) let found = found_in(res);
r[p] = pkg_version(p); let sig = join(', ', found);
return r; if (length(found) && sig != st.announced) {
if (auto)
slog('dawnline', 'info', `updates available · ${sig}`, null, 'Components');
upd.history_add({ kind: 'found', items: found, auto });
}
st.announced = sig;
} }
function check_awg() { /* ---------- installs ---------- */
let installed = awg_installed();
let ru = pkg_version(AWG_RU) != null; /** A line in the service log for each finished update (Dawnline's own is logged by the new agent). */
let cur = installed['amneziawg-tools']; function log_update(name, r) {
let r = awg_release(); let how = job.auto ? ' automatically' : '';
if (!r) if (name == 'amneziawg') {
return { installed: cur, gen: awg_gen(cur), packages: installed, current: null, ru, sources: {}, update: false, note: 'Cannot detect the firmware target' }; let b = r?.before?.['kmod-amneziawg'], a = r?.after?.['kmod-amneziawg'];
workdir(); slog('awg', 'up', b && a && b != a ? `updated${how} · ${b} → ${a}`
let sources = {}; : `installed the ${r?.build ?? ''} build${a ? ' · ' + a : ''}`, null, 'AmneziaWG');
for (let id, src in AWG_SOURCES) { }
let f = awg_download(r, 'amneziawg-tools', src.repo); else if (name == 'pkgs' && length([ ...(r?.updated ?? []), ...(r?.installed ?? []) ]))
let v = f ? pkg_file_version(f) : null; slog('dawnline', 'up', `updated${how} · ${join(', ', [ ...(r.updated ?? []), ...(r.installed ?? []) ])}`, null, 'System packages');
let s2 = { label: src.label, repo: src.repo, tag: r.tag, version: v, gen: awg_gen(v), date: f ? release_date(src.repo, r.tag) : null }; }
// A newer firmware may already get 3.1 from this source.
if (s2.gen != '3.1') { function split_target(w) {
let nt = newer_series_tag(src.repo, r.tag); let i = index(w, ':'), at = index(w, '@');
if (nt) { let cut = i < 0 ? at : at < 0 || i < at ? i : at;
let nf = awg_download({ ...r, tag: nt, postfix: replace(r.postfix, r.tag, nt) }, 'amneziawg-tools', src.repo); if (cut < 0)
let nv = nf ? pkg_file_version(nf) : null; return [ w, null ];
if (awg_gen(nv) == '3.1') return [ substr(w, 0, cut), substr(w, cut + (substr(w, cut, 1) == ':' ? 1 : 0)) ];
s2.newer = { tag: nt, gen: '3.1' }; }
}
function app_status(installed, latest) {
if (!latest)
return 'latest';
let c = upd.version_cmp(installed, latest);
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
}
function install(what) {
job.result ??= {};
for (let w in what) {
let t = split_target(w), name = t[0], arg = t[1];
if (!INSTALLS[name])
die(`Unknown component ${name}`);
job.current = name;
phase(`Updating ${WHO[name]}`);
let r = INSTALLS[name](ctx, arg);
job.result[name] = r;
log_update(name, r);
// Installed components are current now: no stale "Update available".
let c = checks_file();
if (name == 'pkgs' && r.check)
save_check({ packages: r.check });
else if (name == 'app' && r.to && c.app) {
let s = app_status(r.to, c.app.latest);
save_check({ app: { ...c.app, installed: r.to, update: s == 'outdated', status: s } });
} }
sources[id] = s2; else if (name == 'amneziawg' && r.after)
save_check({ amneziawg: { ...(c.amneziawg ?? {}), installed: r.after['amneziawg-tools'], packages: r.after,
current: r.build ?? c.amneziawg?.current, update: false, status: 'latest' } });
upd.history_add({ kind: 'install', component: w, from: r.from, to: r.to, state: 'done', auto: job.auto,
took: time() - job.started });
delete job.current;
} }
// The installed build: the source whose package matches, else the main one.
let current = null;
for (let id, x in sources)
if (!current && cur && x.version == cur)
current = id;
current ??= cur ? 'slava' : null;
let mine = current ? sources[current] : null;
return { installed: cur, gen: awg_gen(cur), packages: installed, current, ru, release: r.tag, sources,
latest: mine?.version ?? null,
update: cur == null || (mine?.version != null && version_cmp(cur, mine.version) < 0),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(r.tag, 1)} yet` : null };
} }
function install_awg(arg) { /** Settings → Updates: check when due, install what is allowed (scheduled or right away). */
let parts = split(arg ?? '', ':'); function auto() {
let id = parts[0] || 'slava'; let st = upd.auto_state();
let src = AWG_SOURCES[id]; let what = upd.due(POL, st);
if (!src) if (!what)
die(`Unknown AmneziaWG build ${id}`); return;
let want_ru = parts[1] == 'ru'; let now = time();
let r = awg_release(); let res;
if (!r) if (what == 'check' || now - (st.check ?? 0) >= 3600) {
die('Cannot detect the firmware target'); res = run_checks(upd.TARGETS);
let before = awg_installed(); st.check = now;
workdir(); note_found(res, st, true);
let files = [];
for (let p in [ ...AWG_PKGS, ...(want_ru ? [ AWG_RU ] : []) ]) {
phase(`Downloading ${p} from ${src.repo}`);
let f = awg_download(r, p, src.repo);
if (!f)
die(`No ${p} build for OpenWrt ${substr(r.tag, 1)} in ${src.repo}`);
push(files, f);
}
phase('Refreshing package lists');
run_logged(is_apk() ? 'apk update' : 'opkg update');
phase(`Installing the ${src.label} build`);
let cmd = is_apk()
? `apk add --allow-untrusted ${join(' ', map(files, q))}`
: `opkg install --force-reinstall --force-downgrade ${join(' ', map(files, q))}`;
if (run_logged(cmd).code != 0)
die('Package installation failed');
if (!want_ru && pkg_version(AWG_RU))
run_logged(is_apk() ? `apk del ${AWG_RU}` : `opkg remove ${AWG_RU}`);
let after = awg_installed();
if (before['kmod-amneziawg'] && before['kmod-amneziawg'] != after['kmod-amneziawg']) {
// New kernel module: every AmneziaWG interface must be re-created.
let ifaces = [];
let c = cursor();
c.load('network');
c.foreach('network', 'interface', (s) => {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']);
});
phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
for (let i in ifaces)
run(`ifdown ${q(i)}`);
run('rmmod amneziawg');
run_logged('modprobe amneziawg');
for (let i in ifaces)
run(`ifup ${q(i)}`);
}
run('rm -f /tmp/luci-indexcache* /tmp/luci-modulecache/* 2>/dev/null');
return { build: id, before, after };
}
/* ---------- OpenWrt packages Dawnline uses ---------- */
// Installed packages with a newer version in the feeds: { name: latest }.
function upgradable(refresh) {
if (refresh) {
phase('Refreshing package lists');
run(is_apk() ? 'apk update' : 'opkg update');
}
let up = {};
if (is_apk()) {
for (let line in split(run('apk version -l "<"').out, '\n')) {
let m = match(line, /^(\S+?)-([0-9][^ ]*)\s+<\s+(\S+)/);
if (m)
up[m[1]] = m[3];
}
} }
else else
for (let line in split(run('opkg list-upgradable').out, '\n')) { res = checks_file();
let m = match(line, /^(\S+) - (\S+) - (\S+)/); if (what == 'install')
if (m) upd.mark_day(POL, st, now);
up[m[1]] = m[3]; upd.auto_save(st);
} if (!POL.auto || (what != 'install' && POL.mode != 'immediate'))
return up; return;
let todo = [];
// Packages first, Dawnline last: it restarts rpcd and itself.
if (index(POL.targets, 'packages') >= 0 && res.packages?.updates) {
let names = filter(keys(res.packages.pkgs ?? {}), (p) => res.packages.pkgs[p].latest || length(res.packages.pkgs[p].with ?? []));
if (length(names))
push(todo, `pkgs:${join(',', names)}`);
}
let a = res.amneziawg;
if (index(POL.targets, 'amneziawg') >= 0 && a?.update && a.installed) {
// Only the same build, same generation: anything else needs a person to decide.
if (a.current && !a.gen_change)
push(todo, `amneziawg:${a.current}${a.ru ? ':ru' : ''}`);
else
slog('awg', 'info', `${a.latest ?? 'a new build'} needs a manual switch in Components`, null, 'AmneziaWG');
}
if (index(POL.targets, 'app') >= 0 && res.app?.update)
push(todo, 'app');
if (!length(todo))
return;
quiet = false;
job.action = 'install';
job.component = join(' ', todo);
job.auto = true;
job.log = [];
log(`Automatic update: ${join(', ', todo)}`);
install(todo);
} }
// The packages to update for these names: each one plus its upgradable family. /**
function with_family(names, up) { * The restarts the job asked for, in one go, after its final state is saved.
let set = {}; * Dawnline's own package is restarted by postupdate, a shell that also checks
for (let n in names) { * the new version and rolls back to the kept one when it does not come up.
if (up[n]) */
set[n] = true; function restarts() {
let f = family(n); if (after.app) {
if (f) let to = replace(`${job.to ?? ''}`, /[^A-Za-z0-9.-]/g, '');
for (let u in keys(up)) system(`/usr/libexec/dawnline/postupdate '${to}' </dev/null >/dev/null 2>&1 &`);
if (match(u, f)) return;
set[u] = true;
} }
return sort(keys(set)); let cmds = [];
} if (after.apply)
push(cmds, '/usr/bin/dawnline apply');
function check_pkgs(refresh) { if (after.uhttpd)
let up = upgradable(refresh ?? true); push(cmds, '/etc/init.d/uhttpd restart');
let res = {}, all = {}; if (after.apply || after.uhttpd)
for (let p in SYS_PKGS) { push(cmds, '/etc/init.d/dawnline restart');
let v = pkg_version(p); if (length(cmds))
let set = v ? with_family([ p ], up) : []; system(`( sleep 2; ${join('; ', cmds)} ) </dev/null >/dev/null 2>&1 &`);
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
for (let x in set)
all[x] = true;
}
return { pkgs: res, updates: length(keys(all)) };
}
// Before install_pkgs: ucode resolves a name at the point it is used.
function save_check(res, at) {
fs.writefile(CHECK_FILE, sprintf('%J', { time: at ?? time(), components: res }));
}
function install_pkgs(arg) {
let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names)
if (index(SYS_PKGS, n) < 0)
die(`${n} is not a package Dawnline manages`);
if (!length(names))
die('Nothing to install');
phase('Refreshing package lists');
run_logged(is_apk() ? 'apk update' : 'opkg update');
let missing = filter(names, (n) => pkg_version(n) == null);
let have = with_family(filter(names, (n) => pkg_version(n) != null), upgradable(false));
if (length(have)) {
phase(`Updating ${join(', ', have)}`);
if (run_logged(is_apk() ? `apk upgrade ${join(' ', map(have, q))}` : `opkg upgrade ${join(' ', map(have, q))}`).code != 0)
die('Update failed');
}
if (length(missing)) {
phase(`Installing ${join(', ', missing)}`);
if (run_logged(is_apk() ? `apk add ${join(' ', map(missing, q))}` : `opkg install ${join(' ', map(missing, q))}`).code != 0)
die('Installation failed');
}
// Show the new state right away instead of the check from before the update.
try {
let c = json(fs.readfile(CHECK_FILE) ?? '{}') ?? {};
c.components ??= {};
c.components.packages = check_pkgs(false);
save_check(c.components, c.time);
}
catch (e) {
log(`Could not refresh the package check: ${e.message}`);
}
// The portal's HTTPS runs in uhttpd. Restart after this job saved its state.
let touched = [ ...names, ...have ];
// A missing piece arrived: set up what waited for it (the portal, the home-like link).
if (length(missing) && length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/))))
run('( sleep 3; /usr/bin/dawnline apply; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
run('( sleep 3; /etc/init.d/uhttpd restart; /etc/init.d/dawnline restart ) </dev/null >/dev/null 2>&1 &');
return { updated: have, installed: missing };
} }
/* ---------- main ---------- */ /* ---------- main ---------- */
const CHECKS = { app: check_app, amneziawg: check_awg, packages: check_pkgs }; ensure_dir(RUN_DIR);
const INSTALLS = { app: install_app, amneziawg: install_awg, pkgs: install_pkgs }; // One job at a time (LuCI refuses a second one; an automatic run just skips its turn).
let LOCK = null;
for (let i = 0; i < 10 && !LOCK; i++) {
if (!fs.access(STATE_DIR)) LOCK = upd.try_lock();
fs.mkdir(STATE_DIR, 0o755); if (!LOCK)
system('usleep 100000 2>/dev/null || sleep 1');
}
if (!LOCK)
exit(0);
fs.mkdir(ctx.work, 0o700);
save(); save();
try { try {
if (job.action == 'check') { if (job.action == 'check') {
let res = {}; let which = job.component ? [ job.component ] : upd.TARGETS;
for (let name, fn in CHECKS) { for (let w in which)
phase(`Checking ${name}`); if (!CHECKS[w])
try { die(`Unknown component ${w}`);
res[name] = fn(); job.result = run_checks(which);
} let st = upd.auto_state();
catch (e) { note_found(job.result, st, false);
res[name] = { error: e.message }; if (length(which) == length(upd.TARGETS))
} st.check = time();
} upd.auto_save(st);
save_check(res);
job.result = res;
}
else if (job.action == 'install') {
let what = job.component == 'all' ? [ 'amneziawg', 'app' ] : [ job.component ];
job.result = {};
for (let w in what) {
let i = index(w, ':');
let name = i < 0 ? w : substr(w, 0, i), arg = i < 0 ? null : substr(w, i + 1);
if (!INSTALLS[name])
die(`Unknown component ${name}`);
phase(`Updating ${name}`);
job.result[name] = INSTALLS[name](arg);
}
} }
else if (job.action == 'install')
install([ job.component ]);
else if (job.action == 'auto')
auto();
else else
die('Usage: updater check | install app|amneziawg[:build[:ru]]|pkgs:<names>|all'); die('Usage: updater check [app|amneziawg|packages] | install <what> | auto');
job.state = 'done'; job.state = 'done';
phase('Finished'); phase('Finished');
} }
catch (e) { catch (e) {
quiet = false;
job.state = 'failed'; job.state = 'failed';
job.error = e.message; job.error = e.message;
log(`Error: ${e.message}`); log(`Error: ${e.message}`);
let name = job.current ?? split_target(split(job.component ?? '', ' ')[0])[0];
if (job.action != 'check') {
slog(name == 'amneziawg' ? 'awg' : 'dawnline', 'error', `${job.auto ? 'automatic ' : ''}update failed`, e.message, WHO[name] ?? 'Dawnline');
upd.history_add({ kind: 'install', component: name, from: job.from, to: job.to, state: 'failed', auto: job.auto, error: e.message,
took: time() - job.started });
}
else
upd.history_add({ kind: 'error', component: job.component ?? 'all', state: 'failed', error: e.message });
} }
run(`rm -rf ${WORK_DIR}`); system(`rm -rf '${ctx.work}'`);
job.finished = time(); job.finished = time();
delete job.current;
save(); save();
restarts();
@@ -1 +1 @@
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.pill{display:inline-flex;align-items:center;height:22px;padding:0 9px;border-radius:999px;font-size:12px;font-weight:500;background:var(--soft);color:var(--muted)}.pill.ok{background:var(--ok-wash);color:var(--ok)}.pill.warn{background:var(--warn-wash);color:var(--warn)}.pill.bad{background:var(--bad-wash);color:var(--bad)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);mLine truncated @font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--ease-out: cubic-bezier(.23, 1, .32, 1);--ease-in: cubic-bezier(.55, 0, 1, .45);--ease-drawer: cubic-bezier(.32, .72, 0, 1);--spring: linear( 0, .022, .079, .158, .249, .344, .438, .527, .61, .684, .749, .805, .852, .891, .923, .949, .969, .984, .996, 1.004, 1.009, 1.013, 1.014, 1.015, 1.015, 1.014, 1.013, 1.012, 1.01, 1.009, 1.008, 1.006, 1.005, 1.004, 1.003, 1.002, 1.002, 1.001, 1.001, 1.001, 1 );--spring-pop: linear( 0, .034, .122, .244, .383, .526, .662, .785, .889, .974, 1.038, 1.083, 1.111, 1.124, 1.126, 1.119, 1.106, 1.09, 1.072, 1.054, 1.038, 1.023, 1.01, 1, .993, .988, .985, .984, .984, .985, .987, .989, .992, .994, .996, .998, .999, 1, 1.001, 1.002, 1 );--dur-press: .12s;--dur-hover: .15s;--dur-pop: .18s;--dur-swap: .26s;--dur-enter: .44s;--dur-sheet: .44s;--dur-exit: .16s;--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}html{scrollbar-gutter:stable}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}input,textarea,.keybox .mono,.linkrow .mono,.conf{cursor:text}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}a.btn:hover,a.badge:hover{text-decoration:none}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid vaLine truncated
@@ -1,6 +1,6 @@
"use strict";(()=>{var tt=Object.create;var $e=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty;var st=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ot=(n,e,a,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let v of rt(e))!it.call(n,v)&&v!==a&&$e(n,v,{get:()=>e[v],enumerable:!(o=nt(e,v))||o.enumerable});return n};var lt=(n,e,a)=>(a=n!=null?tt(at(n)):{},ot(e||!n||!n.__esModule?$e(a,"default",{value:n,enumerable:!0}):a,n));var Ue=st((Oe,Ke)=>{"use strict";var Ie=(function(){var n=function(M,k){var w=236,b=17,l=M,m=a[k],i=null,r=0,y=null,f=[],g={},T=function(c,u){r=l*4+17,i=(function(s){for(var d=new Array(s),h=0;h<s;h+=1){d[h]=new Array(s);for(var x=0;x<s;x+=1)d[h][x]=null}return d})(r),E(0,0),E(r-7,0),E(0,r-7),q(),I(),Q(c,u),l>=7&&z(c),y==null&&(y=Xe(l,m,f)),W(y,u)},E=function(c,u){for(var s=-1;s<=7;s+=1)if(!(c+s<=-1||r<=c+s))for(var d=-1;d<=7;d+=1)u+d<=-1||r<=u+d||(0<=s&&s<=6&&(d==0||d==6)||0<=d&&d<=6&&(s==0||s==6)||2<=s&&s<=4&&2<=d&&d<=4?i[c+s][u+d]=!0:i[c+s][u+d]=!1)},P=function(){for(var c=0,u=0,s=0;s<8;s+=1){T(!0,s);var d=v.getLostPoint(g);(s==0||c>d)&&(c=d,u=s)}return u},I=function(){for(var c=8;c<r-8;c+=1)i[c][6]==null&&(i[c][6]=c%2==0);for(var u=8;u<r-8;u+=1)i[6][u]==null&&(i[6][u]=u%2==0)},q=function(){for(var c=v.getPatternPosition(l),u=0;u<c.length;u+=1)for(var s=0;s<c.length;s+=1){var d=c[u],h=c[s];if(i[d][h]==null)for(var x=-2;x<=2;x+=1)for(var C=-2;C<=2;C+=1)x==-2||x==2||C==-2||C==2||x==0&&C==0?i[d+x][h+C]=!0:i[d+x][h+C]=!1}},z=function(c){for(var u=v.getBCHTypeNumber(l),s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[Math.floor(s/3)][s%3+r-8-3]=d}for(var s=0;s<18;s+=1){var d=!c&&(u>>s&1)==1;i[s%3+r-8-3][Math.floor(s/3)]=d}},Q=function(c,u){for(var s=m<<3|u,d=v.getBCHTypeInfo(s),h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<6?i[h][8]=x:h<8?i[h+1][8]=x:i[r-15+h][8]=x}for(var h=0;h<15;h+=1){var x=!c&&(d>>h&1)==1;h<8?i[8][r-h-1]=x:h<9?i[8][15-h-1+1]=x:i[8][15-h-1]=x}i[r-8][8]=!c},W=function(c,u){for(var s=-1,d=r-1,h=7,x=0,C=v.getMaskFunction(u),A=r-1;A>0;A-=2)for(A==6&&(A-=1);;){for(var S=0;S<2;S+=1)if(i[d][A-S]==null){var K=!1;x<c.length&&(K=(c[x]>>>h&1)==1);var L=C(d,A-S);L&&(K=!K),i[d][A-S]=K,h-=1,h==-1&&(x+=1,h=7)}if(d+=s,d<0||r<=d){d-=s,s=-s;break}}},re=function(c,u){for(var s=0,d=0,h=0,x=new Array(u.length),C=new Array(u.length),A=0;A<u.length;A+=1){var S=u[A].dataCount,K=u[A].totalCount-S;d=Math.max(d,S),h=Math.max(h,K),x[A]=new Array(S);for(var L=0;L<x[A].length;L+=1)x[A][L]=255&c.getBuffer()[L+s];s+=S;var Y=v.getErrorCorrectPolynomial(K),j=_(x[A],Y.getLength()-1),Ee=j.mod(Y);C[A]=new Array(Y.getLength()-1);for(var L=0;L<C[A].length;L+=1){var Be=L+Ee.getLength()-C[A].length;C[A][L]=Be>=0?Ee.getAt(Be):0}}for(var De=0,L=0;L<u.length;L+=1)De+=u[L].totalCount;for(var me=new Array(De),ce=0,L=0;L<d;L+=1)for(var A=0;A<u.length;A+=1)L<x[A].length&&(me[ce]=x[A][L],ce+=1);for(var L=0;L<h;L+=1)for(var A=0;A<u.length;A+=1)L<C[A].length&&(me[ce]=C[A][L],ce+=1);return me},Xe=function(c,u,s){for(var d=$.getRSBlocks(c,u),h=B(),x=0;x<s.length;x+=1){var C=s[x];h.put(C.getMode(),4),h.put(C.getLength(),v.getLengthInBits(C.getMode(),c)),C.write(h)}for(var A=0,x=0;x<d.length;x+=1)A+=d[x].dataCount;if(h.getLengthInBits()>A*8)throw"code length overflow. ("+h.getLengthInBits()+">"+A*8+")";for(h.getLengthInBits()+4<=A*8&&h.put(0,4);h.getLengthInBits()%8!=0;)h.putBit(!1);for(;!(h.getLengthInBits()>=A*8||(h.put(w,8),h.getLengthInBits()>=A*8));)h.put(b,8);return re(h,d)};g.addData=function(c,u){u=u||"Byte";var s=null;switch(u){case"Numeric":s=D(c);break;case"Alphanumeric":s=F(c);break;case"Byte":s=J(c);break;case"Kanji":s=U(c);break;default:throw"mode:"+u}f.push(s),y=null},g.isDark=function(c,u){if(c<0||r<=c||u<0||r<=u)throw c+","+u;return i[c][u]},g.getModuleCount=function(){return r},g.make=function(){if(l<1){for(var c=1;c<40;c++){for(var u=$.getRSBlocks(c,m),s=B(),d=0;d<f.length;d++){var h=f[d];s.put(h.getMode(),4),s.put(h.getLength(),v.getLengthInBits(h.getMode(),c)),h.write(s)}for(var x=0,d=0;d<u.length;d++)x+=u[d].dataCount;if(s.getLengthInBits()<=x*8)break}l=c}T(!1,P())},g.createTableTag=function(c,u){c=c||2,u=typeof u=="undefined"?c*4:u;var s="";s+='<table style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: "+u+"px;",s+='">',s+="<tbody>";for(var d=0;d<g.getModuleCount();d+=1){s+="<tr>";for(var h=0;h<g.getModuleCount();h+=1)s+='<td style="',s+=" border-width: 0px; border-style: none;",s+=" border-collapse: collapse;",s+=" padding: 0px; margin: 0px;",s+=" width: "+c+"px;",s+=" height: "+c+"px;",s+=" background-color: ",s+=g.isDark(d,h)?"#000000":"#ffffff",s+=";",s+='"/>';s+="</tr>"}return s+="</tbody>",s+="</table>",s},g.createSvgTag=function(c,u,s,d){var h={};typeof arguments[0]=="object"&&(h=arguments[0],c=h.cellSize,u=h.margin,s=h.alt,d=h.title),c=c||2,u=typeof u=="undefined"?c*4:u,s=typeof s=="string"?{text:s}:s||{},s.text=s.text||nLine truncated "use strict";(()=>{var Dn=Object.create;var xt=Object.defineProperty;var Hn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var In=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var On=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bn(t))!Rn.call(e,s)&&s!==r&&xt(e,s,{get:()=>t[s],enumerable:!(a=Hn(t,s))||a.enumerable});return e};var zn=(e,t,r)=>(r=e!=null?Dn(Nn(e)):{},On(t||!e||!e.__esModule?xt(r,"default",{value:e,enumerable:!0}):r,e));var St=In((Et,$t)=>{"use strict";var Tt=(function(){var e=function(v,f){var d=236,k=17,u=v,x=r[f],l=null,o=0,L=null,m=[],C={},B=function(p,g){o=u*4+17,l=(function(c){for(var y=new Array(c),b=0;b<c;b+=1){y[b]=new Array(c);for(var E=0;E<c;E+=1)y[b][E]=null}return y})(o),N(0,0),N(o-7,0),N(0,o-7),j(),W(),ae(p,g),u>=7&&J(p),L==null&&(L=K(u,x,m)),X(L,g)},N=function(p,g){for(var c=-1;c<=7;c+=1)if(!(p+c<=-1||o<=p+c))for(var y=-1;y<=7;y+=1)g+y<=-1||o<=g+y||(0<=c&&c<=6&&(y==0||y==6)||0<=y&&y<=6&&(c==0||c==6)||2<=c&&c<=4&&2<=y&&y<=4?l[p+c][g+y]=!0:l[p+c][g+y]=!1)},O=function(){for(var p=0,g=0,c=0;c<8;c+=1){B(!0,c);var y=s.getLostPoint(C);(c==0||p>y)&&(p=y,g=c)}return g},W=function(){for(var p=8;p<o-8;p+=1)l[p][6]==null&&(l[p][6]=p%2==0);for(var g=8;g<o-8;g+=1)l[6][g]==null&&(l[6][g]=g%2==0)},j=function(){for(var p=s.getPatternPosition(u),g=0;g<p.length;g+=1)for(var c=0;c<p.length;c+=1){var y=p[g],b=p[c];if(l[y][b]==null)for(var E=-2;E<=2;E+=1)for(var P=-2;P<=2;P+=1)E==-2||E==2||P==-2||P==2||E==0&&P==0?l[y+E][b+P]=!0:l[y+E][b+P]=!1}},J=function(p){for(var g=s.getBCHTypeNumber(u),c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[Math.floor(c/3)][c%3+o-8-3]=y}for(var c=0;c<18;c+=1){var y=!p&&(g>>c&1)==1;l[c%3+o-8-3][Math.floor(c/3)]=y}},ae=function(p,g){for(var c=x<<3|g,y=s.getBCHTypeInfo(c),b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<6?l[b][8]=E:b<8?l[b+1][8]=E:l[o-15+b][8]=E}for(var b=0;b<15;b+=1){var E=!p&&(y>>b&1)==1;b<8?l[8][o-b-1]=E:b<9?l[8][15-b-1+1]=E:l[8][15-b-1]=E}l[o-8][8]=!p},X=function(p,g){for(var c=-1,y=o-1,b=7,E=0,P=s.getMaskFunction(g),_=o-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var q=0;q<2;q+=1)if(l[y][_-q]==null){var Q=!1;E<p.length&&(Q=(p[E]>>>b&1)==1);var H=P(y,_-q);H&&(Q=!Q),l[y][_-q]=Q,b-=1,b==-1&&(E+=1,b=7)}if(y+=c,y<0||o<=y){y-=c,c=-c;break}}},$=function(p,g){for(var c=0,y=0,b=0,E=new Array(g.length),P=new Array(g.length),_=0;_<g.length;_+=1){var q=g[_].dataCount,Q=g[_].totalCount-q;y=Math.max(y,q),b=Math.max(b,Q),E[_]=new Array(q);for(var H=0;H<E[_].length;H+=1)E[_][H]=255&p.getBuffer()[H+c];c+=q;var ee=s.getErrorCorrectPolynomial(Q),te=w(E[_],ee.getLength()-1),yt=te.mod(ee);P[_]=new Array(ee.getLength()-1);for(var H=0;H<P[_].length;H+=1){var wt=H+yt.getLength()-P[_].length;P[_][H]=wt>=0?yt.getAt(wt):0}}for(var bt=0,H=0;H<g.length;H+=1)bt+=g[H].totalCount;for(var Fe=new Array(bt),Se=0,H=0;H<y;H+=1)for(var _=0;_<g.length;_+=1)H<E[_].length&&(Fe[Se]=E[_][H],Se+=1);for(var H=0;H<b;H+=1)for(var _=0;_<g.length;_+=1)H<P[_].length&&(Fe[Se]=P[_][H],Se+=1);return Fe},K=function(p,g,c){for(var y=h.getRSBlocks(p,g),b=M(),E=0;E<c.length;E+=1){var P=c[E];b.put(P.getMode(),4),b.put(P.getLength(),s.getLengthInBits(P.getMode(),p)),P.write(b)}for(var _=0,E=0;E<y.length;E+=1)_+=y[E].dataCount;if(b.getLengthInBits()>_*8)throw"code length overflow. ("+b.getLengthInBits()+">"+_*8+")";for(b.getLengthInBits()+4<=_*8&&b.put(0,4);b.getLengthInBits()%8!=0;)b.putBit(!1);for(;!(b.getLengthInBits()>=_*8||(b.put(d,8),b.getLengthInBits()>=_*8));)b.put(k,8);return $(b,y)};C.addData=function(p,g){g=g||"Byte";var c=null;switch(g){case"Numeric":c=A(p);break;case"Alphanumeric":c=D(p);break;case"Byte":c=T(p);break;case"Kanji":c=R(p);break;default:throw"mode:"+g}m.push(c),L=null},C.isDark=function(p,g){if(p<0||o<=p||g<0||o<=g)throw p+","+g;return l[p][g]},C.getModuleCount=function(){return o},C.make=function(){if(u<1){for(var p=1;p<40;p++){for(var g=h.getRSBlocks(p,x),c=M(),y=0;y<m.length;y++){var b=m[y];c.put(b.getMode(),4),c.put(b.getLength(),s.getLengthInBits(b.getMode(),p)),b.write(c)}for(var E=0,y=0;y<g.length;y++)E+=g[y].dataCount;if(c.getLengthInBits()<=E*8)break}u=p}B(!1,O())},C.createTableTag=function(p,g){p=p||2,g=typeof g=="undefined"?p*4:g;var c="";c+='<table style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: "+g+"px;",c+='">',c+="<tbody>";for(var y=0;y<C.getModuleCount();y+=1){c+="<tr>";for(var b=0;b<C.getModuleCount();b+=1)c+='<td style="',c+=" border-width: 0px; border-style: none;",c+=" border-collapse: collapse;",c+=" padding: 0px; margin: 0px;",c+=" width: "+p+"px;",c+=" height: "+p+"px;",c+=" background-color: ",c+=C.isDark(y,b)?"#000000":"#ffffff",c+=";",c+='"/>';c+="</tr>"}return c+="</tbody>",c+="</table>",c},C.createSvgTag=function(p,g,c,y){var b={};typeof arguments[0]=="object"&&(b=arguments[0],p=b.cellSize,g=b.margin,c=b.alt,y=b.title),p=p||2,g=typeof g=="undefined"?p*4:g,c=typeof c=="string"?{text:c}:c||{},c.text=c.texLine truncated
`}return s%2&&c>0?j.substring(0,j.length-s-1)+Array(s+1).join("▀"):j.substring(0,j.length-1)};return g.createASCII=function(c,u){if(c=c||1,c<2)return et(u);c-=1,u=typeof u=="undefined"?c*2:u;var s=g.getModuleCount()*c+u*2,d=u,h=s-u,x,C,A,S,K=Array(c+1).join("██"),L=Array(c+1).join(" "),Y="",j="";for(x=0;x<s;x+=1){for(A=Math.floor((x-d)/c),j="",C=0;C<s;C+=1)S=1,d<=C&&C<h&&d<=x&&x<h&&g.isDark(A,Math.floor((C-d)/c))&&(S=0),j+=S?K:L;for(A=0;A<c;A+=1)Y+=j+` `}return c%2&&p>0?te.substring(0,te.length-c-1)+Array(c+1).join("▀"):te.substring(0,te.length-1)};return C.createASCII=function(p,g){if(p=p||1,p<2)return qe(g);p-=1,g=typeof g=="undefined"?p*2:g;var c=C.getModuleCount()*p+g*2,y=g,b=c-g,E,P,_,q,Q=Array(p+1).join("██"),H=Array(p+1).join(" "),ee="",te="";for(E=0;E<c;E+=1){for(_=Math.floor((E-y)/p),te="",P=0;P<c;P+=1)q=1,y<=P&&P<b&&y<=E&&E<b&&C.isDark(_,Math.floor((P-y)/p))&&(q=0),te+=q?Q:H;for(_=0;_<p;_+=1)ee+=te+`
`}return Y.substring(0,Y.length-1)},g.renderTo2dContext=function(c,u){u=u||2;for(var s=g.getModuleCount(),d=0;d<s;d++)for(var h=0;h<s;h++)c.fillStyle=g.isDark(d,h)?"black":"white",c.fillRect(d*u,h*u,u,u)},g};n.stringToBytesFuncs={default:function(M){for(var k=[],w=0;w<M.length;w+=1){var b=M.charCodeAt(w);k.push(b&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(M,k){var w=(function(){for(var l=H(M),m=function(){var I=l.read();if(I==-1)throw"eof";return I},i=0,r={};;){var y=l.read();if(y==-1)break;var f=m(),g=m(),T=m(),E=String.fromCharCode(y<<8|f),P=g<<8|T;r[E]=P,i+=1}if(i!=k)throw i+" != "+k;return r})(),b=63;return function(l){for(var m=[],i=0;i<l.length;i+=1){var r=l.charCodeAt(i);if(r<128)m.push(r);else{var y=w[l.charAt(i)];typeof y=="number"?(y&255)==y?m.push(y):(m.push(y>>>8),m.push(y&255)):m.push(b)}}return m}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},a={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},v=(function(){var M=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,w=7973,b=21522,l={},m=function(i){for(var r=0;i!=0;)r+=1,i>>>=1;return r};return l.getBCHTypeInfo=function(i){for(var r=i<<10;m(r)-m(k)>=0;)r^=k<<m(r)-m(k);return(i<<10|r)^b},l.getBCHTypeNumber=function(i){for(var r=i<<12;m(r)-m(w)>=0;)r^=w<<m(r)-m(w);return i<<12|r},l.getPatternPosition=function(i){return M[i-1]},l.getMaskFunction=function(i){switch(i){case o.PATTERN000:return function(r,y){return(r+y)%2==0};case o.PATTERN001:return function(r,y){return r%2==0};case o.PATTERN010:return function(r,y){return y%3==0};case o.PATTERN011:return function(r,y){return(r+y)%3==0};case o.PATTERN100:return function(r,y){return(Math.floor(r/2)+Math.floor(y/3))%2==0};case o.PATTERN101:return function(r,y){return r*y%2+r*y%3==0};case o.PATTERN110:return function(r,y){return(r*y%2+r*y%3)%2==0};case o.PATTERN111:return function(r,y){return(r*y%3+(r+y)%2)%2==0};default:throw"bad maskPattern:"+i}},l.getErrorCorrectPolynomial=function(i){for(var r=_([1],0),y=0;y<i;y+=1)r=r.multiply(_([1,p.gexp(y)],0));return r},l.getLengthInBits=function(i,r){if(1<=r&&r<10)switch(i){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:"+i}else if(r<27)switch(i){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:"+i}else if(r<41)switch(i){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:"+i}else throw"type:"+r},l.getLostPoint=function(i){for(var r=i.getModuleCount(),y=0,f=0;f<r;f+=1)for(var g=0;g<r;g+=1){for(var T=0,E=i.isDark(f,g),P=-1;P<=1;P+=1)if(!(f+P<0||r<=f+P))for(var I=-1;I<=1;I+=1)g+I<0||r<=g+I||P==0&&I==0||E==i.isDark(f+P,g+I)&&(T+=1);T>5&&(y+=3+T-5)}for(var f=0;f<r-1;f+=1)for(var g=0;g<r-1;g+=1){var q=0;i.isDark(f,g)&&(q+=1),i.isDark(f+1,g)&&(q+=1),i.isDark(f,g+1)&&(q+=1),i.isDark(f+1,g+1)&&(q+=1),(q==0||q==4)&&(y+=3)}for(var f=0;f<r;f+=1)for(var g=0;g<r-6;g+=1)i.isDark(f,g)&&!i.isDark(f,g+1)&&i.isDark(f,g+2)&&i.isDark(f,g+3)&&i.isDark(f,g+4)&&!i.isDark(f,g+5)&&i.isDark(f,g+6)&&(y+=40);for(var g=0;g<r;g+=1)for(var f=0;f<r-6;f+=1)i.isDark(f,g)&&!i.isDark(f+1,g)&&i.isDark(f+2,g)&&i.isDark(f+3,g)&&i.isDark(f+4,g)&&!i.isDark(f+5,g)&&i.isDark(f+6,g)&&(y+=40);for(var z=0,g=0;g<r;g+=1)for(var f=0;f<r;f+=1)i.isDark(f,g)&&(z+=1);var Q=Math.abs(100*z/r/r-50)/5;return y+=Q*10,y},l})(),p=(function(){for(var M=new Array(256),k=new Array(256),w=0;w<8;w+=1)M[w]=1<<w;for(var w=8;w<256;w+=1)M[w]=M[w-4]^M[w-5]^M[w-6]^M[w-8];for(var w=0;w<255;w+=1)k[M[w]]=w;var b={};return b.glog=function(l){if(l<1)throw"glog("+l+")";return k[l]},b.gexp=function(l){for(;l<0;)l+=255;for(;l>=256;)l-=255;return M[l]},b})();function _(M,k){if(typeof M.length=="undefined")throw M.length+"/"+k;var w=(function(){for(var l=0;l<M.length&&M[l]==0;)l+=1;for(var m=new Array(M.length-l+k),i=0;i<M.length-l;i+=1)m[i]=M[i+l];return m})(),b={};return b.getAt=function(l){return w[l]},b.getLength=function(){return w.length},b.multiply=function(l){for(var m=new Array(b.getLength()+l.getLength()-1),i=0;i<b.getLength();i+=1)for(var r=0;r<l.getLength();r+=1)m[i+r]^=p.gexp(p.glog(b.getAt(i))+p.glog(l.getAt(r)));return _(m,0)},b.mod=function(l){if(b.getLen Line truncated `}return ee.substring(0,ee.length-1)},C.renderTo2dContext=function(p,g){g=g||2;for(var c=C.getModuleCount(),y=0;y<c;y++)for(var b=0;b<c;b++)p.fillStyle=C.isDark(y,b)?"black":"white",p.fillRect(y*g,b*g,g,g)},C};e.stringToBytesFuncs={default:function(v){for(var f=[],d=0;d<v.length;d+=1){var k=v.charCodeAt(d);f.push(k&255)}return f}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(v,f){var d=(function(){for(var u=F(v),x=function(){var W=u.read();if(W==-1)throw"eof";return W},l=0,o={};;){var L=u.read();if(L==-1)break;var m=x(),C=x(),B=x(),N=String.fromCharCode(L<<8|m),O=C<<8|B;o[N]=O,l+=1}if(l!=f)throw l+" != "+f;return o})(),k=63;return function(u){for(var x=[],l=0;l<u.length;l+=1){var o=u.charCodeAt(l);if(o<128)x.push(o);else{var L=d[u.charAt(l)];typeof L=="number"?(L&255)==L?x.push(L):(x.push(L>>>8),x.push(L&255)):x.push(k)}}return x}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},s=(function(){var v=[[],[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]],f=1335,d=7973,k=21522,u={},x=function(l){for(var o=0;l!=0;)o+=1,l>>>=1;return o};return u.getBCHTypeInfo=function(l){for(var o=l<<10;x(o)-x(f)>=0;)o^=f<<x(o)-x(f);return(l<<10|o)^k},u.getBCHTypeNumber=function(l){for(var o=l<<12;x(o)-x(d)>=0;)o^=d<<x(o)-x(d);return l<<12|o},u.getPatternPosition=function(l){return v[l-1]},u.getMaskFunction=function(l){switch(l){case a.PATTERN000:return function(o,L){return(o+L)%2==0};case a.PATTERN001:return function(o,L){return o%2==0};case a.PATTERN010:return function(o,L){return L%3==0};case a.PATTERN011:return function(o,L){return(o+L)%3==0};case a.PATTERN100:return function(o,L){return(Math.floor(o/2)+Math.floor(L/3))%2==0};case a.PATTERN101:return function(o,L){return o*L%2+o*L%3==0};case a.PATTERN110:return function(o,L){return(o*L%2+o*L%3)%2==0};case a.PATTERN111:return function(o,L){return(o*L%3+(o+L)%2)%2==0};default:throw"bad maskPattern:"+l}},u.getErrorCorrectPolynomial=function(l){for(var o=w([1],0),L=0;L<l;L+=1)o=o.multiply(w([1,i.gexp(L)],0));return o},u.getLengthInBits=function(l,o){if(1<=o&&o<10)switch(l){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:"+l}else if(o<27)switch(l){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:"+l}else if(o<41)switch(l){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:"+l}else throw"type:"+o},u.getLostPoint=function(l){for(var o=l.getModuleCount(),L=0,m=0;m<o;m+=1)for(var C=0;C<o;C+=1){for(var B=0,N=l.isDark(m,C),O=-1;O<=1;O+=1)if(!(m+O<0||o<=m+O))for(var W=-1;W<=1;W+=1)C+W<0||o<=C+W||O==0&&W==0||N==l.isDark(m+O,C+W)&&(B+=1);B>5&&(L+=3+B-5)}for(var m=0;m<o-1;m+=1)for(var C=0;C<o-1;C+=1){var j=0;l.isDark(m,C)&&(j+=1),l.isDark(m+1,C)&&(j+=1),l.isDark(m,C+1)&&(j+=1),l.isDark(m+1,C+1)&&(j+=1),(j==0||j==4)&&(L+=3)}for(var m=0;m<o;m+=1)for(var C=0;C<o-6;C+=1)l.isDark(m,C)&&!l.isDark(m,C+1)&&l.isDark(m,C+2)&&l.isDark(m,C+3)&&l.isDark(m,C+4)&&!l.isDark(m,C+5)&&l.isDark(m,C+6)&&(L+=40);for(var C=0;C<o;C+=1)for(var m=0;m<o-6;m+=1)l.isDark(m,C)&&!l.isDark(m+1,C)&&l.isDark(m+2,C)&&l.isDark(m+3,C)&&l.isDark(m+4,C)&&!l.isDark(m+5,C)&&l.isDark(m+6,C)&&(L+=40);for(var J=0,C=0;C<o;C+=1)for(var m=0;m<o;m+=1)l.isDark(m,C)&&(J+=1);var ae=Math.abs(100*J/o/o-50)/5;return L+=ae*10,L},u})(),i=(function(){for(var v=new Array(256),f=new Array(256),d=0;d<8;d+=1)v[d]=1<<d;for(var d=8;d<256;d+=1)v[d]=v[d-4]^v[d-5]^v[d-6]^v[d-8];for(var d=0;d<255;d+=1)f[v[d]]=d;var k={};return k.glog=function(u){if(u<1)throw"glog("+u+")";return f[u]},k.gexp=function(u){for(;u<0;)u+=255;for(;u>=256;)u-=255;return v[u]},k})();function w(v,f){if(typeof v.length=="undefined")throw v.length+"/"+f;var d=(function(){for(var u=0;u<v.length&&v[u]==0;)u+=1;for(var x=new Array(v.length-u+f),l=0;l<v.length-u;l+=1)x[l]=v[l+u];return x})(),k={};return k.getAt=function(u){return d[u]},k.getLength=function(){return d.length},k.multiply=function(u){for(var x=new Array(k.getLength()+u.getLength()-1),l=0;l<k.getLength();l+=1)for(var o=0;o<u.getLength();o+=1)x[l+o]^=i.gexp(i.glog(k.getAt(l))+i.glog(u.getAt(o)));return w(x,0)},k.mod=function(u){if(k.ge Line truncated
`),hostName:p,mtu:a.mtu,persistent_keep_alive:a.persistent_keep_alive,port:Number(a.port),psk_key:a.psk_key,server_pub_key:a.server_pub_key},$={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(_),port:String(a.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:p};return a.dns[0]&&($.dns1=a.dns[0]),a.dns[1]&&($.dns2=a.dns[1]),$}function vt(n){let e="";for(let a=0;a<n.length;a+=32768)e+=String.fromCharCode(...n.subarray(a,a+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pt(n){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let a=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(a).arrayBuffer()),v=new Uint8Array(4+o.length);return new DataView(v.buffer).setUint32(0,n.length,!1),v.set(o,4),v}catch{return null}}async function xe(n,e,a=!0){let o=new TextEncoder().encode(JSON.stringify(ht(n,e))),v=a?await pt(o):null;return`vpn://${vt(v!=null?v:o)}`}function t(n,e={},...a){let o=document.createElement(n);for(let[p,_]of Object.entries(e))_==null||_===!1||(p.startsWith("on")&&typeof _=="function"?o.addEventListener(p.slice(2),_):p==="class"?o.className=String(_):_===!0?o.setAttribute(p,""):o.setAttribute(p,String(_)));let v=p=>{p==null||p===!1||(Array.isArray(p)?p.forEach(v):o.appendChild(typeof p=="string"?document.createTextNode(p):p))};return a.forEach(v),o}function O(n){let e=t("span",{class:"ic"});return e.innerHTML=He(n,"ic-svg"),e}var gt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Ce=document.getElementById("app"),Ye,de=(Ye=Ce.dataset.base)!=null?Ye:"",mt=Ce.dataset.title||"Dawnline",ke=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),R=null,Fe=0,yt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(de)?de.slice(1):"",Ae=class extends Error{constructor(a,o){super(o);this.status=a}};async function oe(n,e){var v;let a=await fetch(`${de}/api/${n}`,{method:e===void 0?"GET":"POST",credentials:"omit",headers:e===void 0?{}:{"Content-Type":"application/json"},body:e===void 0?void 0:JSON.stringify(e),cache:"no-store"}),o=null;try{o=await a.json()}catch{}if(!a.ok)throw new Ae(a.status,(v=o==null?void 0:o.error)!=null?v:`Request failed (${a.status})`);return o}function se(n,e=!1){let a=t("div",{class:`toast${e?" bad":""}`,role:"status"},n);document.body.appendChild(a),requestAnimationFrame(()=>a.classList.add("show")),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>a.remove(),300)},2600)}async function ve(n,e="Copied"){try{await navigator.clipboard.writeText(n)}catch{let a=t("textarea",{class:"offscreen"},n);document.body.appendChild(a),a.select(),document.execCommand("copy"),a.remove()}se(e)}function je(n,e){let a=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),o=t("a",{href:a,download:n,class:"offscreen"});document.body.appendChild(o),o.click(),setTimeout(()=>{URL.revokeObjectURL(a),o.remove()},1e3)}var Z=null;function ze(n,e){let a=o=>{Z!=null||(Z=document.body.appendChild(t("div",{class:"tip"}))),Z.replaceChildren(...e().map((v,p)=>t("div",{class:p?"muted":"tip-title"},v))),Z.style.display="",Z.style.left=`${o.clientX}px`,Z.style.top=`${o.clientY-10}px`};n.addEventListener("mouseenter",a),n.addEventListener("mousemove",a),n.addEventListener("mouseleave",()=>Z&&(Z.style.display="none"))}function wt(n){let e=Math.max(1,...n),a=t("div",{class:"spark"});return n.forEach((o,v)=>{let p=t("i",{class:o?"":"zero"});p.style.height=`${Math.max(8,o/e*100)}%`;let _=n.length-1-v,$=new Date(Date.now()-_*864e5);ze(p,()=>[_===0?"Today":_===1?"Yesterday":$.toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),ee(o)]),a.appendChild(p)}),a}var ie=null,le=null;function te(n=!1){if(!ie)return;let e=ie;if(ie=null,document.body.classList.remove("locked"),le==null||le(),le=null,n){e.remove();return}e.classList.remove("open"),setTimeout(()=>e.remove(),250)}function pe(n,e,...a){let o=!!ie;te(!0);let v=t("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":n},t("div",{class:"grab"}),t("div",{class:"sheet-head"},t("div",{class:"stack"},t("h2",{},n),e?t("span",{class:"muted s"},e):null),t("button",{class:"icon-btn","aria-label":"Close",onclick:()=>te()},O("x"))),t("div",{class:"sheet-body"},...a)),p=t("div",{class:"sheet",onclick:_=>{_.target===p&&te()}},v);return document.body.appendChild(p),document.body.classList.add("locked"),o?p.classList.add("open"):requestAnimationFrame(()=>p.classList.add("open")),ie=p,v}document.addEventListener("keydown",n=>{n.key==="Escape"&&(he(),te())});var X=null;function he(){X==null||X.remove(),X=null}document.addEventListener("click",n=>{X&&!X.contains(n.target)&&he()});function bt(n,e){he();let a=t(" Line truncated `),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},h={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(w),port:String(r.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:i};return r.dns[0]&&(h.dns1=r.dns[0]),r.dns[1]&&(h.dns2=r.dns[1]),h}function Yn(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Qn(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),a=new Uint8Array(await new t.Response(r).arrayBuffer()),s=new Uint8Array(4+a.length);return new DataView(s.buffer).setUint32(0,e.length,!1),s.set(a,4),s}catch{return null}}async function Be(e,t,r=!0){let a=new TextEncoder().encode(JSON.stringify(Vn(e,t))),s=r?await Qn(a):null;return`vpn://${Yn(s!=null?s:a)}`}function n(e,t={},...r){let a=document.createElement(e);for(let[i,w]of Object.entries(t))w==null||w===!1||(i.startsWith("on")&&typeof w=="function"?a.addEventListener(i.slice(2),w):i==="class"?a.className=String(w):w===!0?a.setAttribute(i,""):a.setAttribute(i,String(w)));let s=i=>{i==null||i===!1||(Array.isArray(i)?i.forEach(s):a.appendChild(typeof i=="string"?document.createTextNode(i):i))};return r.forEach(s),a}function I(e){let t=n("span",{class:"ic"});return t.innerHTML=He(e,"ic-svg"),t}var ie=()=>typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches,oe={out:"cubic-bezier(0.23, 1, 0.32, 1)",in:"cubic-bezier(0.55, 0, 1, 0.45)",drawer:"cubic-bezier(0.32, 0.72, 0, 1)"};function Ht(e){var r;let t=e.closest(".sheet-panel");return t?(t.dataset.hold=String(+((r=t.dataset.hold)!=null?r:0)+1),()=>{var s;let a=+((s=t.dataset.hold)!=null?s:1)-1;a>0?t.dataset.hold=String(a):delete t.dataset.hold}):()=>{}}function jn(e,t){return e<=0||t<=0?0:(1-1/(e*.55/t+1))*t}function Jn(e,t,r){return e<=0||t<-.1?!1:t>.4||e>r/3}var Bt=e=>Math.round(Math.min(380,Math.max(220,200+e*.35)));function ne(e,t){e.classList.remove(t),e.offsetWidth,e.classList.add(t)}function Nt(e,t){let r=0,a=0,s=!1,i=null,w=new ResizeObserver(()=>{if(e.dataset.hold){i==null||i.cancel(),e.classList.remove("morphing","morphing-w"),r=e.offsetHeight,a=e.offsetWidth;return}let h=getComputedStyle(e),M=i?parseFloat(h.height):r,A=i?parseFloat(h.width):a;i==null||i.cancel(),e.classList.remove("morphing","morphing-w");let D=e.offsetHeight,T=e.offsetWidth,R=e.dataset.morph==="width"||s;delete e.dataset.morph;let z=a!==0&&T!==a;if(r=D,a=T,!M||ie()||z&&!R)return;let U=Math.abs(D-M),F=R?Math.abs(T-A):0;if(U<2&&F<2)return;s=F>=2,e.classList.add("morphing"),e.classList.toggle("morphing-w",s);let V=e.animate(s?[{height:`${M}px`,width:`${A}px`},{height:`${D}px`,width:`${T}px`}]:[{height:`${M}px`},{height:`${D}px`}],{duration:Bt(Math.max(U,F)),easing:oe.out});i=V;let G=()=>{i===V&&(i=null,s=!1,e.classList.remove("morphing","morphing-w"))};V.onfinish=G,V.oncancel=G});return w.observe(t),()=>w.disconnect()}function et(e,t,r=0){let a=[...e.childNodes];if(!a.length||!e.isConnected){e.replaceChildren(...t);return}let s=getComputedStyle(e),i=document.createElement("div");i.className="ghost",i.setAttribute("aria-hidden","true"),i.inert=!0,Object.assign(i.style,{display:s.display==="flex"?"flex":"block",flexDirection:s.flexDirection,alignItems:s.alignItems,gap:s.gap,top:s.paddingTop,left:s.paddingLeft,right:s.paddingRight}),i.append(...a),e.replaceChildren(i,...t);let w=ie(),h=i.animate([{opacity:1,transform:"none"},{opacity:0,transform:w?"none":`translateX(${-r*8}px)`}],{duration:120,easing:oe.out,fill:"forwards"}),M=()=>i.remove();h.onfinish=M,h.oncancel=M;for(let A of t)A instanceof HTMLElement&&A.animate(w?[{opacity:0},{opacity:1}]:[{opacity:0,transform:`translate(${r*12}px, ${r?0:6}px)`,filter:"blur(4px)"},{opacity:1,transform:"none",filter:"blur(0)"}],{duration:w?160:280,delay:50,easing:oe.out,fill:"backwards"})}function Rt(e){return!e||!e.isConnected?Promise.resolve():e.animate(ie()?[{opacity:1},{opacity:0}]:[{opacity:1,transform:"none",filter:"blur(0)"},{opacity:0,transform:"scale(0.96)",filter:"blur(4px)"}],{duration:200,easing:oe.in,fill:"forwards"}).finished.then(()=>{},()=>{})}var It=e=>new Promise(t=>setTimeout(t,ie()?0:e)),Ce={ms:520,contentMs:300,blur:4,drift:6,scale:.98};async function Ot(e){if(!e.isConnected)return;let t=Ht(e),r=parseFloat(getComputedStyle(e.parentElement).rowGap)||0,a=e.offsetHeight;e.style.overflow="hidden",e.style.transformOrigin="50% 0",e.inert=!0;let s=()=>{};ie()?await e.animate([{opacity:1},{opacity:0}],{duration:160,easing:oe.out,fill:"forwards"}).finished.then(s,s):(e.animate([{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:`blur(${Ce.blur}px)`,transform:`translateY(${-Ce.drift}px) scale(${Ce. Line truncated
`).flatMap((p,_)=>_?[` `).flatMap((w,h)=>h?[`
`,Ve(p,e)]:[Ve(p,e)])),v=t("button",{class:"btn small",onclick:p=>{p.preventDefault(),e=!e,v.replaceChildren(O(e?"x":"key"),t("span",{},e?"Hide key":"Show key")),o()}},O("key"),t("span",{},"Show key"));return o(),t("div",{class:"pane"},t("div",{class:"filecard"},t("span",{class:"filecard-ic"},".conf"),t("span",{class:"stack"},t("span",{class:"mono ellipsis"},n.filename),t("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),t("button",{class:"btn primary",onclick:()=>je(n.filename,n.conf)},O("download"),t("span",{},"Download"))),t("details",{class:"confbox"},t("summary",{},O("chevron"),t("span",{},"Configuration"),t("span",{class:"grow"}),v,t("button",{class:"btn small",onclick:p=>{p.preventDefault(),ve(n.conf,"Configuration copied")}},O("copy"),t("span",{},"Copy"))),a))}async function fe(n,e,a){let o=a!=null?a:await Te(n);if(!o)return;let v=await xe(o,`${o.server} · ${o.name}`),p=ke(),_={app:()=>t("div",{class:"pane"},t("a",{class:"btn primary block big",href:v},O("open"),t("span",{},"Open in AmneziaVPN")),t("ol",{class:"steps"},t("li",{},"No AmneziaVPN yet? ",t("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),t("li",{},"Tap ",t("b",{},"Open in AmneziaVPN")," and confirm the import."),t("li",{},"Turn the connection on — this page shows ",t("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let H=t("div",{class:"qr"});return H.innerHTML=qe(o.conf),t("div",{class:"pane center"},H,t("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>t("div",{class:"pane"},t("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),t("div",{class:"keybox"},t("span",{class:"mono"},v),t("button",{class:"btn small",onclick:()=>ve(v,"Key copied")},"Copy")),t("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Et(o)},$=p?["app","qr","key","file"]:["qr","key","file"],B={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=t("div",{class:"tab-body"}),F=t("div",{class:"tabs",role:"tablist"}),J=H=>{F.querySelectorAll("button").forEach(ne=>ne.classList.toggle("on",ne.dataset.id===H)),D.replaceChildren(_[H]())};for(let H of $)F.appendChild(t("button",{role:"tab","data-id":H,onclick:()=>J(H)},B[H]));J(e&&$.includes(e)?e:$[0]);let U=t("div",{class:"waiting"}),N=H=>{H!=null&&H.online?U.replaceChildren(t("i",{class:"dot ok"}),t("span",{class:"ok"},`${n.name} is connected`)):H!=null&&H.handshake?U.replaceChildren(t("i",{class:"dot"}),t("span",{class:"muted"},`Last connected ${ye(H.handshake)}`)):U.replaceChildren(t("i",{class:"dot warn pulse"}),t("span",{class:"muted"},"Waiting for the first connection…"))};N(n);let G=window.setInterval(async()=>{try{let H=await oe("state");R=H,N(H.person.devices.find(ne=>ne.id===n.id))}catch{}},5e3);pe(n.handshake?`Connect ${n.name}`:`${n.name} is ready`,p?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",F,D,U),le=()=>{clearInterval(G),R&&ge(R)}}function Bt(n){let e=t("input",{type:"text",value:n.name,maxlength:48,"aria-label":"Device name"});pe(`Rename ${n.name}`,null,t("form",{class:"stack gap",onsubmit:async a=>{a.preventDefault();try{R=(await oe(`devices/${n.id}`,{action:"rename",name:e.value})).state,te(),ge(R),se("Renamed")}catch(o){se(o.message,!0)}}},e,t("button",{class:"btn primary block",type:"submit"},"Save"))),setTimeout(()=>e.select(),50)}function Dt(n){pe(`Remove ${n.name}?`,null,t("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),t("div",{class:"row gap"},t("button",{class:"btn block",onclick:()=>te()},"Cancel"),t("button",{class:"btn danger-solid block",onclick:async()=>{try{R=(await oe(`devices/${n.id}`,{action:"delete"})).state,te(),ge(R),se("Device removed")}catch(e){se(e.message,!0)}}},"Remove")))}var V=navigator.userAgent,Qe=/iPad/.test(V)||/Macintosh/.test(V)&&navigator.maxTouchPoints>1;function Me(){return Qe||/Tablet/i.test(V)||/Android/.test(V)&&!/Mobile/.test(V)?"tablet":/Android|iPhone|Mobile/i.test(V)?"phone":"computer"}var $t=[[/^SM-S93/,"Galaxy S25"],[/^SM-S92/,"Galaxy S24"],[/^SM-S91/,"Galaxy S23"],[/^SM-S90/,"Galaxy S22"],[/^SM-G99/,"Galaxy S21"],[/^SM-F9/,"Galaxy Z Fold"],[/^SM-F7/,"Galaxy Z Flip"],[/^SM-A5/,"Galaxy A5x"],[/^SM-A3/,"Galaxy A3x"],[/^SM-X/,"Galaxy Tab"]],_e="",Pt=(async()=>{var e;let n=navigator.userAgentData;if(!n||!/Android/.test(V))return"";try{let a=((e=(await n.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!a||a==="K")return"";let o=$t.find(([v])=>v.test(a));_e=o?`${o[1]} (${a})`:/^SM-/.test(a)?`Galaxy ${a}`:a}catch{}return _e})();function St(n){return/iPhone/.test(V)?"iPhone":Qe?"iPad":/Android/.test(V)?_e||(n==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(V)?"Chromebook":/Mac OS X/.test(V)?"Mac":/Windows/.test(V)?"Windows PC":/Linux/.test(V)?"Linux PC":ue[n]}function Rt(){if(!R)return;let n=Me(),e=new Set(R.person.devices.map(B=>B Line truncated `,ln(w,t)]:[ln(w,t)])),i&&r.querySelectorAll(".conf-v, .conf-mask").forEach(w=>w.classList.add("unmask"))},s=n("button",{class:"btn small",onclick:i=>{i.preventDefault(),t=!t,s.replaceChildren(I(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),ne(s,"swap"),a(!0)}},I("key"),n("span",{},"Show key"));return a(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},Te()?"For computers and routers: import it in any WireGuard app":"For computers and routers: import it in AmneziaWG or AmneziaVPN")),ut(e)?n("button",{class:"btn primary",onclick:()=>ut(e)()},I("open"),n("span",{},"Share file")):n("button",{class:"btn primary",onclick:()=>ze(e.filename,e.conf)},I("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},I("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),s,n("button",{class:"btn small",onclick:i=>{i.preventDefault(),ue(e.conf,"Configuration copied",i.currentTarget)}},I("copy"),n("span",{},"Copy"))),r))}async function pt(e,t,r){let a=r!=null?r:await Ge(e);if(!a)return;let s=await Be(a,`${a.server} · ${a.name}`),i=fn(),w=e.kind==="phone"||e.kind==="tablet",h={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:s},I("amnezia"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:on().href,target:"_blank",rel:"noopener noreferrer"},on().label),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let G=n("div",{class:"qr"}),v=n("p",{class:"muted s"}),f=n("div",{class:"seg"}),d=Te()?"conf":"vpn",k=()=>{},u=(x=!1)=>{let l=d==="vpn"?s:a.conf;vt(G,l),v.textContent=d==="vpn"?"Scan with the phone’s camera or inside AmneziaVPN.":Te()?"Scan inside the AmneziaWG, WireGuard or AmneziaVPN app.":"Scan inside the AmneziaWG app (or AmneziaVPN).",f.querySelectorAll(":scope > button").forEach(o=>o.classList.toggle("on",o.dataset.m===d)),k(),x&&(ne(G,"swap"),ne(v,"swap"))};for(let[x,l]of[["vpn","AmneziaVPN"],["conf",Te()?"WireGuard app":"AmneziaWG app"]])f.appendChild(n("button",{type:"button","data-m":x,onclick:()=>{d!==x&&(d=x,u(!0))}},l));return u(),k=tt(f),n("div",{class:"pane center"},f,G,v,dt())},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},s),n("button",{class:"btn small",onclick:G=>ue(s,"Key copied",G.currentTarget)},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>An(a)},M=i&&w?["app","qr","key","file"]:w?["qr","key","file"]:["file","key","qr"],A={app:"Open in app",qr:"QR code",key:"Key",file:"File"},D=n("div",{class:"tab-body"}),T=n("div",{class:"tabs",role:"tablist"}),R=-1,z=()=>{},U=G=>{let v=M.indexOf(G);T.querySelectorAll(":scope > button").forEach(f=>{f.classList.toggle("on",f.dataset.id===G),f.setAttribute("aria-selected",String(f.dataset.id===G))}),z(),R<0?D.replaceChildren(h[G]()):v!==R&&et(D,[h[G]()],Math.sign(v-R)),R=v};for(let G of M)T.appendChild(n("button",{role:"tab","data-id":G,onclick:()=>U(G)},A[G]));U(t&&M.includes(t)?t:M[0]),z=tt(T);let F=e.handshake||e.disabled?null:rt(e.kind),V=F?$n(e,()=>void Tn(F,[T,D]),F.gaveUp):()=>{};$e(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,i&&w?"Add it to AmneziaVPN on this phone":w?"Scan with the phone’s camera or AmneziaVPN":"Import the file in AmneziaWG or AmneziaVPN",F==null?void 0:F.el,T,D,e.handshake?mr(e):null),ce=()=>{V(),S&&ye(S)}}function mr(e){return n("div",{class:"waiting"},e.online?n("span",{class:"ok"},"Connected"):n("span",{class:"muted"},`Last connected ${Ue(e.handshake,mt())}`))}async function Tn(e,t){var r;e.connected(),(r=e.el.closest(".sheet-panel"))==null||r.scrollTo({top:0,behavior:ie()?"auto":"smooth"}),await It(400),await Promise.all(t.map(a=>Ot(a))),await new Promise(a=>setTimeout(a,2e3)),re!=null&&re.contains(e.el)&&!e.el.closest(".ghost")&&de()}function En(e,t=4){window.setTimeout(async()=>{var r;try{let a=await he("state");S=a,!re&&!ve&&ye(a),!((r=a.person.devices.find(s=>s.id===e))!=null&&r.online)&&t>1&&En(e,t-1)}catch{}},1500)}function $n(e,t,r){let a=mt(),s=0,i=0,w=!1,h=Date.now(),M=async()=>{if(s=0,!w){if(Date.now()-h>6e5){w=!0,r();return}if(document.hidden){A();return}try{let T=await he("state");S=T;let R=T.person.devices.find(z=>z.id===e.id);if(R&&R.handshake>a){w=!0,t(),R.online||En(e.id);return}}catch(T){if(T.status===404||T.status===401){w=!0;return}}i++,A()}},A=()=>{!w&&!s&&(s=window.setTimeout(M,i<6?5e3:i<12?15e3:3e4))},D=()=>{!document.hidden&&!w&&!s&&M()};return document.addEventListener("visibilitychange",D),A(),()=>{w=!0,s&&clearTimeout(s),document.removeEventListener("visibilitychange",D)}}var Sn=e=>`dl.app.${e.id}`;function gr(e){try{let t=loc Line truncated
@@ -0,0 +1,22 @@
#!/usr/bin/ucode
// Dawnline personal portal as a CGI script: the request handling itself is
// dawnline.portal. www/cgi-bin/portal (a shell) runs it for requests shaped
// like a personal link and answers the rest itself.
'use strict';
import { stdin } from 'fs';
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',
// The visitor behind Cloudflare (believed only when REMOTE_ADDR is Cloudflare's).
'HTTP_CF_CONNECTING_IP' ])
env[k] = getenv(k);
serve({
env,
headers: {},
read: (n) => stdin.read(n),
write: (s) => print(s),
});
@@ -1,344 +1,51 @@
#!/usr/bin/ucode #!/bin/sh
// Dawnline personal portal (CGI behind a dedicated uhttpd instance). # Dawnline personal portal, the door: uhttpd runs this for every request.
// # Anything that is not shaped like a personal link (/<word-code>[/…]) gets
// GET /<code> the app shell (<code> = three words, the personal link) # the portal's bare answer from here, in a shell that costs nothing, so a
// GET /<code>/assets/<file> its script, styles, fonts # scanner or a flood on the root never starts ucode (compiling the portal's
// GET /<code>/api/state # module graph is ~140 ms of CPU). Links go on to the portal itself
// POST /<code>/api/devices { name, kind, public_key? } # (/usr/share/dawnline/portal/cgi.uc), which judges the code.
// GET /<code>/api/devices/<id>/config #
// POST /<code>/api/devices/<id> { action: rename|delete, name? } # The answer here is byte for byte the portal's own not_found(): keep both
// # in step (dawnline.portal headers(), SECURITY_HEADERS, not_found()).
// 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 —
// the root, a person's link, the API and the assets alike — so nothing tells
// a scanner there is a portal here. Wrong codes are rate-limited per IP
// (blocked addresses get the same 404 even with the right code).
// Regenerating the code in LuCI locks the old link out at once. POST bodies
// must be JSON from the same origin; Referrer-Policy keeps the code out of
// other sites' logs.
//
// The portal can only manage the person's own devices within their limit.
'use strict';
import { stdin, stat, unlink, readfile } from 'fs'; path="${REQUEST_URI%%\?*}"
import { w='[a-z][a-z][a-z][a-z][a-z][a-z]'
read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, VERSION, RUN_DIR, DATA_DIR # The expansion is meant as a pattern (a word of six letters), not literally.
} from 'dawnline.util'; # shellcheck disable=SC2254
import * as core from 'dawnline.core'; case "$path" in
import * as live from 'dawnline.live'; /$w-$w-$w|/$w-$w-$w/*) exec /usr/bin/ucode /usr/share/dawnline/portal/cgi.uc ;;
import * as apply from 'dawnline.apply'; esac
import * as view from 'dawnline.view';
const RATE = `${RUN_DIR}/portal-rate.json`; # HSTS pins the whole name: only when the visitor is on the standard port.
const ASSETS = '/usr/share/dawnline/portal/assets'; hsts=
const TYPES = { js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml', woff2: 'font/woff2' }; if [ "$HTTPS" = on ]; then
const FAIL_LIMIT = 8; port="${HTTP_HOST##*:}"
const FAIL_WINDOW = 900; case "$HTTP_HOST" in *:*) ;; *) port=443 ;; esac
case "$HTTP_HOST" in *\]) port=443 ;; esac
[ "$port" = 443 ] && hsts=1
fi
const SECURITY_HEADERS = { # Files always get the 404: a missing asset must not turn into someone's website.
'X-Content-Type-Options': 'nosniff', file=
'Referrer-Policy': 'no-referrer', case "$path" in
'X-Frame-Options': 'DENY', /luci-static|/luci-static/*|/cgi-bin|/cgi-bin/*|/ubus|/ubus/*) file=1 ;;
'Cache-Control': 'no-store', *) case "${path##*/}" in *.*) file=1 ;; esac ;;
'Strict-Transport-Security': 'max-age=31536000', esac
}; redirect=
[ -n "$file" ] || redirect="$(uci -q get dawnline.settings.portal_redirect)"
function headers(status, extra) { if [ -n "$redirect" ]; then
let h = `Status: ${status}\r\n`; printf 'Status: 302 Found\r\n'
for (let k, v in { ...SECURITY_HEADERS, ...(extra ?? {}) }) printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
h += `${k}: ${v}\r\n`; printf 'Location: %s\r\nContent-Type: text/plain\r\n' "$redirect"
print(h + '\r\n'); [ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
} printf '\r\nMoved\n'
else
function send_json(status, obj, extra) { printf 'Status: 404 Not Found\r\n'
headers(status, { 'Content-Type': 'application/json', ...(extra ?? {}) }); printf 'X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\nCache-Control: no-store\r\n'
print(sprintf('%J', obj)); printf 'Content-Type: text/plain\r\n'
exit(0); [ -n "$hsts" ] && printf 'Strict-Transport-Security: max-age=31536000\r\n'
} printf '\r\nNot found\n'
fi
function fail(status, msg) { exit 0
send_json(status, { error: msg });
}
function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
function page(status, base, title, code) {
// The build's time joins the version so every update busts the hour-long asset cache.
let q = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
headers(status, {
'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'; " +
"connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'",
});
print(`<!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="color-scheme" content="light dark">
<meta name="robots" content="noindex, nofollow">
<title>${html_escape(title)}</title>
<link rel="icon" href="${base}/assets/icon.svg${q}" type="image/svg+xml">
<link rel="stylesheet" href="${base}/assets/portal.css${q}">
</head>
<body>
<div id="app" data-base="${html_escape(base ?? '')}" data-title="${html_escape(title)}"></div>
<script src="${base}/assets/portal.js${q}" defer></script>
</body>
</html>
`);
exit(0);
}
/* ---------- request ---------- */
const method = getenv('REQUEST_METHOD') ?? 'GET';
const uri = getenv('REQUEST_URI') ?? '/';
// Behind a Cloudflare-proxied hostname every request comes from Cloudflare,
// and uhttpd does not hand CF-Connecting-IP to CGI: all those visitors share
// one bucket with a higher limit (three-word codes can't be guessed anyway).
const peer = getenv('REMOTE_ADDR') ?? '';
const via_cf = cloudflare_ip(peer);
const ip = via_cf ? 'cloudflare' : peer;
const fail_limit = via_cf ? FAIL_LIMIT * 25 : FAIL_LIMIT;
const qpos = index(uri, '?');
const path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
const query = qpos >= 0 ? substr(uri, qpos + 1) : '';
const segs = filter(split(path, '/'), (s) => s != '');
function query_param(name) {
for (let kv in split(query, '&')) {
let eq = index(kv, '=');
if (eq > 0 && substr(kv, 0, eq) == name)
return substr(kv, eq + 1);
}
return null;
}
function body() {
let len = +(getenv('CONTENT_LENGTH') ?? 0);
if (len <= 0)
return {};
if (len > 8192)
fail('413 Payload Too Large', 'Request too large.');
let raw = stdin.read(len);
try {
let j = json(raw);
return type(j) == 'object' ? j : {};
}
catch (e) {
fail('400 Bad Request', 'Invalid JSON.');
}
}
/* ---------- rate limiting ---------- */
function rate_state() {
let st = read_json(RATE, {});
let now = time();
for (let k, v in st)
if (now - v.first > FAIL_WINDOW)
delete st[k];
return st;
}
function rate_blocked() {
let v = rate_state()[ip];
return v != null && v.count >= fail_limit;
}
function rate_fail() {
let l = lock('portal-rate');
let st = rate_state();
let v = st[ip] ?? { first: time(), count: 0 };
v.count++;
st[ip] = v;
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
if (v.count == fail_limit)
live.add_event({ type: 'portal_blocked', detail: ip });
}
// Older versions kept sign-in sessions on flash; they mean nothing now.
if (stat(`${DATA_DIR}/sessions.json`))
unlink(`${DATA_DIR}/sessions.json`);
/* ---------- routing ---------- */
let m = core.load();
const redirect = m.settings.portal_redirect;
/**
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
* Files and LuCI's own paths always get the 404: at home this script is LuCI's error page, and a
* missing script must not turn into someone's website.
*/
function not_found() {
let parts = split(split(uri, '?')[0], '/');
let file = match(uri, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
if (redirect && !file) {
headers('302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
print('Moved\n');
}
else {
headers('404 Not Found', { 'Content-Type': 'text/plain' });
print('Not found\n');
}
exit(0);
}
const title = m.settings.portal_title || 'Dawnline';
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
// for it); names, and LuCI's web server at home, stay HTTPS-only.
if (getenv('HTTPS') != 'on') {
let h = getenv('HTTP_HOST') ?? '';
h = match(h, /^\[/) ? h : split(h, ':')[0];
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
not_found();
}
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
not_found();
const code = segs[0];
const base = `/${code}`;
const rest = slice(segs, 1);
let person = null;
for (let id, p in m.people)
if (p.code == code)
person = p;
// A wrong code or a blocked address: indistinguishable from a path that does
// not exist. Only well-formed guesses count towards the limit.
if (rate_blocked())
not_found();
if (person == null) {
rate_fail();
not_found();
}
const person_id = person.id;
// The app shell; it reads the code from its own URL and sends it along.
if (length(rest) == 0 && method == 'GET')
page('200 OK', base, title, code);
// Script, styles, icon and fonts (kept outside the web root).
if (rest[0] == 'assets' && length(rest) == 2 && method == 'GET') {
let name = rest[1];
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2)$/)?.[1];
let data = ext ? readfile(`${ASSETS}/${name}`) : null;
if (data == null)
not_found();
headers('200 OK', { 'Content-Type': TYPES[ext], 'Cache-Control': 'private, max-age=3600' });
print(data);
exit(0);
}
if (rest[0] != 'api')
not_found();
// CSRF: only same-origin JSON requests (uhttpd passes no custom headers to
// CGI; a cross-site page cannot send application/json without CORS, and it
// would need the code anyway).
if (method == 'POST') {
let origin = getenv('HTTP_ORIGIN');
if (!match(getenv('CONTENT_TYPE') ?? '', /^application\/json/) ||
(origin != null && origin != `${getenv('HTTPS') == 'on' ? 'https' : 'http'}://${getenv('HTTP_HOST')}`))
fail('403 Forbidden', 'Cross-site request refused.');
}
else if (method != 'GET')
fail('405 Method Not Allowed', 'Method not allowed.');
const api = slice(rest, 1);
function state() {
let usage = core.load_usage();
let dmp = live.dump();
let v = view.person_view(m, person, usage, dmp, view.states(m, usage));
let srv = m.servers[person.server];
return {
title,
person: v,
server: { name: srv?.name, endpoint: core.endpoint_host(m, srv) },
can_add: length(person.devices) < person.device_limit,
kinds: core.KINDS,
version: VERSION,
};
}
function own_device(id) {
let d = m.devices[id];
if (!d || d.person != person.id)
fail('404 Not Found', 'Device not found.');
return d;
}
if (api[0] == 'state' && method == 'GET')
send_json('200 OK', state());
if (api[0] == 'devices' && length(api) == 1 && method == 'POST') {
let b = body();
let l = lock('config');
let id;
try {
let c = core.open_cursor();
m = core.load(c);
person = m.people[person_id];
id = core.create_device(c, m, person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key || null });
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
}
catch (e) {
unlock(l);
fail('400 Bad Request', e.message);
}
unlock(l);
apply.sync();
m = core.load();
person = m.people[person_id];
live.add_event({ type: 'device_added', person: person.id, device: id, detail: `${m.devices[id].name} (portal)` });
core.mark_issued(m, id);
send_json('200 OK', { id, config: core.client_config(m, m.devices[id]), state: state() });
}
if (api[0] == 'devices' && length(api) == 3 && api[2] == 'config' && method == 'GET') {
let d = own_device(api[1]);
core.mark_issued(m, d.id);
send_json('200 OK', core.client_config(m, d));
}
if (api[0] == 'devices' && length(api) == 2 && method == 'POST') {
own_device(api[1]);
let b = body();
let l = lock('config');
try {
let c = core.open_cursor();
m = core.load(c);
if (b.action == 'rename')
core.rename_device(c, m, api[1], b.name);
else if (b.action == 'delete') {
let d = m.devices[api[1]];
core.delete_device(c, m, api[1]);
live.add_event({ type: 'device_removed', person: person.id, device: api[1], detail: `${d.name} (portal)` });
}
else
die('Unknown action.');
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
}
catch (e) {
unlock(l);
fail('400 Bad Request', e.message);
}
unlock(l);
if (b.action == 'delete')
apply.sync();
m = core.load();
person = m.people[person_id];
send_json('200 OK', { ok: true, state: state() });
}
fail('404 Not Found', 'Not found.');
@@ -28,8 +28,6 @@
} }
}, },
"admin/network/dawnline/activity": { "admin/network/dawnline/activity": {
"title": "Activity",
"order": 25,
"action": { "action": {
"type": "view", "type": "view",
"path": "dawnline/activity" "path": "dawnline/activity"
@@ -49,9 +47,15 @@
"path": "dawnline/server" "path": "dawnline/server"
} }
}, },
"admin/network/dawnline/health": { "admin/network/dawnline/diagnostics": {
"title": "Health", "title": "Diagnostics",
"order": 40, "order": 40,
"action": {
"type": "view",
"path": "dawnline/diagnostics"
}
},
"admin/network/dawnline/health": {
"action": { "action": {
"type": "view", "type": "view",
"path": "dawnline/health" "path": "dawnline/health"
@@ -66,7 +70,7 @@
} }
}, },
"admin/network/dawnline/updates": { "admin/network/dawnline/updates": {
"title": "Updates", "title": "Components",
"order": 70, "order": 70,
"action": { "action": {
"type": "view", "type": "view",
@@ -4,32 +4,32 @@
"read": { "read": {
"ubus": { "ubus": {
"luci.dawnline": [ "luci.dawnline": [
"rev",
"status", "status",
"setup_defaults", "setup_defaults",
"health", "health",
"service_log",
"backup_list", "backup_list",
"updates_status", "updates_status",
"updates_releases",
"updates_notes",
"updates_changes",
"person_usage", "person_usage",
"settings_get", "settings_get",
"portal_info",
"interfaces", "interfaces",
"server_ports",
"endpoint_probe",
"events" "events"
] ]
}, }
"uci": [
"dawnline",
"network",
"firewall"
]
}, },
"write": { "write": {
"ubus": { "ubus": {
"luci.dawnline": [ "luci.dawnline": [
"*" "*"
] ]
}, }
"uci": [
"dawnline"
]
} }
} }
} }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,265 @@
// Dawnline: "Check access" — walks the same rules the nft table and the
// client configuration apply, and says in words where a connection stops.
'use strict';
import { ip2int, in_nets } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as awg from 'dawnline.awg';
const STATE_TEXT = {
no_server: 'they have no server',
server_off: 'their server is turned off',
paused: 'they are paused',
expired: 'their access has ended',
quota: 'they used up their data',
hours: 'it is outside their allowed hours',
};
const ACCESS_TEXT = { lan: 'Home only', internet: 'Internet only', both: 'Home and Internet' };
function step(ok, title, detail) {
return { ok: !!ok, title, detail: detail ?? '' };
}
/** Add the step where it stops and end the walk. */
function stop(steps, s) {
push(steps, s);
return steps;
}
/** The tunnel subnet (of any server) that holds `ip`: never home, whatever routes cover it. */
function in_tunnels(m, ip) {
let nets = [];
for (let id, s in m.servers)
for (let t in core.tunnels(s))
push(nets, t.subnet);
return in_nets(ip, nets);
}
/** "10.0.1.20:445" → [ip, port]; a device id → its address. */
function parse_target(m, s) {
s = trim(`${s ?? ''}`);
if (m.devices[s])
return { dev: m.devices[s], ip: m.devices[s].address, port: null };
let mm = match(s, /^([0-9.]+)(:([0-9]{1,5}))?$/);
if (!mm || ip2int(mm[1]) == null)
return null;
let ip = mm[1];
for (let id, d in m.devices)
if (d.address == ip)
return { dev: d, ip, port: mm[3] ? +mm[3] : null };
return { ip, port: mm[3] ? +mm[3] : null };
}
function home_access(p) {
return p.access == 'both' || (p.access == 'lan' && !length(p.services));
}
function peer_of(dmp, d) {
return dmp.peers[d.public_key];
}
/** What the device sends to the router: its configuration's AllowedIPs. */
function routed(m, srv, p, d) {
return { nets: awg.allowed_ips(m, srv, p), what: 'Its configuration', list: null };
}
/** The home network (interface) of a server that holds an address. */
function home_dev_of(srv, ip, snap) {
for (let h in net.server_net(srv, snap).home)
if (in_nets(ip, h.nets))
return h.dev;
return null;
}
function router_addrs(snap) {
let out = [];
for (let dev, d in snap.devices)
for (let a in d.addrs ?? [])
push(out, split(a, '/')[0]);
return out;
}
function person_ok(m, p, d, states) {
let st = states[p.id] ?? 'active';
if (d.disabled)
return step(false, `${d.name} is turned off`, 'Turn the device on again on its page.');
if (st != 'active')
return step(false, `${p.name} can't connect: ${STATE_TEXT[st] ?? st}`, '');
return step(true, `${p.name} is active`, ACCESS_TEXT[p.access]);
}
function connected(dmp, d, who) {
let peer = peer_of(dmp, d);
if (!peer || !(peer.handshake > 0))
return step(false, `${who} has never connected`, 'There is no session the router could reach.');
if (!live.online(dmp, d.id, peer))
return step(false, `${who} isn't connected right now`, 'The router reaches it only while its VPN is on.');
return step(true, `${who} is connected`, '');
}
/** A device → somewhere: the router, home, another device or the internet. */
function from_device(m, d, t, states, dmp, snap) {
let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null;
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
let steps = [ person_ok(m, p, d, states) ];
if (!steps[0].ok)
return steps;
let r = routed(m, srv, p, d);
let allowed = r.nets;
let via = (ip) => {
let hit = in_nets(ip, allowed);
let what = r.list ? `${r.what}: ${r.list}` : `AllowedIPs ${join(', ', filter(allowed, (x) => index(x, ':') < 0))}`;
return hit
? step(true, `${r.what} sends it to the router`, what)
: step(false, `${r.what} doesn't send it to the router`, `${what}: the device's own network handles it.`);
};
// Another device.
if (t.dev) {
let q = m.people[t.dev.person];
let who = `${q?.name ?? '?'} · ${t.dev.name}`;
if (t.dev.id == d.id)
return [ step(false, 'That is the same device', '') ];
if (!q || q.server != p.server)
return stop(steps, step(false, `${who} is on another server`, 'Devices of different servers never reach each other.'));
if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${ACCESS_TEXT[p.access]}`, 'Only people with home access reach other devices.'));
if (!home_access(q))
return stop(steps, step(false, `${q.name} has ${ACCESS_TEXT[q.access]}`, 'Only devices of people with home access can be reached.'));
if (srv.mesh == 'off')
return stop(steps, step(false, `"Devices reach each other" is off on ${srv.name}`, 'Server → Access → Home network.'));
if (srv.mesh == 'circles' && q.id != p.id) {
let a = core.person_circle(m, p), b = core.person_circle(m, q);
if (!a || !b || a.id != b.id)
return stop(steps, step(false, `${p.name} and ${q.name} are not in one circle`,
`${p.name}: ${a?.name ?? 'no circle'} · ${q.name}: ${b?.name ?? 'no circle'}`));
push(steps, step(true, `Both are in ${a.name}`, 'Devices in one circle reach each other.'));
}
else
push(steps, step(true, q.id == p.id ? `Both are ${p.name}'s devices` : 'Devices reach each other on this server', ''));
let st = states[q.id] ?? 'active';
if (st != 'active' || t.dev.disabled)
return stop(steps, step(false, `${who} can't be reached: ${t.dev.disabled ? 'it is turned off' : STATE_TEXT[st] ?? st}`, ''));
push(steps, via(t.ip));
push(steps, connected(dmp, t.dev, who));
return steps;
}
// 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)));
if (t.port == 53)
push(steps, step(true, `${t.ip} is this router: DNS is open to everyone`, ''));
else if (portal)
push(steps, step(true, `${t.ip} is this router: the personal portal is open to everyone`, ''));
else if (!home_access(p))
return stop(steps, step(false, `${t.ip} is this router`, `${p.name} has ${ACCESS_TEXT[p.access]}: only DNS and the portal on the router.`));
else {
// Like any home address: only on the networks the person reaches.
let h = core.person_home(srv, p, snap);
if (!h.all && !in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is this router on a network ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is this router`, h.all ? 'Home access includes the router.' : `On one of the networks ${p.name} reaches.`));
}
push(steps, via(t.ip));
return steps;
}
// A tunnel address no device has.
let tn = in_tunnels(m, t.ip);
if (tn)
return stop(steps, step(false, `No device uses ${t.ip}`, `It is in the tunnel network ${tn}.`));
// Home.
let sn = net.server_net(srv, snap);
let hdev = home_dev_of(srv, t.ip, snap);
if (hdev) {
if (p.access == 'internet')
return stop(steps, step(false, `${t.ip} is at home (${hdev})`, `${p.name} has Internet only.`));
if (p.access == 'lan' && length(p.services)) {
let hit = null;
for (let sid in p.services) {
let s = m.services[sid];
if (s?.address == t.ip && (!length(s.ports) || t.port == null || index(s.ports, `${t.port}`) >= 0))
hit = s;
}
let names = join(', ', map(filter(map(p.services, (x) => m.services[x]), (x) => x), (x) => x.name));
if (!hit)
return stop(steps, step(false, `${t.ip}${t.port ? `:${t.port}` : ''} is not one of ${p.name}'s home services`, `Allowed: ${names}`));
push(steps, step(true, `${t.ip} is ${hit.name}, one of ${p.name}'s home services`,
length(hit.ports) ? `Ports ${join(', ', hit.ports)}` : 'All ports'));
}
else {
let h = core.person_home(srv, p, snap);
if (!in_nets(t.ip, h.nets))
return stop(steps, step(false, `${t.ip} is in ${hdev}, which ${p.name} doesn't reach`, `${p.name} reaches ${join(', ', h.devs) || 'no home network'}.`));
push(steps, step(true, `${t.ip} is in ${hdev}`, h.all ? 'Home access reaches every home network.' : `One of the networks ${p.name} reaches.`));
}
push(steps, via(t.ip));
push(steps, step(true, 'The firewall lets it through', `${srv.ifname} → ${join(', ', sn.zones) || 'home'}`));
return steps;
}
// Another private address, or the internet.
if (in_nets(t.ip, [ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '100.64.0.0/10', '169.254.0.0/16' ]))
return stop(steps, step(false, `${t.ip} isn't in ${srv.name}'s home network`, 'Private addresses outside the home network are blocked.'));
if (p.access == 'lan')
return stop(steps, step(true, `${t.ip} is on the internet`, `${p.name} has Home only: their device's own internet reaches it, not the tunnel.`));
push(steps, via(t.ip));
push(steps, step(true, `${t.ip} is on the internet`, srv.lan_like ? 'It leaves like a home device would.' : `It leaves through ${sn.wan.dev ?? 'the WAN'}.`));
return steps;
}
/** A home address → a device. */
function to_device(m, ip, d, states, dmp, snap) {
let p = m.people[d.person];
let srv = p ? m.servers[p.server] : null;
if (!p || !srv)
return [ step(false, `${d.name} has no server`, '') ];
let who = `${p.name} · ${d.name}`;
let hdev = in_tunnels(m, ip) ? null : home_dev_of(srv, ip, snap);
if (!hdev)
return [ step(false, `${ip} isn't in ${srv.name}'s home network`, 'Only home devices reach people\'s devices.') ];
let steps = [ step(true, `${ip} is at home (${hdev})`, '') ];
if (!home_access(p))
return stop(steps, step(false, `${p.name} has ${p.access == 'lan' ? 'only some home services' : ACCESS_TEXT[p.access]}`,
'Home devices reach only people with home access.'));
let h = core.person_home(srv, p, snap);
if (!in_nets(ip, h.nets))
return stop(steps, step(false, `${p.name} doesn't reach ${hdev}`, 'Networks a person does not reach cannot reach them either.'));
push(steps, person_ok(m, p, d, states));
if (!steps[length(steps) - 1].ok)
return steps;
push(steps, step(true, 'The firewall lets it through', `${join(', ', net.server_net(srv, snap).zones) || 'home'} → ${srv.ifname}`));
push(steps, connected(dmp, d, who));
return steps;
}
/** `from` and `to`: a device id, or an IPv4 address (optionally :port). */
export function check(m, from, to) {
let a = parse_target(m, from), b = parse_target(m, to);
if (!a)
die(`"${from}" is not a device or an IPv4 address.`);
if (!b)
die(`"${to}" is not a device or an IPv4 address.`);
let usage = core.load_usage();
let states = view.states(m, usage);
let dmp = live.dump(m);
let snap = net.snapshot(true);
let steps;
if (a.dev)
steps = from_device(m, a.dev, b, states, dmp, snap);
else if (b.dev)
steps = to_device(m, a.ip, b.dev, states, dmp, snap);
else
die('Choose a device on at least one side.');
let ok = length(filter(steps, (s) => !s.ok)) == 0;
return { ok, steps };
};
@@ -1,424 +1,51 @@
// Dawnline — reconciliation. Turns /etc/config/dawnline into router state: // Dawnline — reconciliation. Turns /etc/config/dawnline into router state:
// * network interfaces (proto amneziawg), peers applied live with `awg syncconf` // * network interfaces (dawnline.netifd) and the devices loaded live into
// * firewall zones, forwardings and WAN rules (named sections dawnline_*) // them (dawnline.awg)
// * nft table `inet dawnline` enforcing each person's access // * firewall zones, forwardings, WAN rules and reply routes (dawnline.fw)
// * the nft table `inet dawnline` enforcing each person's access (dawnline.nft)
// * hostnames in /tmp/hosts/dawnline // * hostnames in /tmp/hosts/dawnline
// * the "like a home device" path and the Home-only resolver (dawnline.loop) // * the "like a home device" path and the Home-only resolver (dawnline.loop)
// Only objects created by Dawnline are ever modified. // Only objects created by Dawnline are ever modified.
//
// apply(), sync() and sync_loop() run under one lock ('apply') and read the
// model inside it, so a rebuild and a runtime update never interleave and the
// last one to run always works from the newest configuration. The config lock
// (dawnline.store) is never taken while 'apply' is held.
import { cursor } from 'uci';
import { readfile, writefile, stat, unlink } from 'fs'; import { readfile, writefile, stat, unlink } from 'fs';
import { import { ensure_dir, write_file, write_json, with_lock, ip2int, slog, RUN_DIR } from 'dawnline.util';
q, sh, sh_out, sh_bg, ensure_dir, write_file, write_json, read_json, parse_cidr, int2ip, uniq,
lock, unlock, RUN_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop'; import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as nft from 'dawnline.nft';
import * as fw from 'dawnline.fw';
import * as netifd from 'dawnline.netifd';
import * as migrate from 'dawnline.migrate';
const HOSTS_FILE = '/tmp/hosts/dawnline'; const HOSTS_FILE = '/tmp/hosts/dawnline';
/* /** The network signature the last apply() worked from (the agent compares against it). */
* Our own answers leave by the main table: the portal's (TCP) and each export const NET_SIG = `${RUN_DIR}/net.sig`;
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule) may mark // The last access-table error that was logged (each distinct failure once).
* the router's own traffic to internet addresses and divert it locally, which const NFT_ERR = `${RUN_DIR}/nft.err`;
* swallows replies to outside clients. These rules sit before such fwmark
* rules and only match our listening ports.
*/
const PREF_REPLY = 90;
function log(msg) { function log(who, msg, level, detail) {
system(`logger -t dawnline ${q(msg)}`); slog('dawnline', level ?? 'info', msg, detail, who);
} }
/* ---------- helpers ---------- */
/** Set an option only when it differs; returns true if something changed. */
function put(c, conf, sec, opt, val) {
let cur = c.get(conf, sec, opt);
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
if (cur != null) {
c.delete(conf, sec, opt);
return true;
}
return false;
}
if (type(val) == 'array') {
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
return false;
}
else if (cur == `${val}`)
return false;
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
return true;
}
function ensure_section(c, conf, sec, stype) {
if (c.get(conf, sec) == stype)
return false;
if (c.get(conf, sec) != null)
c.delete(conf, sec);
c.set(conf, sec, stype);
return true;
}
/**
* After committing a config ourselves (and applying it), record its new
* checksum so a later `reload_config` does not treat it as changed and
* restart unrelated services that reload on any network change.
*/
function ack_config(confs) {
let md5f = '/var/run/config.md5';
if (!stat(md5f))
return;
let lines = split(trim(readfile(md5f) ?? ''), '\n');
for (let conf in confs) {
let path = `/var/run/config.check/${conf}`;
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
if (!sum)
continue;
let found = false;
for (let i = 0; i < length(lines); i++)
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
lines[i] = `${sum} ${path}`;
found = true;
}
if (!found)
push(lines, `${sum} ${path}`);
}
writefile(md5f, join('\n', lines) + '\n');
}
/* ---------- network ---------- */
function sync_network(m) {
let c = cursor();
c.load('network');
let changed = false, touched = [];
let want = {};
for (let id, srv in m.servers) {
if (!srv.private_key)
continue;
let ifn = srv.ifname;
want[ifn] = true;
let addr = core.server_address(srv);
let pc = parse_cidr(srv.subnet);
let before = changed;
changed = ensure_section(c, 'network', ifn, 'interface') || changed;
changed = put(c, 'network', ifn, 'proto', 'amneziawg') || changed;
changed = put(c, 'network', ifn, 'private_key', srv.private_key) || changed;
changed = put(c, 'network', ifn, 'listen_port', srv.port) || changed;
changed = put(c, 'network', ifn, 'addresses', [ `${addr}/${pc.prefix}` ]) || changed;
changed = put(c, 'network', ifn, 'mtu', srv.mtu) || changed;
changed = put(c, 'network', ifn, 'disabled', srv.enabled ? null : '1') || changed;
changed = put(c, 'network', ifn, 'auto', srv.enabled ? null : '0') || changed;
changed = put(c, 'network', ifn, '_dawnline', id) || changed;
for (let k in core.OBF_KEYS)
changed = put(c, 'network', ifn, `awg_${k}`, srv.obf[k]) || changed;
if (changed != before)
push(touched, ifn);
}
// Remove interfaces Dawnline created for servers that no longer exist.
let stale = [];
c.foreach('network', 'interface', (s) => {
if (s._dawnline && !want[s['.name']])
push(stale, s['.name']);
});
for (let ifn in stale) {
system(`ifdown ${q(ifn)} 2>/dev/null`);
c.delete('network', ifn);
changed = true;
}
if (changed) {
c.commit('network');
ack_config([ 'network' ]);
system('ubus call network reload');
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
system(`ifup ${q(ifn)}`);
log(`network updated (${join(', ', touched) || 'removed ' + join(', ', stale)})`);
}
return changed;
}
/* ---------- firewall ---------- */
const LOOP_ZONE = 'dl_loop';
function sync_firewall(m) {
let c = cursor();
c.load('firewall');
let changed = false, want = {};
let sec = (name, stype, opts) => {
want[name] = true;
changed = ensure_section(c, 'firewall', name, stype) || changed;
for (let k, v in opts)
changed = put(c, 'firewall', name, k, v) || changed;
};
let snap = net.snapshot(true);
let portal_zone = null, want_loop = false;
for (let id, srv in m.servers) {
if (!srv.private_key)
continue;
let z = `dawnline_${id}`;
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
sec(`${z}_zone`, 'zone', {
name: srv.ifname, network: [ srv.ifname ],
input: 'ACCEPT', output: 'ACCEPT', forward: 'REJECT',
});
// Access per person is enforced by the inet dawnline table; the zone
// only needs to be allowed to reach each home-network zone and WAN.
for (let i, zone in sn.zones)
if (zone != sn.wan.zone && zone != srv.ifname)
sec(i == 0 ? `${z}_lan` : `${z}_lan_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`, 'forwarding', { src: srv.ifname, dest: zone });
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
if (srv.lan_like) {
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
want_loop = true;
}
sec(`${z}_port`, 'rule', {
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
});
}
// The link into the netns that re-enters the router from the LAN.
if (want_loop) {
sec('dawnline_loop', 'zone', {
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
});
// The Home-only resolver in the netns reaches its upstream DNS this way.
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
}
if (m.settings.portal_enabled) {
let wan = portal_zone ?? 'wan';
sec('dawnline_portal', 'rule', {
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
dest_port: m.settings.portal_port, target: 'ACCEPT',
});
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
if (core.portal_http(m)) {
sec('dawnline_portal_http', 'rule', {
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
dest_port: core.portal_http_port(m), target: 'ACCEPT',
});
if (core.portal_http_public(m) == 80)
sec('dawnline_portal_80', 'redirect', {
name: 'Dawnline-Portal-80', src: wan, proto: 'tcp',
src_dport: 80, dest_port: core.portal_http_port(m), target: 'DNAT',
});
}
// Links use 443: from outside it lands on the portal (LuCI stays closed there).
if (core.portal_public_port(m) == 443 && m.settings.portal_port != 443)
sec('dawnline_portal_443', 'redirect', {
name: 'Dawnline-Portal-443', src: wan, proto: 'tcp',
src_dport: 443, dest_port: m.settings.portal_port, target: 'DNAT',
});
}
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
c.delete('firewall', s);
changed = true;
}
if (changed) {
c.commit('firewall');
ack_config([ 'firewall' ]);
system('fw4 -q reload');
log('firewall updated');
}
return changed;
}
/* ---------- nft access table ---------- */
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' ];
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
let sets = { lan_ok: [], inet_ok: [], svc_ok: [], dns_real: [] };
for (let id, d in m.devices) {
let p = m.people[d.person];
if (!p || d.disabled || !d.address || states[p.id] != 'active')
continue;
// Plain DNS for whoever's internet does not go through the router.
// Home names: the plain resolver (their internet does not use the tunnel).
if (p.access == 'lan' && p.dns_mode == 'home')
push(sets.dns_real, d.address);
if (p.access == 'internet' || p.access == 'both')
push(sets.inet_ok, d.address);
if (p.access == 'both' || (p.access == 'lan' && !length(p.services)))
push(sets.lan_ok, d.address);
else if (p.access == 'lan')
for (let sid in p.services) {
let s = m.services[sid];
if (!s || !s.address)
continue;
for (let port in s.ports)
if (match(port, /^[0-9]+$/))
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
}
}
return sets;
};
function set_elems(arr) {
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
function nft_table(m, sets) {
let ifs = [], lan = [];
let dns_addr = loop.client_dns();
let rt = loop.resolver_target();
let snap = net.snapshot();
for (let id, srv in m.servers)
if (srv.private_key) {
push(ifs, `"${srv.ifname}"`);
push(lan, ...net.server_net(srv, snap).nets);
}
lan = net.collapse(lan);
let t = [];
push(t, 'table inet dawnline {');
push(t, ` set lan_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(lan)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
push(t, ' chain pre {');
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
push(t, ' type filter hook prerouting priority -160; policy accept;');
if (length(ifs))
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
push(t, ' }');
push(t, ' chain guard {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct state established,related accept');
push(t, ' icmp type echo-request fib daddr type local accept');
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
push(t, ' fib daddr type local ip saddr @lan_ok accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
push(t, ' ip daddr @lan_nets ip saddr @lan_ok accept');
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
push(t, ' ip saddr @inet_ok accept');
push(t, ' counter drop');
push(t, ' }');
// Devices ask the tunnel address; send each query where it belongs.
let to_resolver = rt.mode == 'ns' ? `dnat ip to ${rt.address}:53` : `redirect to :${rt.port}`;
let lan_dns = loop.lan_dns();
push(t, ' chain dns {');
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
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}`);
for (let id, srv in m.servers) {
let a = srv.private_key ? core.server_address(srv) : null;
if (!a)
continue;
// Everyone else: the LAN's DNS, through the netns (from the LAN side) when internet goes that way.
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
push(t, ` iifname "${srv.ifname}" ip daddr ${a} meta l4proto { tcp, udp } th dport 53 ${target}`);
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
function nft_load(script) {
ensure_dir(RUN_DIR);
let f = `${RUN_DIR}/nft.rules`;
writefile(f, script);
let r = sh(`nft -f ${f}`);
if (r.code != 0)
log(`nft failed: ${trim(r.out)}`);
return r.code == 0;
}
/** Full table rebuild (structure changes: servers, LAN subnets). */
export function rebuild_nft(m, sets) {
let s = 'table inet dawnline\ndelete table inet dawnline\n' + nft_table(m, sets);
return nft_load(s);
};
/** Atomically replace set contents only. */
export function update_sets(sets) {
let s = '';
for (let name in [ 'lan_ok', 'inet_ok', 'svc_ok', 'dns_real' ]) {
s += `flush set inet dawnline ${name}\n`;
if (length(sets[name]))
s += `add element inet dawnline ${name} { ${join(', ', sets[name])} }\n`;
}
return nft_load(s);
};
export function remove_nft() {
system('nft delete table inet dawnline 2>/dev/null');
};
/* ---------- AmneziaWG peers ---------- */
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
let res = {};
for (let id, srv in m.servers) {
if (!srv.private_key || !srv.enabled)
continue;
if (system(`awg show ${q(srv.ifname)} public-key >/dev/null 2>&1`) != 0) {
res[id] = 'down';
continue;
}
let lines = [ '[Interface]', `PrivateKey = ${srv.private_key}`, `ListenPort = ${srv.port}`, '' ];
for (let did, d in m.devices) {
let p = m.people[d.person];
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !d.public_key || !d.address)
continue;
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
push(lines, `AllowedIPs = ${d.address}/32`, '');
}
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)
log(`awg syncconf ${srv.ifname}: ${trim(r.out)}`);
}
return res;
};
/* ---------- hostnames ---------- */ /* ---------- hostnames ---------- */
function host_label(s) {
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
l = replace(l, /^-+|-+$/g, '');
return substr(l, 0, 40) || 'device';
}
export function sync_hosts(m) { export function sync_hosts(m) {
let lines = []; let lines = [];
if (m.settings.hostnames) if (m.settings.hostnames)
for (let id, d in m.devices) { for (let pid, p in m.people) {
let p = m.people[d.person]; // One label per device, unique within the person (the UI shows the same).
if (p && d.address) let labels = core.device_labels(m, p);
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`); for (let id in p.devices) {
let d = m.devices[id];
if (ip2int(d.address) != null)
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
}
} }
let ls = loop.status(); let ls = loop.status();
if (ls.active) if (ls.active)
@@ -439,7 +66,7 @@ export function sync_hosts(m) {
return true; return true;
}; };
/* ---------- entry points ---------- */ /* ---------- access table ---------- */
export function states_for(m, usage) { export function states_for(m, usage) {
let st = {}; let st = {};
@@ -448,21 +75,116 @@ export function states_for(m, usage) {
return st; return st;
}; };
/** Runtime sync: peers + access sets + hostnames. Cheap; safe to call often. */ /** Per-person runtime membership (dawnline.nft). */
export function sync(m, usage) { export function access_sets(m, usage, states) {
m ??= core.load(); return nft.access_sets(m, usage, states);
usage ??= core.load_usage(); };
/**
* Log an access-table failure once per distinct error (with what it means
* for the devices: none loaded while the table is missing, the previous rules
* kept when an older one survived the failed rebuild); the error, or null.
*/
function nft_result(err, present) {
let was = readfile(NFT_ERR);
if (err == null) {
if (was != null)
unlink(NFT_ERR);
return null;
}
if (was != err) {
log('Access rules', present
? "couldn't be updated — the previous rules stay, and changes to access wait until they load"
: "couldn't load — no device is loaded into the tunnels until they do", 'error', err);
ensure_dir(RUN_DIR);
writefile(NFT_ERR, err);
}
return err;
}
/**
* The table in place: rebuilt with `full`, otherwise members only, rebuilt
* when that fails (no table yet at boot, or an older shape). Null, or the
* error when the rebuild fails too.
*/
function load_table(m, sets, full) {
let err = full ? nft.rebuild(m, sets) : nft.update(sets);
if (err != null && !full)
err = nft.rebuild(m, sets);
return nft_result(err, err != null && nft.present());
}
/** Full table rebuild (structure changes: servers, LAN subnets); true when it loaded. */
export function rebuild_nft(m, sets) {
let err = nft.rebuild(m, sets);
return nft_result(err, err != null && nft.present()) == null;
};
/** Atomically replace set contents only. */
export function update_sets(sets) {
return nft.update(sets) == null;
};
export function remove_nft() {
nft.remove();
};
/** For the watchdog (dawnline.fw). */
export function firewall_drift(m) {
return fw.drift(m);
};
/* ---------- runtime sync ---------- */
/**
* What an admin should hear when a sync did not fully take: the access table
* failed, or a server did not accept its devices. Null when all went in.
*/
function sync_warning(m, table, peers) {
let out = [];
if (table != null)
push(out, nft.present()
? `Access rules couldn't be updated (${table}): the previous rules stay, so this change isn't in effect yet.`
: `Access rules couldn't load (${table}): no device is loaded into the tunnels until they do.`);
for (let id, r in peers)
if (r != 'ok' && r != 'down')
push(out, `Couldn't load devices into ${m.servers[id]?.name ?? id}: ${r}.`);
return length(out) ? join(' ', out) + ' Open Diagnostics → Health.' : null;
}
/*
* With the lock held: access sets first, then devices into the tunnels.
* Fail closed: without the table the firewall would let every loaded device
* reach everything, so while it is missing no device is loaded at all. An
* older table that survived a failed rebuild keeps limiting them with the
* sets it has, and the devices still follow people's states (a revoked one
* leaves).
*/
function locked_sync(m, usage, full) {
let states = states_for(m, usage); let states = states_for(m, usage);
let l = lock('apply'); let sets = nft.access_sets(m, usage, states);
let peers = sync_peers(m, states); let table = load_table(m, sets, full);
let sets = access_sets(m, usage, states); let peers = awg.sync_peers(m, table == null || nft.present() ? states : {});
if (!update_sets(sets))
rebuild_nft(m, sets);
sync_hosts(m); sync_hosts(m);
unlock(l);
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
write_json(`${RUN_DIR}/states.json`, states, 0o644); write_json(`${RUN_DIR}/states.json`, states, 0o644);
return { peers, states }; return { peers, states, table, warning: sync_warning(m, table, peers) };
}
/**
* Runtime sync: devices into the tunnels (AmneziaWG peers), access sets,
* hostnames. Cheap; safe to call often. The model is always read again under
* the lock (`m` is accepted for older callers and not used); `usage` is the
* caller's (the agent holds the live counters). The result carries `warning`
* (a sentence for the admin) when the sync did not fully take.
*/
export function sync(m, usage) {
return with_lock('apply', () => locked_sync(core.load(), usage ?? core.load_usage()));
};
/** Is the access table loaded (the agent's tick re-syncs when it is not). */
export function table_present() {
return nft.present();
}; };
/** /**
@@ -480,142 +202,67 @@ export function net_signature(m) {
return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() }); return sprintf('%J', { wan: snap.wan, lan: snap.lan, addrs: lan?.addrs, servers: srvs, dns: loop.lan_dns(), loop: loop.client_dns() });
}; };
const PORTAL_CGI = '/usr/share/dawnline/portal/www/cgi-bin/portal';
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
/*
* At home the portal's hostname usually points at the router itself, where
* LuCI's web server owns 443. Paths it does not know (the portal's) go to the
* portal CGI through its error page, so the same link works inside and out.
*/
function sync_uhttpd(m) {
let want = m.settings.portal_enabled && core.portal_public_port(m) == 443 && m.settings.portal_port != 443;
let c = cursor();
c.load('uhttpd');
let cur = c.get('uhttpd', 'main', 'error_page');
let changed = false;
if (want) {
if (!stat(LAN_CGI))
system(`ln -sf ${PORTAL_CGI} ${LAN_CGI}`);
if (cur == null && c.get('uhttpd', 'main')) {
c.set('uhttpd', 'main', 'error_page', LAN_CGI_URL);
changed = true;
}
}
else {
if (cur == LAN_CGI_URL) {
c.delete('uhttpd', 'main', 'error_page');
changed = true;
}
if (stat(LAN_CGI))
unlink(LAN_CGI);
}
if (changed) {
c.commit('uhttpd');
system('/etc/init.d/uhttpd reload >/dev/null 2>&1');
log(want ? 'portal answers on 443 at home too' : 'portal removed from the LuCI web server');
}
}
/** One `ipproto <p> sport <port> lookup main` rule per listening port and family. */
function sync_reply_routes(m) {
let want = [];
if (m.settings.portal_enabled) {
push(want, `tcp ${+m.settings.portal_port}`);
if (core.portal_http(m))
push(want, `tcp ${core.portal_http_port(m)}`);
}
for (let id, srv in m.servers)
if (srv.private_key && srv.enabled && +srv.port)
push(want, `udp ${+srv.port}`);
want = uniq(want);
for (let fam in [ '-4', '-6' ]) {
let have = [];
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
let mm = match(line, /ipproto (tcp|udp) sport (\d+) lookup main/);
if (mm)
push(have, `${mm[1]} ${mm[2]}`);
}
for (let h in have)
if (index(want, h) < 0)
sh(`ip ${fam} rule del priority ${PREF_REPLY} ipproto ${split(h, ' ')[0]} sport ${split(h, ' ')[1]} lookup main 2>/dev/null`);
for (let w in want)
if (index(have, w) < 0)
sh(`ip ${fam} rule add priority ${PREF_REPLY} ipproto ${split(w, ' ')[0]} sport ${split(w, ' ')[1]} lookup main`);
}
}
/** /**
* Keep the "like a home device" path and the resolver in step (agent tick). * Keep the "like a home device" path and the resolver in step (agent tick).
* Cheap when nothing changed; rebuilds the access table when the netns * Cheap when nothing changed; rebuilds the access table when the netns
* address appears, moves or goes away (the guard allows DNS to it). * address appears, moves or goes away (the guard allows DNS to it).
*/ */
export function sync_loop(m, usage, force) { export function sync_loop(m, usage, force) {
m ??= core.load(); let p = with_lock('apply', () => {
let before = `${loop.client_dns()} ${loop.resolver_target().mode}`; let mm = core.load();
let p = loop.ensure(m, force); let before = `${loop.client_dns()} ${loop.resolver_target().mode}`;
loop.sync_resolver(m); let lp = loop.ensure(mm, force);
sync_reply_routes(m); loop.sync_resolver(mm);
if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before) { fw.sync_reply_routes(mm);
usage ??= core.load_usage(); if (`${loop.client_dns()} ${loop.resolver_target().mode}` != before)
rebuild_nft(m, access_sets(m, usage, states_for(m, usage))); locked_sync(mm, usage ?? core.load_usage(), true);
sync_hosts(m); return lp;
} });
loop.remember(p);
return p; return p;
}; };
/** Every personal code is a word code; older random ones are replaced (their links stop working). */ /* ---------- entry points ---------- */
function ensure_word_codes() {
let c = cursor();
c.load('dawnline');
let changed = false;
c.foreach('dawnline', 'person', (s) => {
if (s.code != null && !match(s.code, core.WORD_CODE)) {
c.set('dawnline', s['.name'], 'code', core.new_code());
c.delete('dawnline', s['.name'], 'words');
changed = true;
}
});
if (changed) {
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
log('personal links moved to word codes');
}
}
/** Full reconcile: router configuration + runtime state. */ /** Full reconcile: router configuration + runtime state. */
export function apply(opts) { export function apply(opts) {
opts ??= {}; opts ??= {};
ensure_word_codes(); migrate.run();
let m = core.load(); let r = with_lock('apply', () => {
let usage = core.load_usage(); let m = core.load();
let l = lock('reconcile'); let usage = core.load_usage();
let net = sync_network(m); let network = netifd.sync(m);
let fw = sync_firewall(m); let firewall = fw.sync(m);
sync_uhttpd(m); let lp = loop.ensure(m, true);
let lp = loop.ensure(m, true); loop.sync_resolver(m);
loop.sync_resolver(m); fw.sync_reply_routes(m);
sync_reply_routes(m); let s = locked_sync(m, usage, true);
let states = states_for(m, usage); ensure_dir(RUN_DIR);
rebuild_nft(m, access_sets(m, usage, states)); write_file(NET_SIG, net_signature(m), 0o644);
unlock(l); return { network, firewall, lp, peers: s.peers, warning: s.warning };
let r = sync(m, usage); });
return { network: net, firewall: fw, like_home: lp.error ? { error: lp.error } : !lp.off, peers: r.peers }; loop.remember(r.lp);
return { network: r.network, firewall: r.firewall, like_home: r.lp.error ? { error: r.lp.error } : !r.lp.off, peers: r.peers, warning: r.warning };
}; };
/** Remove everything Dawnline created (used by the uninstaller). */ /** Remove everything Dawnline created (used by the uninstaller). */
export function teardown() { export function teardown() {
let m = core.load(); with_lock('apply', () => {
loop.remove(); let m = core.load();
unlink(loop.RESOLVER.conf); loop.remove();
m.servers = {}; unlink(loop.RESOLVER.conf);
m.settings.portal_enabled = false; m.servers = {};
sync_network(m); m.settings.portal_enabled = false;
sync_firewall(m); netifd.sync(m);
sync_uhttpd(m); fw.sync(m);
sync_reply_routes(m); fw.sync_reply_routes(m);
remove_nft(); nft.remove();
unlink(HOSTS_FILE); unlink(HOSTS_FILE);
system('killall -HUP dnsmasq 2>/dev/null'); unlink(NET_SIG);
system('killall -HUP dnsmasq 2>/dev/null');
});
migrate.uhttpd();
// The agent's heartbeat check.
if (system('grep -qs /usr/libexec/dawnline/heartbeat /etc/crontabs/root') == 0)
system("sed -i '\\#/usr/libexec/dawnline/heartbeat#d' /etc/crontabs/root; /etc/init.d/cron restart >/dev/null 2>&1");
}; };
@@ -0,0 +1,662 @@
// Dawnline — the AmneziaWG core: keys, disguise (obfuscation), client
// configurations (.conf, AmneziaVPN key), the netifd options of a server's
// tunnel, its peers (`awg syncconf`, no restart), live counters and what the
// watchdog and Health check about it. Plain WireGuard is AmneziaWG with the
// disguise off.
import { readfile, stat, unlink } from 'fs';
import {
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, translit, ensure_dir, write_file, read_json, write_json, lock, unlock,
slog, iface_status, DATA_DIR, RUN_DIR
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
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',
};
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' ];
/** netifd knows the amneziawg protocol (it reads the proto scripts when it starts). */
function proto_handler() {
try {
return 'amneziawg' in (json(sh_out('ubus call network get_proto_handlers 2>/dev/null') || '{}') ?? {});
}
catch (e) {
return false;
}
}
/**
* What of AmneziaWG is on the router:
* tools the awg tool and the netifd protocol script (amneziawg-tools)
* kmod the kernel module, loaded or on disk for the running kernel
* loaded the module is loaded
* handler netifd lists the amneziawg protocol
* missing packages that are not installed; ok: everything is in place
*/
export function state() {
let tools = stat(TOOL) != null && stat(PROTO) != null;
let loaded = stat('/sys/module/amneziawg') != null;
let rel = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let kmod = loaded || (rel != '' && stat(`/lib/modules/${rel}/amneziawg.ko`) != null);
let handler = tools && proto_handler();
let missing = filter(PACKAGES, (p) => p == 'kmod-amneziawg' ? !kmod : !tools);
return { tools, kmod, loaded, handler, missing, ok: !length(missing) && loaded && handler };
};
/**
* state(), after loading an installed module that isn't loaded yet: nothing loads
* it before the first tunnel comes up, so "not loaded" alone is no fault.
*/
export function load() {
let s = state();
if (!s.kmod || s.loaded)
return s;
system('modprobe amneziawg >/dev/null 2>&1');
return state();
};
/** The kernel module and the awg tool are on the router. */
export function installed() {
let s = state();
return s.tools && s.kmod;
};
/* ---------- keys ---------- */
export function genkey() {
return sh_out('awg genkey');
};
export function pubkey(priv) {
if (!valid_key(priv))
return null;
return sh_out(`printf %s ${q(priv)} | awg pubkey`);
};
/** A preshared key is 32 random bytes: no tool needed (`awg genpsk` does the same). */
export function genpsk() {
return b64enc(rand_bytes(32));
};
/**
* Keys for a new device. With `public_key` (made in the browser) the private
* key never reaches the router. Never without a preshared key.
*/
export function new_keys(public_key) {
let psk = genpsk();
if (!valid_key(psk))
die('Key generation failed (no random data).');
if (public_key) {
if (!valid_key(public_key))
die('Invalid public key.');
return { public_key, preshared_key: psk };
}
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
return { private_key: priv, public_key: pub, preshared_key: psk };
};
/** A server's own key pair (set up once, on the server). */
export function server_keys() {
let priv = genkey(), pub = pubkey(priv);
if (!pub)
die('Key generation failed (is amneziawg-tools installed?).');
return { private_key: priv, public_key: pub };
};
/* ---------- obfuscation ---------- */
// Junk packets may be tiny (the 3.1 preset sends 10-50 bytes, as AmneziaVPN
// does); the ceiling keeps them under the path MTU.
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 0, 1024 ], jmax: [ 0, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] };
function rand_h(used) {
for (let i = 0; i < 50; i++) {
let v = rand_int(5, 2147483647);
if (!used[v]) {
used[v] = true;
return `${v}`;
}
}
}
// caps() answers from here while the tool, the protocol script and the module file are the same.
const CAPS = `${RUN_DIR}/awg-caps.json`;
/**
* What the installed AmneziaWG can do: the netifd protocol script (the
* 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):
* 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
*/
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 cached = read_json(CAPS, null);
if (cached?.key == key && cached.caps)
return cached.caps;
let script = readfile(PROTO) ?? '';
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
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'));
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,
};
ensure_dir(RUN_DIR);
write_json(CAPS, { key, caps: out }, 0o644);
return out;
};
/**
* Why this AmneziaWG cannot run a server's disguise values, or null: a 3.1
* preset after a rollback to a 2.0 build would come up without the header
* protection every device expects, so such a server is kept down instead
* (dawnline.netifd).
*/
export function obf_unsupported(o) {
let c = caps();
let has = (keys) => length(filter(keys, (k) => o?.[k] != null && o[k] != '')) > 0;
let v3 = [ 'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
let v2 = [ 's3', 's4', 'i1', 'i2', 'i3', 'i4', 'i5' ];
let ranged = length(filter([ 'h1', 'h2', 'h3', 'h4' ], (k) => match(`${o?.[k] ?? ''}`, /-/))) > 0;
if (has(v3) && !c.v3)
return `its disguise needs AmneziaWG 3.1 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
if ((has(v2) || ranged) && !c.v2)
return `its disguise needs AmneziaWG 2.0 (installed: ${c.kmod ?? c.tools ?? 'none'})`;
return null;
};
/**
* Signature packets shaped like DNS, made fresh for each server: the same
* fixed bytes on every router (AmneziaVPN's own 3.1 default is one constant
* answer about icloud.com) would be one rule for a DPI to match. A query and
* an answer about a name of this server's own, with its own TTL and address.
* <r N> random bytes, <rc N> random letters, <b 0x..> fixed bytes
*/
function dns_name_hex() {
let hex = (s) => {
let out = '';
for (let i = 0; i < length(s); i++)
out += sprintf('%02x', ord(s, i));
return out;
};
let tld = [ 'com', 'net', 'org', 'io' ][rand_int(0, 3)];
let n = rand_int(5, 9);
return { labels: `<b 0x${sprintf('%02x', n)}><rc ${n}><b 0x${sprintf('%02x', length(tld))}${hex(tld)}00>`, len: n + length(tld) + 2 };
}
function dns_query() {
let name = dns_name_hex();
// id, flags (standard query, recursion desired), 1 question, name, type A, class IN
return `<r 2><b 0x01000001000000000000>${name.labels}<b 0x00010001>`;
}
function dns_answer() {
let name = dns_name_hex();
let ttl = sprintf('%08x', rand_int(300, 86400));
// id, flags (answer, authoritative, recursion), 1 question, 1 answer, name, A IN, pointer, A IN, ttl, 4 bytes
return `<r 2><b 0x85800001000100000000>${name.labels}<b 0x00010001c00c00010001${ttl}0004><r 4>`;
}
/**
* Generate obfuscation parameters for a method:
* off plain WireGuard-compatible packets
* balanced AmneziaWG 2.0: junk packets, random headers, padded cookie and
* data packets, DNS-shaped signature packets
* max AmneziaWG 3.1: protected headers, random trailers, padding,
* jittered timers and a DNS-like first packet — the values
* AmneziaVPN itself uses for 3.1 servers
* Servers made before 0.8 may still carry the old "standard" or "strong"
* values (1.0-style junk only): they keep running as they are, the picker
* offers Balanced or Maximum instead.
*/
export function obf_preset(name) {
if (name == 'max')
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'),
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 = {};
o.jc = `${rand_int(4, 8)}`;
let jmin = rand_int(64, 128);
o.jmin = `${jmin}`;
o.jmax = `${jmin + rand_int(150, 400)}`;
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
while (s1 + 56 == s2)
s2 = rand_int(15, 64);
o.s1 = `${s1}`;
o.s2 = `${s2}`;
let used = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
o[k] = rand_h(used);
// AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept
// small: core.tunnel_mtu) and DNS-shaped signature packets before each
// handshake — what 1.0 traffic lacks and gets recognised by.
o.s3 = `${rand_int(8, 48)}`;
o.s4 = `${rand_int(4, 16)}`;
o.i1 = dns_query();
o.i2 = dns_answer();
return o;
};
export function obf_errors(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]})`);
}
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, `${k} must be a number or range`);
else if (hs[v])
push(errs, 'h1-h4 must be distinct');
hs[v] = true;
}
return errs;
};
export function allowed_ips(m, srv, p) {
if (p.access == 'lan') {
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.
let a = core.server_address(srv);
if (srv.device_mesh && srv.subnet)
push(nets, srv.subnet);
else if (a)
push(nets, `${a}/32`);
// 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`);
return net.collapse(nets);
}
return [ '0.0.0.0/0', '::/0' ];
};
/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */
export function obf_neutral(o) {
for (let k in core.OBF_KEYS) {
let v = o?.[k];
if (v == null || v == '')
continue;
let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0';
if (`${v}` != want)
return false;
}
return true;
};
/*
* The .conf file name doubles as the tunnel name in WireGuard apps (15
* characters at most): the device first, so a person's devices stay apart,
* and a number when the cut would still make two of them alike.
*/
function conf_filename(m, p, dev) {
let label = (d) => trim(substr(trim(replace(lc(translit(d.name + '-' + p.id)), /[^a-z0-9]+/g, '-'), '-'), 0, 15), '-');
let order = sort(map(p.devices, (id) => m.devices[id]),
(a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
let seen = {};
for (let d in order) {
let l = label(d);
let n = seen[l] = (seen[l] ?? 0) + 1;
if (d.id == dev.id)
return (n > 1 ? trim(substr(l, 0, 15 - length(`-${n}`)), '-') + `-${n}` : l) + '.conf';
}
return label(dev) + '.conf';
}
/**
* The junk a device sends is its own: within the preset's own ranges, the
* count and sizes are shifted a little by the device (deterministic, so the
* configuration keeps its fingerprint), so two phones of one family do not
* share one profile. Server-side values (headers, padding sizes, the header
* protection key) stay the server's.
*/
function client_obf(srv, dev) {
let o = { ...srv.obf };
if (obf_neutral(o) || !(+o.jc > 0))
return o;
let key = `${srv.id}/${dev.id}/${srv.obf.h1 ?? ''}`;
let seed = 2166136261;
for (let i = 0; i < length(key); i++)
seed = ((seed ^ ord(key, i)) * 16777619) & 0x7fffffff;
let pick = (n) => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed % n;
};
let jc = +o.jc, jmin = +o.jmin, jmax = +o.jmax;
o.jc = `${max(1, min(10, jc + pick(3) - 1))}`;
if (jmax > jmin + 32) {
let d = pick(17);
o.jmin = `${jmin + d}`;
o.jmax = `${jmax - pick(17)}`;
if (+o.jmax <= +o.jmin)
o.jmax = `${+o.jmin + 32}`;
}
return o;
}
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 dns = core.client_dns(m, srv, p);
let mtu = core.device_mtu(srv, dev);
let lines = [ '[Interface]' ];
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
push(lines, `Address = ${dev.address}/32`);
if (length(dns))
push(lines, `DNS = ${join(', ', dns)}`);
push(lines, `MTU = ${mtu}`);
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
// out, so any WireGuard app accepts the file.
let obf = client_obf(srv, dev);
if (!obf_neutral(obf))
for (let k in core.OBF_KEYS)
if (obf[k] != null && obf[k] != '')
push(lines, `${OBF_CONF[k]} = ${obf[k]}`);
push(lines, '', '[Peer]');
push(lines, `PublicKey = ${srv.public_key}`);
if (dev.preshared_key)
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}`);
return {
name: dev.name,
person: p.name,
server: srv.name,
filename: conf_filename(m, p, dev),
conf: join('\n', lines) + '\n',
has_private_key: dev.private_key != '',
amnezia: {
host,
port: srv.port,
mtu: `${mtu}`,
dns,
allowed_ips: allowed,
client_ip: dev.address,
client_priv_key: dev.private_key,
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
obfuscation: obf,
},
};
};
/* ---------- the server's tunnel ---------- */
/** netifd options of the server's interface (proto amneziawg). */
export function netifd_options(srv) {
let addr = core.server_address(srv);
let prefix = split(srv.subnet, '/')[1];
let o = {
proto: 'amneziawg',
private_key: srv.private_key,
listen_port: srv.port,
addresses: [ `${addr}/${prefix}` ],
mtu: core.tunnel_mtu(srv),
};
for (let k in core.OBF_KEYS)
o[`awg_${k}`] = srv.obf[k];
return o;
};
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
/** Push the peer list of every server to the kernel without restarting it. */
export function sync_peers(m, states) {
ensure_dir(RUN_DIR);
let res = {};
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';
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;
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
if (d.preshared_key)
push(lines, `PresharedKey = ${d.preshared_key}`);
push(lines, `AllowedIPs = ${d.address}/32`, '');
}
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)
slog('awg', 'error', "couldn't load devices into the tunnel", trim(r.out), srv.name);
}
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.
*/
export function dump(wanted) {
let r = sh('awg show all dump');
let out = { ok: r.code == 0, ifaces: {}, peers: {} };
for (let line in split(r.out, '\n')) {
let f = split(line, '\t');
if (length(f) < 5 || !valid_key(f[1]))
continue;
if (valid_key(f[2]) && match(f[3] ?? '', /^[0-9]+$/))
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] };
else if (length(f) >= 9 && (f[2] == '(none)' || valid_key(f[2]))) {
let ep = f[3] == '(none)' ? '' : f[3];
out.peers[f[1]] = {
ifname: f[0],
endpoint: ep,
handshake: +f[5],
rx: +f[6],
tx: +f[7],
};
}
}
if (!out.ok && type(wanted) == 'array')
out.ok = length(filter(wanted, (n) => !out.ifaces[n])) == 0;
return out;
};
/** Is the server's tunnel up and listening (for status and Overview). */
export function server_state(srv) {
let st = iface_status(srv.ifname);
return { up: !!st?.up, uptime: st?.uptime ?? 0 };
};
/* ---------- watchdog ---------- */
/** Why a tunnel is down, from netifd and the last related syslog lines. */
export function iface_errors(ifname) {
let s = iface_status(ifname);
let errs = map(s?.errors ?? [], (e) => e.code + (length(e.data ?? []) ? ` (${join(' ', e.data)})` : ''));
// Only what explains a failure, not the ordinary "is now up/down" lines.
let lines = sh_out(`logread -l 400 2>/dev/null | grep -E ${q(`${ifname}|amneziawg`)} | grep -iE 'error|fail|invalid|unrecogni|cannot|unable|not found|refused|denied' | tail -n 6`);
return join('\n', filter([ length(errs) ? `netifd: ${join(', ', errs)}` : null, lines ], (x) => x));
};
/**
* What the watchdog looks at for AmneziaWG (see dawnline.watchdog):
* AmneziaWG itself, then every running server's tunnel. `ctx.udp_listening`,
* `ctx.reapply` and `ctx.owner` (dawnline.netifd) come from the watchdog
* (ops, apply and netifd import this module).
*/
export function probes(m, ctx) {
let out = [];
let srvs = filter(values(m.servers), (x) => x.enabled && x.private_key);
if (!length(srvs))
return out;
// AmneziaWG itself first: without it no tunnel can run (they come back on the next pass).
// Missing packages and an unknown protocol are reported once; only the module can be loaded here.
let st = state();
let base = { id: 'awg', src: 'awg', name: 'AmneziaWG', who: 'AmneziaWG', back: 'is ready again' };
if (!st.tools || !st.kmod) {
push(out, { ...base, ok: false, repair: null,
problem: `${st.tools ? "kernel module isn't" : "isn't"} installed: no tunnel can run — install it in Dawnline → Components`,
detail: () => `Missing: ${join(', ', st.missing)}.` });
return out;
}
push(out, { ...base, ok: st.loaded && st.handler,
problem: !st.loaded ? "kernel module isn't loaded" : "isn't known to the network service — restart the network or reboot",
detail: !st.loaded
? () => sh_out("modprobe amneziawg 2>&1; dmesg 2>/dev/null | grep -i amneziawg | grep -iE 'error|fail|invalid|unknown|disagrees|taint' | tail -n 4")
: () => 'netifd reads its protocol handlers when it starts; it was running before AmneziaWG was installed.',
repair: !st.loaded ? { what: 'loading it', run: () => system('modprobe amneziawg >/dev/null 2>&1') } : null,
});
// Without the protocol handler ifup cannot work: the tunnels are not probed (or restarted) one by one.
if (st.loaded && !st.handler)
return out;
for (let srv in srvs) {
// A tunnel Dawnline may not set up (dawnline.netifd) is reported, never restarted:
// an interface of the same name that isn't Dawnline's may be your LAN.
let own = core.valid_ifname(srv.ifname) ? ctx.owner?.(srv.ifname) : null;
let why = srv.blocked ?? (!core.valid_ifname(srv.ifname) ? `has an invalid interface name "${srv.ifname}"`
: own != null && own != srv.id ? `can't use the network interface ${srv.ifname}: it exists and isn't Dawnline's` : null);
if (why) {
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: false, repair: null,
problem: why, back: 'AmneziaWG is running again',
detail: () => 'Choose another interface name in the server settings.',
});
continue;
}
let s = iface_status(srv.ifname);
let up = !!s?.up;
push(out, {
id: `up_${srv.id}`, src: 'awg', name: `${srv.name} · AmneziaWG`, who: srv.name, ok: up && ctx.udp_listening(srv.port),
problem: !s ? 'AmneziaWG is missing from the router' : !up ? "AmneziaWG isn't running" : `AmneziaWG isn't accepting connections on port ${srv.port}`,
back: `AmneziaWG is running again · accepting connections on port ${srv.port}`,
detail: () => iface_errors(srv.ifname),
repair: s ? { what: 'restarting it', run: () => system(`ifup ${q(srv.ifname)}`) } : { what: 'setting it up again', run: ctx.reapply },
});
}
return out;
};
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
function fnv32(str) {
let h = 2166136261;
for (let i = 0; i < length(str); i++)
h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff;
return sprintf('%08x', h);
}
/**
* What a device holds, minus its private key: changes when it must import
* again. The junk count and sizes (Jc, Jmin, Jmax) are the device's own and
* never have to match the server, so they are left out: a change there is
* no reason to import again.
*/
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;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
export function issued() {
return read_json(ISSUED, {});
};
/** Remember that a device was just given its current configuration. */
export function mark_issued(m, id) {
let fp = config_fingerprint(m, m.devices[id]);
if (!fp)
return;
let l = lock('issued');
let all = issued();
if (all[id] != fp) {
all[id] = fp;
for (let k in keys(all))
if (!m.devices[k])
delete all[k];
ensure_dir(DATA_DIR, 0o700);
write_json(ISSUED, all, 0o600);
}
unlock(l);
};
@@ -0,0 +1,97 @@
// 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.
import { readfile } from 'fs';
import { connect } from 'ubus';
import { ensure_dir, read_json, write_json, DATA_DIR } from 'dawnline.util';
import * as pkg from 'dawnline.pkg';
export const SOURCES = {
slava: { repo: 'Slava-Shchipunov/awg-openwrt', label: 'Slava-Shchipunov' },
grey: { repo: '2Grey/awg-openwrt', label: '2Grey' },
};
/** Tried in this order when no build is chosen. */
export const ORDER = [ 'slava', 'grey' ];
export const PKGS = [ 'kmod-amneziawg', 'amneziawg-tools', 'luci-proto-amneziawg' ];
export const RU = 'luci-i18n-amneziawg-ru';
/**
* This firmware as the builds name it: { tag: 'v24.10.6', postfix:
* '_v24.10.6_aarch64_cortex-a53_mediatek_filogic', ext }, or null.
*/
export function firmware() {
let u = connect();
let b = u?.call('system', 'board') ?? {};
u?.disconnect();
let rel = b.release ?? {};
let target = split(rel.target ?? '', '/');
let arch = rel.arch ?? match(readfile('/etc/openwrt_release') ?? '', /DISTRIB_ARCH='([^']*)'/)?.[1];
if (!rel.version || length(target) != 2 || !arch)
return null;
return { tag: `v${rel.version}`, postfix: `_v${rel.version}_${arch}_${target[0]}_${target[1]}`, ext: pkg.ext(),
snapshot: match(rel.version, /SNAPSHOT/) != null };
};
/** What was installed, for whom: /etc/dawnline/awg.json (survives a sysupgrade with the data). */
export const RECORD = `${DATA_DIR}/awg.json`;
/**
* 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).
*/
export function record(source, tag, packages) {
ensure_dir(DATA_DIR, 0o700);
write_json(RECORD, {
osrelease: trim(readfile('/proc/sys/kernel/osrelease') ?? ''),
source, tag, packages, installed: time(),
}, 0o600);
};
/**
* 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.
*/
export function kernel_changed() {
let r = read_json(RECORD, null);
let now = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
if (!r?.osrelease || r.osrelease == now)
return null;
return { was: r.osrelease, now, tag: r.tag, source: r.source };
};
/** The file name of a package in a build. */
export function asset(fw, name) {
return `${name}${fw.postfix}.${fw.ext}`;
};
/** The same firmware, another release of its series (v24.10.6 → v24.10.8). */
export function for_tag(fw, tag) {
return { ...fw, tag, postfix: replace(fw.postfix, fw.tag, tag) };
};
/**
* AmneziaWG generation of a package version: 3.x packages carry 3.1; 1.0.x
* ones are 2.0 (S3/S4, I1-I5, header ranges) from July 2025 on, and the
* first generation before that. A kernel module's version carries the kernel
* release in front (6.12.94.3.1.20260906): the AmneziaWG part is at the end.
*/
export function gen(version) {
if (version == null)
return null;
let v = match(`${version}`, /([0-9]+\.[0-9]+\.[0-9]{8})(-r?[0-9]+)?$/)?.[1] ?? `${version}`;
if (match(v, /^3\./))
return '3.1';
if (match(v, /^1\.0\.2024/) || match(v, /^1\.0\.20250[1-6]/))
return '1.0';
return '2.0';
};
/** The installed AmneziaWG packages: { name: version | null }. */
export function installed() {
let r = {};
for (let p in PKGS)
r[p] = pkg.version(p);
return r;
};
@@ -0,0 +1,322 @@
// 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.
import { readfile, stat, unlink, lsdir, rename } from 'fs';
import { cursor } from 'uci';
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 live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as health from 'dawnline.health';
const BACKUP_DIR = `${DATA_DIR}/backups`;
/**
* How many backups of each kind stay (the newest): the nightly ones must not
* push out what the admin made by hand or what a removal left behind.
*/
const KEEP = { manual: 10, auto: 7, 'pre-delete': 5, 'pre-remove': 3, 'pre-update': 3, 'pre-restore': 3, 'pre-import': 3 };
const NAME = /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/;
/** What a backup holds (paths inside the archive, relative to /). */
const FILES = [ 'etc/config/dawnline', 'etc/dawnline/usage.json', 'etc/dawnline/events.json' ];
/**
* Kinds that hold the config alone (about 20 KB): the history can be a
* megabyte or more, and these are made often and never to bring history
* back. Manual, pre-restore and pre-import backups protect the data that is
* about to be replaced, so they take everything.
*/
const CONFIG_ONLY = [ 'auto', 'pre-delete', 'pre-remove', 'pre-update' ];
/** The unpacked size a backup may have (the upload itself is limited to 4 MB). */
const MAX_UNPACKED = 16 * 1024 * 1024;
/* ---------- checking a configuration before it is used ---------- */
/**
* 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.
*/
export function config_errors(c) {
let m = core.load(c);
let errs = core.model_errors(m);
let nc = cursor();
nc.load('network');
let foreign = health.foreign_subnets();
let internal = values(net.INTERNAL);
let ifnames = {}, ports = {}, subnets = [];
for (let id, srv in m.servers) {
let who = `Server ${srv.name}`;
for (let e in core.server_errors(m, srv, [ ...foreign, ...subnets ]))
push(errs, `${who}: ${e}`);
if (ifnames[srv.ifname])
push(errs, `${who}: interface ${srv.ifname} is also used by ${ifnames[srv.ifname]}.`);
ifnames[srv.ifname] = srv.name;
let t = nc.get('network', srv.ifname);
if (index(internal, srv.ifname) >= 0 || (t != null && (t != 'interface' || nc.get('network', srv.ifname, '_dawnline') == null)))
push(errs, `${who}: ${srv.ifname} is one of the router's own network interfaces.`);
if (ports[srv.port])
push(errs, `${who}: UDP ${srv.port} is also used by ${ports[srv.port]}.`);
ports[srv.port] = srv.name;
if (srv.subnet)
push(subnets, srv.subnet);
}
return errs;
};
/** Check the config file in `dir` (as /etc/config/dawnline would be); dies listing the problems. */
function check_config_dir(dir) {
ensure_dir(`${dir}/.delta`, 0o700);
// Its own delta directory: changes staged in LuCI must not leak into the check.
let c = cursor(dir, `${dir}/.delta`);
if (!c.load('dawnline'))
die('The configuration in this file cannot be read.');
let errs = config_errors(c);
if (length(errs))
die(`This configuration can't be used: ${join(' ', errs)}`);
}
/** A private scratch directory under RUN_DIR (the caller removes it). */
function scratch(kind) {
ensure_dir(RUN_DIR);
let dir = `${RUN_DIR}/${kind}.${rand_hex(4)}`;
system(`rm -rf ${q(dir)}; mkdir -m 700 -p ${q(dir)}`);
return dir;
}
/* ---------- backups ---------- */
export function backup_list() {
let out = [];
for (let f in lsdir(BACKUP_DIR) ?? []) {
let mm = match(f, NAME);
if (!mm)
continue;
let st = stat(`${BACKUP_DIR}/${f}`);
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
}
return sort(out, (a, b) => b.created - a.created);
};
/**
* Make a backup now; returns its name. Written whole or not at all (a half
* archive from a full flash never shows up as a backup). Of each kind the
* oldest beyond KEEP are removed, except `keep` (the backup being restored,
* which must survive the backup made just before restoring it).
*/
export function backup_create(reason, keep) {
let kind = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? reason : 'manual';
let config_only = index(CONFIG_ONLY, kind) >= 0;
// Flush live counters first so the backup has current usage.
if (!config_only) {
let u = read_json(`${RUN_DIR}/usage.json`, null);
if (u)
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
live.persist_events();
}
ensure_dir(BACKUP_DIR, 0o700);
let t = localtime();
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, kind == 'manual' ? '' : `-${kind}`);
let want = config_only ? [ FILES[0] ] : FILES;
let files = join(' ', map(filter(want, (f) => file_exists(`/${f}`)), q));
// Not a NAME until it is complete.
let tmp = `${BACKUP_DIR}/.${name}.tmp`;
let r = sh(`tar -czf ${q(tmp)} -C / ${files}`);
if (r.code != 0 || !rename(tmp, `${BACKUP_DIR}/${name}`)) {
unlink(tmp);
die(`Backup failed: ${trim(r.out) || 'the archive could not be written (is the flash full?)'}`);
}
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let by_kind = {};
for (let b in backup_list())
if (b.name != keep && b.name != name)
push(by_kind[b.reason] ??= [], b);
for (let k, list in by_kind)
for (let i = KEEP[k] ?? 3; i < length(list); i++)
unlink(`${BACKUP_DIR}/${list[i].name}`);
return name;
};
function backup_path(name) {
if (!match(name ?? '', NAME))
die('Invalid backup name.');
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
return p;
}
/**
* Validate an archive: only Dawnline's own files, all of them regular files
* (no links, devices or directories), within a sane unpacked size.
*/
function check_archive(path) {
let r = sh(`tar -tvzf ${q(path)}`);
if (r.code != 0)
die('Not a valid backup archive.');
let has_config = false, total = 0;
for (let line in split(trim(r.out), '\n')) {
let f = split(trim(line), /[ \t]+/);
let name = replace(f[length(f) >= 6 ? 5 : length(f) - 1] ?? '', /^\.?\//, '');
// "-rw------- root/root 1234 2026-01-01 12:00:00 etc/config/dawnline"; links show "a -> b".
if (substr(line, 0, 1) != '-' || index(line, ' -> ') >= 0 || index(line, ' link to ') >= 0)
die(`Unexpected entry in backup: ${name}`);
if (index(FILES, name) < 0)
die(`Unexpected file in backup: ${name}`);
total += +(f[2] ?? 0) || 0;
if (name == 'etc/config/dawnline')
has_config = true;
}
if (!has_config)
die('Backup does not contain /etc/config/dawnline.');
if (total > MAX_UNPACKED)
die('Backup is too large.');
}
/**
* Put the files unpacked in `dir` in place, under the config lock. The
* config goes first: when it cannot be written nothing else is touched, and
* a data file that fails afterwards is reported, not ignored.
*/
function install_files(dir) {
ensure_dir(DATA_DIR, 0o700);
let l = lock('config');
try {
for (let f in FILES) {
let data = readfile(`${dir}/${f}`);
if (data != null && !write_file(`/${f}`, data, 0o600))
die(`Couldn't write /${f}. Is the flash full?`);
}
}
catch (e) {
unlock(l);
die(e.message);
}
unlock(l);
system('chmod 600 /etc/config/dawnline');
}
export function backup_restore(name, path) {
path ??= backup_path(name);
check_archive(path);
let dir = scratch('restore');
try {
let r = sh(`tar -xzf ${q(path)} -C ${q(dir)} ${join(' ', map(FILES, q))} 2>/dev/null; test -f ${q(dir + '/etc/config/dawnline')}`);
if (r.code != 0)
die('Not a valid backup archive.');
check_config_dir(`${dir}/etc/config`);
backup_create('pre-restore', name);
install_files(dir);
}
catch (e) {
system(`rm -rf ${q(dir)}`);
die(e.message);
}
system(`rm -rf ${q(dir)}`);
// Live counters must follow the restored file: the agent reloads them from
// flash on its next tick (its watcher may write the old ones again before).
unlink(`${RUN_DIR}/usage.json`);
unlink(`${RUN_DIR}/events.json`);
write_file(live.USAGE_RELOAD, `${time()}`, 0o600);
return apply.apply();
};
export function backup_delete(name) {
unlink(backup_path(name));
return true;
};
export function backup_read(name) {
return b64enc(readfile(backup_path(name)));
};
export function backup_upload(data_b64) {
let data = b64dec(data_b64 ?? '');
if (!data || length(data) > 4 * 1024 * 1024)
die('Upload is empty or too large.');
ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data);
let res;
try {
res = backup_restore(null, tmp);
}
catch (e) {
unlink(tmp);
die(e.message);
}
unlink(tmp);
return res;
};
/* ---------- export / import (JSON) ---------- */
export function export_json() {
let c = cursor();
c.load('dawnline');
let sections = [];
c.foreach('dawnline', null, (s) => {
let o = { '.type': s['.type'], '.name': s['.name'] };
for (let k, v in s)
if (substr(k, 0, 1) != '.')
o[k] = v;
push(sections, o);
});
return { format: 'dawnline', version: VERSION, exported: time(), sections };
};
/** An export as /etc/config/dawnline text; dies on anything that is not one. */
function export_to_uci(data) {
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
die('Not a Dawnline export.');
let types = { settings: true, server: true, person: true, device: true, service: true, circle: true };
let esc = (x) => replace(`${x}`, "'", "'\\''");
let lines = [];
for (let s in data.sections) {
if (type(s) != 'object' || !types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
die(`Invalid section ${s?.['.name']}.`);
push(lines, `config ${s['.type']} '${s['.name']}'`);
for (let k, v in s) {
if (substr(k, 0, 1) == '.')
continue;
if (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array'))
die(`Invalid option ${k}.`);
if (type(v) == 'array')
for (let x in v) {
if (type(x) != 'string')
die(`Invalid option ${k}.`);
push(lines, `\tlist ${k} '${esc(x)}'`);
}
else
push(lines, `\toption ${k} '${esc(v)}'`);
}
push(lines, '');
}
return join('\n', lines);
}
export function import_json(data) {
let text = export_to_uci(data);
let dir = scratch('import');
try {
write_file(`${dir}/dawnline`, text, 0o600);
check_config_dir(dir);
}
catch (e) {
system(`rm -rf ${q(dir)}`);
die(e.message);
}
system(`rm -rf ${q(dir)}`);
backup_create('pre-import');
let l = lock('config');
let ok = write_file('/etc/config/dawnline', text, 0o600);
unlock(l);
if (!ok)
die("Couldn't write /etc/config/dawnline. Is the flash full?");
return apply.apply();
};
@@ -1,34 +1,37 @@
// Dawnline — data model: reads /etc/config/dawnline, validates and mutates it, // Dawnline — data model: reads /etc/config/dawnline, validates and mutates it
// allocates addresses, generates keys and renders client configurations. // and allocates addresses. Nothing here knows how the tunnel works: dawnline.awg
// renders AmneziaWG configurations and runs the tunnels.
import { cursor } from 'uci'; import { cursor } from 'uci';
import { readfile } from 'fs';
import { import {
q, sh, sh_out, valid_name, valid_key, valid_host, valid_date, slugify, valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, NAME_RULE, parse_cidr, cidr_overlaps, int2ip, ip2int,
parse_cidr, cidr_str, cidr_overlaps, int2ip, ip2int, in_cidr, rand_token, rand_hex, rand_int, rand_bytes, rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
date_end, month_key, read_json, write_json, ensure_dir, lock, unlock, DATA_DIR, RUN_DIR, uniq
} from 'dawnline.util'; } from 'dawnline.util';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop'; import * as schema from 'dawnline.schema';
import { policy as updates_policy } from 'dawnline.updates';
export const CONFIG = 'dawnline'; export const CONFIG = 'dawnline';
/**
* Servers whose network interface Dawnline may not set up (the name belongs
* to an interface it did not create, or is invalid): { id: why }. Written by
* dawnline.netifd; such a server has no tunnel anywhere (firewall, access
* table, "like a home device"), so nothing of Dawnline lands on that interface.
*/
export const BLOCKED = `${RUN_DIR}/netifd-blocked.json`;
export const ACCESS = [ 'lan', 'internet', 'both' ]; export const ACCESS = [ 'lan', 'internet', 'both' ];
export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ]; export const KINDS = [ 'computer', 'phone', 'tablet', 'router', 'other' ];
/** Kinds that mostly live on mobile networks: their configurations carry a smaller MTU. */
export const MOBILE_KINDS = [ 'phone', 'tablet' ];
/** Devices of different people reaching each other: never, everyone with home access, or within a circle. */
export const MESH = [ 'off', 'all', 'circles' ];
/** Circle colours (index into the admin palette). */
export const CIRCLE_COLORS = 8;
/** AmneziaWG obfuscation options stored on a server (netifd uses `awg_<key>`; dawnline.awg renders them). */
export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5', export const OBF_KEYS = [ 'jc', 'jmin', 'jmax', 's1', 's2', 's3', 's4', 'h1', 'h2', 'h3', 'h4', 'i1', 'i2', 'i3', 'i4', 'i5',
// AmneziaWG 3.x // AmneziaWG 3.x
'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time', 'header_protection_key', 'content_padding_addition', 'rekey_after_time', 'rekey_timeout', 'reject_after_time',
'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ]; 'keepalive_timeout', 'max_handshake_attempts', 'random_trailers', 'disable_cookies' ];
/** Names in .conf files (and AmneziaVPN keys); netifd uses `awg_<key>`. */
export const OBF_CONF = {
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 toint(v, dflt) { function toint(v, dflt) {
if (v == null || v == '') if (v == null || v == '')
return dflt; return dflt;
@@ -66,29 +69,33 @@ export function open_cursor() {
export function load(c) { export function load(c) {
c ??= open_cursor(); c ??= open_cursor();
let s = c.get_all(CONFIG, 'settings') ?? {}; let s = c.get_all(CONFIG, 'settings') ?? {};
// Types, defaults and ranges of the settings live in dawnline.schema (one
// place): what is read here is what settings_update would have accepted.
let g = (k) => schema.get(s, k);
let m = { let m = {
settings: { settings: {
portal_enabled: bool(s.portal_enabled, false), portal_enabled: g('portal_enabled'),
portal_port: toint(s.portal_port, 8443), portal_port: g('portal_port'),
// Also answer on 443 from the internet (mobile networks often drop TLS on other ports). portal_host: g('portal_host'),
portal_443: bool(s.portal_443, true),
portal_host: s.portal_host ?? '',
// More addresses for the same links (the main one is portal_host). // More addresses for the same links (the main one is portal_host).
portal_alt: filter(type(s.portal_alt) == 'array' ? s.portal_alt : s.portal_alt ? [ s.portal_alt ] : [], (x) => x != ''), portal_alt: g('portal_alt'),
portal_cert: s.portal_cert ?? '', portal_cert: g('portal_cert'),
portal_key: s.portal_key ?? '', portal_key: g('portal_key'),
portal_title: s.portal_title ?? 'Dawnline', portal_title: g('portal_title'),
// Where unknown portal links go instead of a bare 404 (empty = 404). // Where unknown portal links go instead of a bare 404 (empty = 404).
portal_redirect: s.portal_redirect ?? '', portal_redirect: g('portal_redirect'),
paused_all: bool(s.paused_all, false), default_device_limit: g('default_device_limit'),
default_device_limit: toint(s.default_device_limit, 3), geo_enabled: g('geo_enabled'),
geo_enabled: bool(s.geo_enabled, true), geo_provider: g('geo_provider'),
geo_provider: s.geo_provider == 'ipapi.co' ? 'ipapi.co' : 'ipwho.is', hostnames: g('hostnames'),
hostnames: bool(s.hostnames, true), domain: g('domain'),
domain: s.domain ?? 'lan', log_connections: g('log_connections'),
log_connections: bool(s.log_connections, true), // 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. // Second DNS for "home names" devices, used by the device when the tunnel is down.
home_dns_fallback: s.home_dns_fallback == 'none' ? '' : (s.home_dns_fallback ?? '1.1.1.1'), home_dns_fallback: g('home_dns_fallback'),
// Settings → Updates (automatic checks and updates of the components).
updates: updates_policy(s),
// Raw retention values; dawnline.live policy() interprets them. // Raw retention values; dawnline.live policy() interprets them.
retention: { retention: {
log_keep_days: s.log_keep_days, log_max: s.log_max, log_category: s.log_category, log_keep_days: s.log_keep_days, log_max: s.log_max, log_category: s.log_category,
@@ -100,8 +107,10 @@ export function load(c) {
people: {}, people: {},
devices: {}, devices: {},
services: {}, services: {},
circles: {},
}; };
let blocked = read_json(BLOCKED, {});
c.foreach(CONFIG, 'server', (r) => { c.foreach(CONFIG, 'server', (r) => {
let id = r['.name']; let id = r['.name'];
let srv = { let srv = {
@@ -111,7 +120,8 @@ export function load(c) {
port: toint(r.port, 51820), port: toint(r.port, 51820),
subnet: r.subnet ?? '', subnet: r.subnet ?? '',
endpoint: r.endpoint ?? '', endpoint: r.endpoint ?? '',
mtu: toint(r.mtu, 1380), // 0 = automatic (tunnel_mtu, device_mtu).
mtu: toint(r.mtu, 0),
dns: list(r.dns), dns: list(r.dns),
keepalive: toint(r.keepalive, 25), keepalive: toint(r.keepalive, 25),
private_key: r.private_key ?? '', private_key: r.private_key ?? '',
@@ -126,12 +136,20 @@ export function load(c) {
detected_wan: r.detected_wan ?? '', detected_wan: r.detected_wan ?? '',
detected_lan: r.detected_lan ?? '', detected_lan: r.detected_lan ?? '',
lan_like: bool(r.lan_like, true), lan_like: bool(r.lan_like, true),
// Devices of people with home access reach each other: off, all, or within circles.
// (Older configs: device_mesh 0/1.)
mesh: index(MESH, r.mesh) >= 0 ? r.mesh : (bool(r.device_mesh, true) ? 'all' : 'off'),
enabled: bool(r.enabled, true), enabled: bool(r.enabled, true),
// AmneziaWG disguise values, read by dawnline.awg.
obf: {}, obf: {},
}; };
for (let k in OBF_KEYS) for (let k in OBF_KEYS)
if (r[k] != null && r[k] != '') if (r[k] != null && r[k] != '')
srv.obf[k] = `${r[k]}`; srv.obf[k] = `${r[k]}`;
// A person's own devices reach each other whenever the mesh is not off.
srv.device_mesh = srv.mesh != 'off';
if (blocked[id])
srv.blocked = blocked[id];
m.servers[id] = srv; m.servers[id] = srv;
}); });
@@ -144,6 +162,8 @@ export function load(c) {
access: index(ACCESS, r.access) >= 0 ? r.access : 'internet', access: index(ACCESS, r.access) >= 0 ? r.access : 'internet',
device_limit: toint(r.device_limit, m.settings.default_device_limit), device_limit: toint(r.device_limit, m.settings.default_device_limit),
code: r.code ?? '', code: r.code ?? '',
// When the personal link was last made (0 for links from before this was kept).
code_set: toint(r.code_set, 0),
expires: r.expires ?? '', expires: r.expires ?? '',
quota_gb: num(r.quota_gb, 0), quota_gb: num(r.quota_gb, 0),
quota_period: r.quota_period == 'total' ? 'total' : 'month', quota_period: r.quota_period == 'total' ? 'total' : 'month',
@@ -156,6 +176,9 @@ export function load(c) {
bonus_gb: num(r.bonus_gb, 0), bonus_gb: num(r.bonus_gb, 0),
bonus_month: r.bonus_month ?? '', bonus_month: r.bonus_month ?? '',
services: list(r.service), services: list(r.service),
// Home networks (interfaces) this person reaches; empty = all of the server's.
home_nets: list(r.home_net),
circle: r.circle ?? '',
note: r.note ?? '', note: r.note ?? '',
created: toint(r.created, 0), created: toint(r.created, 0),
devices: [], devices: [],
@@ -182,6 +205,11 @@ export function load(c) {
push(m.people[d.person].devices, id); push(m.people[d.person].devices, id);
}); });
c.foreach(CONFIG, 'circle', (r) => {
let id = r['.name'];
m.circles[id] = { id, server: r.server ?? '', name: r.name ?? id, color: toint(r.color, 0) % CIRCLE_COLORS };
});
c.foreach(CONFIG, 'service', (r) => { c.foreach(CONFIG, 'service', (r) => {
let id = r['.name']; let id = r['.name'];
m.services[id] = { m.services[id] = {
@@ -214,23 +242,23 @@ function within_hours(h, ts) {
return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]); return h[0] < h[1] ? (cur >= h[0] && cur < h[1]) : (cur >= h[0] || cur < h[1]);
} }
/** Bytes used in the person's quota period. */ /** Bytes used in the person's quota period (the month of `ts`, default now). */
export function person_usage(p, usage) { export function person_usage(p, usage, ts) {
let u = usage?.people?.[p.id]; let u = usage?.people?.[p.id];
if (!u) if (!u)
return 0; return 0;
if (p.quota_period == 'total') if (p.quota_period == 'total')
return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0); return (u.total?.[0] ?? 0) + (u.total?.[1] ?? 0);
let mm = u.months?.[month_key()]; let mm = u.months?.[month_key(ts)];
return mm ? mm[0] + mm[1] : 0; return mm ? mm[0] + mm[1] : 0;
}; };
/** Quota in bytes for the current period (base + this month's bonus), 0 = unlimited. */ /** Quota in bytes for the period of `ts` (default now): base + that month's bonus, 0 = unlimited. */
export function person_quota(p) { export function person_quota(p, ts) {
if (!(p.quota_gb > 0)) if (!(p.quota_gb > 0))
return 0; return 0;
let gb = p.quota_gb; let gb = p.quota_gb;
if (p.bonus_gb > 0 && p.bonus_month == month_key()) if (p.bonus_gb > 0 && p.bonus_month == month_key(ts))
gb += p.bonus_gb; gb += p.bonus_gb;
return gb * 1073741824; return gb * 1073741824;
}; };
@@ -242,24 +270,16 @@ export function person_expired(p, ts) {
return end != null && (ts ?? time()) > end; return end != null && (ts ?? time()) > end;
}; };
/** /** The person's state whatever their server is doing (paused, expired, …, or 'active'). */
* Effective state of a person: 'active', or why they are off: export function own_state(m, p, usage, ts) {
* 'paused' (admin), 'paused_all', 'expired', 'quota', 'hours', 'no_server'.
*/
export function person_state(m, p, usage, ts) {
ts ??= time(); ts ??= time();
let srv = m.servers[p.server];
if (!srv || !srv.enabled)
return 'no_server';
if (p.paused) if (p.paused)
return 'paused'; return 'paused';
if (m.settings.paused_all)
return 'paused_all';
// "notify" keeps access after the end date (shown in Overview and People). // "notify" keeps access after the end date (shown in Overview and People).
if (person_expired(p, ts) && p.expire_action != 'notify') if (person_expired(p, ts) && p.expire_action != 'notify')
return 'expired'; return 'expired';
let quota = person_quota(p); let quota = person_quota(p, ts);
if (quota > 0 && person_usage(p, usage) >= quota) if (quota > 0 && person_usage(p, usage, ts) >= quota)
return 'quota'; return 'quota';
let h = parse_hours(p.hours); let h = parse_hours(p.hours);
if (h && !within_hours(h, ts)) if (h && !within_hours(h, ts))
@@ -267,41 +287,61 @@ export function person_state(m, p, usage, ts) {
return 'active'; return 'active';
}; };
/**
* Effective state of a person: 'active', or why they are off:
* 'paused' (admin), 'expired', 'quota', 'hours', 'no_server',
* 'server_off' (their server is turned off: about the server, not the person).
*/
export function person_state(m, p, usage, ts) {
let srv = m.servers[p.server];
if (!srv)
return 'no_server';
if (!srv.enabled)
return 'server_off';
return own_state(m, p, usage, ts);
};
export function load_usage() { export function load_usage() {
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} }); return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, { devices: {}, people: {} });
}; };
/* ---------- keys ---------- */ /* ---------- tunnels and addresses ---------- */
export function genkey() { /** A server's interface name: also a netifd section and an nft string, so nothing else. */
return sh_out('awg genkey'); export function valid_ifname(s) {
return type(s) == 'string' && match(s, /^[a-z][a-z0-9_]{0,11}$/) != null;
}; };
export function pubkey(priv) { /** Router address inside the AmneziaWG subnet (first host). */
if (!valid_key(priv))
return null;
return sh_out(`printf %s ${q(priv)} | awg pubkey`);
};
export function genpsk() {
return sh_out('awg genpsk');
};
/* ---------- networks ---------- */
/** IPv4 subnets of the router's LAN zone (from netifd), as CIDR strings. */
/** Router address inside the server subnet (first host). */
export function server_address(srv) { export function server_address(srv) {
let c = parse_cidr(srv.subnet); let c = parse_cidr(srv.subnet);
return c ? int2ip(c.first) : null; return c ? int2ip(c.first) : null;
}; };
/**
* The link a server's devices come in on: { ifname, subnet, address (the
* router's) }, as a list so the access table, firewall zone, "like a home
* device" and DNS treat every tunnel interface alike. None for a server
* without keys, subnet or a valid interface name (an imported config), or
* whose interface name is taken (BLOCKED).
*/
export function tunnels(srv) {
let c = srv?.private_key && !srv.blocked && valid_ifname(srv.ifname) ? parse_cidr(srv.subnet) : null;
return c ? [ { ifname: srv.ifname, subnet: srv.subnet, address: int2ip(c.first) } ] : [];
};
/** The server's tunnel link, or null. */
export function tunnel(srv) {
return tunnels(srv)[0];
};
/** The first free address in the server's subnet (the router has the first). */
export function alloc_address(m, srv) { export function alloc_address(m, srv) {
let c = parse_cidr(srv.subnet); let t = parse_cidr(srv.subnet);
if (!c) if (!t)
return null; return null;
let used = {}; let used = {};
used[c.first] = true; used[t.first] = true;
for (let id, d in m.devices) { for (let id, d in m.devices) {
let p = m.people[d.person]; let p = m.people[d.person];
if (p && p.server == srv.id) { if (p && p.server == srv.id) {
@@ -310,124 +350,45 @@ export function alloc_address(m, srv) {
used[n] = true; used[n] = true;
} }
} }
for (let n = c.first + 1; n <= c.last; n++) for (let n = t.first + 1; n <= t.last; n++)
if (!used[n]) if (!used[n])
return int2ip(n); return int2ip(n);
return null; return null;
}; };
/* ---------- obfuscation ---------- */ /* ---------- what clients get ---------- */
const OBF_SPEC = { jc: [ 0, 10 ], jmin: [ 64, 1024 ], jmax: [ 64, 1024 ], s1: [ 0, 64 ], s2: [ 0, 64 ], s3: [ 0, 64 ], s4: [ 0, 32 ] }; /*
* Automatic MTU. A path is assumed to carry 1460 bytes (1500 less PPPoE,
function rand_h(used) { * 464XLAT or DS-Lite), the tunnel's own headers take 80 over IPv6, and
for (let i = 0; i < 50; i++) { * AmneziaWG's S4 adds its bytes to every data packet (its padding and random
let v = rand_int(5, 2147483647); * trailers stay within the largest packet already seen, so they cost
if (!used[v]) { * nothing). Phones and tablets get 1280, the IPv6 minimum: mobile paths vary.
used[v] = true;
return `${v}`;
}
}
}
/**
* What the installed AmneziaWG can do, from the netifd protocol script (the
* options it passes on) and the `awg` tool (the keys it accepts):
* v2 — S3/S4, I1-I5, header ranges (AWG 1.5/2.0)
* v3 — header protection, trailers, padding, timing (AWG 3.1)
*/ */
export function awg_caps() { const AUTO_MTU = 1380;
let script = readfile('/lib/netifd/proto/amneziawg.sh') ?? ''; const MOBILE_MTU = 1280;
let tool = sh_out("grep -a -o -m1 'HeaderProtectionKey' /usr/bin/awg 2>/dev/null") ?? '';
let v2 = index(script, 'awg_s3') >= 0 && index(script, 'awg_i1') >= 0; /** The server's tunnel MTU: the one set, or automatic for its disguise. */
let v3 = v2 && index(script, 'awg_header_protection_key') >= 0 && tool != ''; export function tunnel_mtu(srv) {
return { v2, v3 }; return srv.mtu || max(MOBILE_MTU, AUTO_MTU - toint(srv.obf?.s4, 0));
}; };
/** First junk packet shaped like a DNS answer (AmneziaVPN's own default for 3.1). */ /** The MTU a device's configuration carries: the tunnel's, at most 1280 for phones and tablets. */
const DNS_MIMIC = '<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>'; export function device_mtu(srv, dev) {
let mtu = tunnel_mtu(srv);
/** return index(MOBILE_KINDS, dev.kind) >= 0 ? min(mtu, MOBILE_MTU) : mtu;
* Generate obfuscation parameters for a method:
* off plain WireGuard-compatible packets
* standard junk packets and random headers (any AmneziaWG client)
* strong more and larger junk (any AmneziaWG client)
* max AmneziaWG 3.1: protected headers, random trailers, padding,
* jittered timers and a DNS-like first packet — the values
* AmneziaVPN itself uses for 3.1 servers
*/
export function obf_preset(name) {
if (name == 'max')
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_MIMIC,
header_protection_key: genkey(),
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 strong = name == 'strong';
let o = {};
o.jc = `${strong ? rand_int(6, 10) : rand_int(3, 6)}`;
let jmin = rand_int(64, strong ? 128 : 96);
o.jmin = `${jmin}`;
o.jmax = `${jmin + rand_int(strong ? 200 : 32, strong ? 600 : 160)}`;
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
while (s1 + 56 == s2)
s2 = rand_int(15, 64);
o.s1 = `${s1}`;
o.s2 = `${s2}`;
let used = {};
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
o[k] = rand_h(used);
return o;
}; };
export function obf_errors(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]) {
if (!(v == '0' && (k == 'jmin' || k == 'jmax')))
push(errs, `${k}=${v} (${r[0]}-${r[1]})`);
}
}
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, `${k} must be a number or range`);
else if (hs[v])
push(errs, 'h1-h4 must be distinct');
hs[v] = true;
}
return errs;
};
/* ---------- client configuration ---------- */
export function endpoint_host(m, srv) { export function endpoint_host(m, srv) {
return srv.endpoint || m.settings.portal_host || ''; return srv.endpoint || m.settings.portal_host || '';
}; };
/** /**
* DNS for a server's clients: the router's tunnel address, which never * DNS for a server's clients: the router's address in the tunnel subnet,
* changes after setup. The router forwards each query where it belongs (the * which never changes after setup. The router forwards each query where it
* LAN's DNS, from the LAN side; or the plain resolver), so configurations on * belongs (the LAN's DNS, from the LAN side; or the plain resolver), so
* devices keep working when the LAN, its DNS or the netns address change. * configurations on devices keep working when the LAN, its DNS or the netns
* address change.
*/ */
export function dns_list(m, srv) { export function dns_list(m, srv) {
if (!srv) if (!srv)
@@ -439,10 +400,10 @@ export function dns_list(m, srv) {
}; };
/** /**
* DNS written into a device's configuration. Home-only people keep their * DNS a device uses. Home-only people keep their device's DNS unless they
* device's DNS unless they chose home names; then the first server is * chose home names; then the first server is Dawnline's plain resolver
* Dawnline's plain resolver (reached through the tunnel) and the second the * (reached through the tunnel) and the second the fallback the device uses
* fallback the device uses when the tunnel is down. * when the tunnel is down.
*/ */
export function client_dns(m, srv, p) { export function client_dns(m, srv, p) {
if (p?.access != 'lan') if (p?.access != 'lan')
@@ -456,126 +417,28 @@ export function client_dns(m, srv, p) {
return out; return out;
}; };
export function allowed_ips(m, srv, p) { /**
if (p.access == 'lan') { * The home networks a person reaches: all of the server's, or only the
let nets = net.server_net(srv).nets; * interfaces ticked on their page (networks added later are not included).
let a = server_address(srv); */
if (a) export function person_home(srv, p, snap) {
push(nets, `${a}/32`); let sn = net.server_net(srv, snap);
// The resolver address must be reachable through the tunnel too (not the fallback). let pick = p?.home_nets ?? [];
let dns = client_dns(m, srv, p)[0]; if (!length(pick))
if (dns) return { all: true, nets: sn.nets, devs: map(sn.home, (h) => h.dev) };
push(nets, `${dns}/32`); let nets = [], devs = [];
return net.collapse(nets); for (let h in sn.home)
} if (index(pick, h.dev) >= 0) {
return [ '0.0.0.0/0', '::/0' ]; push(nets, ...h.nets);
push(devs, h.dev);
}
return { all: false, nets: net.collapse(nets), devs };
}; };
/** Everything a client needs; `conf` is the .conf text. */ /** The circle a person is in on their server (circles mode only), or null. */
/** True when the obfuscation settings change nothing on the wire (plain WireGuard). */ export function person_circle(m, p) {
export function obf_neutral(o) { let c = m.circles[p?.circle];
for (let k in OBF_KEYS) { return c && c.server == p.server ? c : null;
let v = o?.[k];
if (v == null || v == '')
continue;
let want = { h1: '1', h2: '2', h3: '3', h4: '4' }[k] ?? '0';
if (`${v}` != want)
return false;
}
return true;
};
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 = endpoint_host(m, srv);
let ep = match(host, /:/) && !match(host, /^\[/) ? `[${host}]` : host;
let allowed = allowed_ips(m, srv, p);
let dns = client_dns(m, srv, p);
let lines = [ '[Interface]' ];
push(lines, `PrivateKey = ${dev.private_key || '<private key stays on your device>'}`);
push(lines, `Address = ${dev.address}/32`);
if (length(dns))
push(lines, `DNS = ${join(', ', dns)}`);
push(lines, `MTU = ${srv.mtu}`);
// "Off" is plain WireGuard: neutral values (no junk, H1-H4 = 1-4) are left
// out, so any WireGuard app accepts the file.
if (!obf_neutral(srv.obf))
for (let k in OBF_KEYS)
if (srv.obf[k] != null && srv.obf[k] != '')
push(lines, `${OBF_CONF[k]} = ${srv.obf[k]}`);
push(lines, '', '[Peer]');
push(lines, `PublicKey = ${srv.public_key}`);
if (dev.preshared_key)
push(lines, `PresharedKey = ${dev.preshared_key}`);
push(lines, `AllowedIPs = ${join(', ', allowed)}`);
push(lines, `Endpoint = ${ep}:${srv.port}`);
if (srv.keepalive > 0)
push(lines, `PersistentKeepalive = ${srv.keepalive}`);
return {
name: dev.name,
person: p.name,
server: srv.name,
filename: `${substr(replace(lc(p.id + '-' + dev.name), /[^a-z0-9]+/g, '-'), 0, 15)}.conf`,
conf: join('\n', lines) + '\n',
has_private_key: dev.private_key != '',
amnezia: {
host,
port: srv.port,
mtu: `${srv.mtu}`,
dns,
allowed_ips: allowed,
client_ip: dev.address,
client_priv_key: dev.private_key,
client_pub_key: dev.public_key,
psk_key: dev.preshared_key,
server_pub_key: srv.public_key,
persistent_keep_alive: `${srv.keepalive}`,
obfuscation: srv.obf,
},
};
};
/* ---------- issued configurations ---------- */
const ISSUED = `${DATA_DIR}/issued.json`;
function fnv32(str) {
let h = 2166136261;
for (let i = 0; i < length(str); i++)
h = ((h ^ ord(str, i)) * 16777619) & 0xffffffff;
return sprintf('%08x', h);
}
/** What a device holds, minus its private key: changes when it must import again. */
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/)))) : null;
};
/** Device id → fingerprint of the configuration last shown or downloaded. */
export function issued() {
return read_json(ISSUED, {});
};
/** Remember that a device was just given its current configuration. */
export function mark_issued(m, id) {
let fp = config_fingerprint(m, m.devices[id]);
if (!fp)
return;
let l = lock('issued');
let all = issued();
if (all[id] != fp) {
all[id] = fp;
for (let k in keys(all))
if (!m.devices[k])
delete all[k];
ensure_dir(DATA_DIR, 0o700);
write_json(ISSUED, all, 0o600);
}
unlock(l);
}; };
/* ---------- mutations (caller commits) ---------- */ /* ---------- mutations (caller commits) ---------- */
@@ -619,13 +482,15 @@ export function new_code() {
export function create_person(c, m, a) { export function create_person(c, m, a) {
if (!valid_name(a.name)) if (!valid_name(a.name))
fail('Enter a name (up to 48 characters).'); fail(NAME_RULE);
// The id is a UCI section name: letters, digits and underscores only (a dash // The id is a UCI section name: letters, digits and underscores only (a dash
// makes uci drop the section). Repeated names get _2, _3, … // makes uci drop the section). Repeated names get _2, _3, …
let base = replace(a.slug ?? slugify(a.name), /-/g, '_'); let base = replace(a.slug ?? slugify(a.name), /-/g, '_');
if (!match(base, /^[a-z0-9_]{1,32}$/)) if (!match(base, /^[a-z0-9_]{1,32}$/))
fail('The id may use lowercase letters, digits and underscores.'); fail('The id may use lowercase letters, digits and underscores.');
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || id == 'settings'; // Any kind of section (store.id_taken, which imports this module).
let taken = (id) => m.people[id] || m.servers[id] || m.devices[id] || m.services[id] || m.circles[id] ||
index([ 'settings', 'main', 'global', 'defaults' ], id) >= 0;
let slug = base; let slug = base;
for (let n = 2; taken(slug); n++) { for (let n = 2; taken(slug); n++) {
if (n > 99) if (n > 99)
@@ -653,6 +518,7 @@ export function create_person(c, m, a) {
c.set(CONFIG, slug, 'access', access); c.set(CONFIG, slug, 'access', access);
c.set(CONFIG, slug, 'device_limit', `${limit}`); c.set(CONFIG, slug, 'device_limit', `${limit}`);
c.set(CONFIG, slug, 'code', new_code()); c.set(CONFIG, slug, 'code', new_code());
c.set(CONFIG, slug, 'code_set', `${time()}`);
c.set(CONFIG, slug, 'created', `${time()}`); c.set(CONFIG, slug, 'created', `${time()}`);
if (a.expires) if (a.expires)
c.set(CONFIG, slug, 'expires', a.expires); c.set(CONFIG, slug, 'expires', a.expires);
@@ -674,7 +540,7 @@ export function update_person(c, m, id, a) {
let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`); let set = (k, v) => (v == null || v == '') ? c.delete(CONFIG, id, k) : c.set(CONFIG, id, k, `${v}`);
if (a.name != null) { if (a.name != null) {
if (!valid_name(a.name)) if (!valid_name(a.name))
fail('Enter a name (up to 48 characters).'); fail(NAME_RULE);
set('name', trim(a.name)); set('name', trim(a.name));
} }
if (a.access != null) { if (a.access != null) {
@@ -686,8 +552,9 @@ export function update_person(c, m, id, a) {
let n = toint(a.device_limit, 0); let n = toint(a.device_limit, 0);
if (n < 1 || n > 32) if (n < 1 || n > 32)
fail('Device limit must be between 1 and 32.'); fail('Device limit must be between 1 and 32.');
if (n < length(p.devices)) let have = length(p.devices);
fail(`${p.name} already has ${length(p.devices)} devices. Remove one first to lower the limit to ${n}.`); if (n < have)
fail(`${p.name} already has ${have} devices. Remove one first to lower the limit to ${n}.`);
set('device_limit', n); set('device_limit', n);
} }
if (a.expires != null) { if (a.expires != null) {
@@ -732,7 +599,7 @@ export function update_person(c, m, id, a) {
set('hours', a.hours); set('hours', a.hours);
} }
if (a.note != null) if (a.note != null)
set('note', substr(trim(a.note), 0, 500)); set('note', ucut(trim(a.note), 500));
if (type(a.services) == 'array') { if (type(a.services) == 'array') {
for (let sid in a.services) for (let sid in a.services)
if (!m.services[sid]) if (!m.services[sid])
@@ -742,14 +609,45 @@ export function update_person(c, m, id, a) {
else else
c.delete(CONFIG, id, 'service'); c.delete(CONFIG, id, 'service');
} }
if (a.circle != null) {
let ci = m.circles[a.circle];
if (a.circle != '' && (!ci || ci.server != p.server))
fail('Unknown circle.');
set('circle', a.circle);
}
// Another server: every device gets an address in its tunnel (so each
// needs its configuration again); circles and home networks are the old
// server's and go.
if (a.server != null && a.server != '' && a.server != p.server) {
if (!m.servers[a.server])
fail('Unknown server.');
set('server', a.server);
p.server = a.server;
for (let did in p.devices) {
let addr = alloc_address(m, m.servers[a.server]);
if (!addr)
fail(`No free address left on ${m.servers[a.server].name}.`);
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.delete(CONFIG, id, 'circle');
c.delete(CONFIG, id, 'home_net');
}
if (type(a.home_nets) == 'array') {
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
if (length(nets))
c.set(CONFIG, id, 'home_net', nets);
else
c.delete(CONFIG, id, 'home_net');
}
if (a.paused != null) if (a.paused != null)
set('paused', a.paused ? '1' : ''); set('paused', a.paused ? '1' : '');
}; };
/** /**
* Add a device for a person. `opts.by` is 'admin' or 'portal'; the portal * Add a device for a person. `opts.keys` = { private_key?, public_key,
* enforces the device limit. `opts.public_key` keeps the private key on the * preshared_key } from dawnline.awg (or a public key the browser generated).
* client (browser-generated keys). * `opts.by` is 'admin' or 'portal'; the portal is held to the device limit.
*/ */
export function create_device(c, m, person_id, name, kind, opts) { export function create_device(c, m, person_id, name, kind, opts) {
opts ??= {}; opts ??= {};
@@ -772,39 +670,29 @@ export function create_device(c, m, person_id, name, kind, opts) {
let addr = alloc_address(m, srv); let addr = alloc_address(m, srv);
if (!addr) if (!addr)
fail('No free addresses left in the server subnet.'); fail('No free addresses left in the server subnet.');
let k = opts.keys ?? {};
let priv = '', pub; if (!valid_key(k.public_key))
if (opts.public_key) {
if (!valid_key(opts.public_key))
fail('Invalid public key.');
pub = opts.public_key;
}
else {
priv = genkey();
pub = pubkey(priv);
}
if (!pub)
fail('Key generation failed (is amneziawg-tools installed?).'); fail('Key generation failed (is amneziawg-tools installed?).');
for (let id, d in m.devices) for (let o, d in m.devices)
if (d.public_key == pub) if (d.public_key == k.public_key)
fail('This key is already in use.'); fail('This key is already in use.');
let id = `d_${rand_hex(4)}`; let id = `d_${rand_hex(4)}`;
let dev = { id, person: person_id, name, kind, address: addr, public_key: k.public_key, private_key: k.private_key ?? '',
preshared_key: k.preshared_key ?? '', created: time(), created_by: opts.by ?? 'admin', disabled: false };
c.set(CONFIG, id, 'device'); c.set(CONFIG, id, 'device');
c.set(CONFIG, id, 'person', person_id); c.set(CONFIG, id, 'person', person_id);
c.set(CONFIG, id, 'name', name); c.set(CONFIG, id, 'name', name);
c.set(CONFIG, id, 'kind', kind); c.set(CONFIG, id, 'kind', kind);
c.set(CONFIG, id, 'address', addr); c.set(CONFIG, id, 'address', addr);
c.set(CONFIG, id, 'public_key', pub); for (let f in [ 'public_key', 'private_key', 'preshared_key' ])
if (priv) if (dev[f])
c.set(CONFIG, id, 'private_key', priv); c.set(CONFIG, id, f, dev[f]);
c.set(CONFIG, id, 'preshared_key', genpsk()); c.set(CONFIG, id, 'created', `${dev.created}`);
c.set(CONFIG, id, 'created', `${time()}`); c.set(CONFIG, id, 'created_by', dev.created_by);
c.set(CONFIG, id, 'created_by', opts.by ?? 'admin');
// Keep the in-memory model consistent for callers that continue. // Keep the in-memory model consistent for callers that continue.
m.devices[id] = { id, person: person_id, name, kind, address: addr, public_key: pub, private_key: priv, m.devices[id] = dev;
preshared_key: c.get(CONFIG, id, 'preshared_key'), created: time(), created_by: opts.by ?? 'admin', disabled: false };
push(p.devices, id); push(p.devices, id);
return id; return id;
}; };
@@ -834,16 +722,17 @@ export function delete_device(c, m, id) {
delete m.devices[id]; delete m.devices[id];
}; };
export function rotate_device(c, m, id) { /** New keys from dawnline.awg (the caller makes them: the model does not run tools). */
export function rotate_device(c, m, id, keys) {
let d = m.devices[id]; let d = m.devices[id];
if (!d) if (!d)
fail('Unknown device.'); fail('Unknown device.');
let priv = genkey(), pub = pubkey(priv); if (!valid_key(keys?.public_key) || !keys?.private_key)
if (!pub)
fail('Key generation failed.'); fail('Key generation failed.');
c.set(CONFIG, id, 'private_key', priv); c.set(CONFIG, id, 'private_key', keys.private_key);
c.set(CONFIG, id, 'public_key', pub); c.set(CONFIG, id, 'public_key', keys.public_key);
c.set(CONFIG, id, 'preshared_key', genpsk()); if (keys.preshared_key)
c.set(CONFIG, id, 'preshared_key', keys.preshared_key);
}; };
export function delete_person(c, m, id) { export function delete_person(c, m, id) {
@@ -855,10 +744,20 @@ export function delete_person(c, m, id) {
c.delete(CONFIG, id); c.delete(CONFIG, id);
}; };
const PRIVATE_NETS = map([ '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** The parsed subnet lies inside one of the private ranges. */
export function private_cidr(c) {
for (let p in PRIVATE_NETS)
if (c.net >= p.net && c.net + c.size <= p.net + p.size)
return true;
return false;
};
/** Validate a server definition (as loaded) against the rest of the router. */ /** Validate a server definition (as loaded) against the rest of the router. */
export function server_errors(m, srv, others_subnets) { export function server_errors(m, srv, others_subnets) {
let errs = []; let errs = [];
if (!match(srv.ifname, /^[a-z][a-z0-9_]{0,11}$/)) if (!valid_ifname(srv.ifname))
push(errs, 'Interface name: 1-12 lowercase letters, digits or _.'); push(errs, 'Interface name: 1-12 lowercase letters, digits or _.');
if (srv.port < 1 || srv.port > 65535) if (srv.port < 1 || srv.port > 65535)
push(errs, 'Port must be 1-65535.'); push(errs, 'Port must be 1-65535.');
@@ -873,29 +772,138 @@ export function server_errors(m, srv, others_subnets) {
} }
if (srv.endpoint != '' && !valid_host(srv.endpoint)) if (srv.endpoint != '' && !valid_host(srv.endpoint))
push(errs, 'Endpoint must be a hostname or IP address.'); push(errs, 'Endpoint must be a hostname or IP address.');
push(errs, ...obf_errors(srv.obf));
return errs; return errs;
}; };
/** Someone else already forwards this TCP port from outside (a port forward we must not take over). */ /**
export function wan_port_taken(port) { * What is wrong inside a model as a whole, beyond each server: devices with
let c = cursor(); * an address outside their server's subnet, the server's own address, a
c.load('firewall'); * prefix on it or one shared with another device (the access sets are keyed
let taken = false; * by address, and one bad peer line makes `awg syncconf` refuse the whole
c.foreach('firewall', 'redirect', (r) => { * server), malformed keys, people and devices pointing at servers, people,
if (match(r['.name'], /^dawnline_/) || r.enabled == '0' || (r.target ?? 'DNAT') != 'DNAT') * circles or services that do not exist, and two people with one link. [] when
return; * it is consistent. Import, restore and Health check it; the runtime sync
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) { * skips what it would reject (dawnline.awg, dawnline.nft).
let m = match(p, /^(\d+)(?:[-:](\d+))?$/); */
if (m && +m[1] <= port && port <= +(m[2] ?? m[1])) export function model_errors(m) {
taken = true; let errs = [];
let codes = {}, addrs = {};
for (let id, p in m.people) {
let who = `Person ${p.name}`;
if (p.server != '' && !m.servers[p.server])
push(errs, `${who}: server ${p.server} does not exist.`);
if (p.circle != '' && !m.circles[p.circle])
push(errs, `${who}: circle ${p.circle} does not exist.`);
for (let sid in p.services)
if (!m.services[sid])
push(errs, `${who}: home service ${sid} does not exist.`);
if (p.code != '') {
if (codes[p.code])
push(errs, `${who}: has the same personal link as ${codes[p.code]}.`);
codes[p.code] = p.name;
} }
}); }
return taken; for (let id, d in m.devices) {
let p = m.people[d.person];
let who = `Device ${d.name}${p ? ` of ${p.name}` : ''}`;
if (!p) {
push(errs, `${who}: person ${d.person} does not exist.`);
continue;
}
if (!valid_key(d.public_key))
push(errs, `${who}: the public key is not a key.`);
if (d.private_key != '' && !valid_key(d.private_key))
push(errs, `${who}: the private key is not a key.`);
if (d.preshared_key != '' && !valid_key(d.preshared_key))
push(errs, `${who}: the preshared key is not a key.`);
let n = ip2int(d.address);
if (n == null) {
push(errs, `${who}: address ${d.address || '(none)'} is not a plain IPv4 address.`);
continue;
}
let srv = m.servers[p.server];
let t = srv ? parse_cidr(srv.subnet) : null;
if (t && (n < t.first || n > t.last))
push(errs, `${who}: address ${d.address} is outside ${srv.name}'s tunnel ${srv.subnet}.`);
else if (t && n == t.first)
push(errs, `${who}: address ${d.address} is the router's own address on ${srv.name}.`);
let key = `${p.server} ${d.address}`;
if (addrs[key])
push(errs, `${who}: address ${d.address} is also used by ${addrs[key]}.`);
addrs[key] = who;
}
for (let id, ci in m.circles)
if (!m.servers[ci.server])
push(errs, `Circle ${ci.name}: server ${ci.server} does not exist.`);
return errs;
}; };
export function wan443_taken() { /**
return wan_port_taken(443); * Give every device on a server an address in `subnet` (the server's new
* tunnel network), lowest first: used by server_update when the network
* changes. Each device then needs its configuration again (the address is
* in it). Fails when the subnet cannot hold them.
*/
export function renumber_server(c, m, srv, subnet) {
srv.subnet = subnet;
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices)
m.devices[did].address = '';
for (let pid, p in m.people)
if (p.server == srv.id)
for (let did in p.devices) {
let addr = alloc_address(m, srv);
if (!addr)
fail(`${subnet} has no room for every device on ${srv.name}.`);
m.devices[did].address = addr;
c.set(CONFIG, did, 'address', addr);
}
c.set(CONFIG, srv.id, 'subnet', subnet);
};
/**
* The DNS labels of a person's devices, { device id: label }, unique within
* the person: two devices whose names give one label ("iPhone" and
* "iPhone!", or two Cyrillic names) get -2, -3 by age. Hostnames in
* /tmp/hosts (dawnline.apply) and the ones the UI shows (dawnline.view) both
* come from here, so what is shown resolves.
*/
export function device_labels(m, p) {
let out = {}, used = {};
let devs = sort(map(p.devices, (id) => m.devices[id]), (a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
for (let d in devs) {
let base = host_label(d.name), l = base;
for (let n = 2; used[l]; n++)
l = `${substr(base, 0, 37)}-${n}`;
used[l] = true;
out[d.id] = l;
}
return out;
};
/**
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
* A forwarded port never reaches the router itself, so nothing here can listen on it.
*/
export function wan_forwards(zone, proto) {
let c = cursor();
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)
return;
// fw4's default is "tcp udp".
let protos = split(type(r.proto) == 'array' ? join(' ', r.proto) : r.proto ?? 'tcp udp', /[ ,]+/);
if (index(protos, proto) < 0 && index(protos, 'all') < 0 && index(protos, 'any') < 0)
return;
for (let p in split(`${r.src_dport ?? ''}`, /[ ,]+/)) {
let m = match(p, /^(\d+)([-:](\d+))?$/);
if (m)
push(out, { from: +m[1], to: +(m[3] || m[1]), name: r.name ?? r['.name'] });
}
});
return out;
}; };
/** Every address the links use, the main one first. */ /** Every address the links use, the main one first. */
@@ -917,17 +925,14 @@ export function portal_http_port(m) {
return m.settings.portal_port + 1; return m.settings.portal_port + 1;
}; };
/** The port in plain-HTTP links: 80 when standard ports are on and free. */ /** The port in plain-HTTP links (the portal never takes 80 or 443 for itself). */
export function portal_http_public(m) { export function portal_http_public(m) {
return m.settings.portal_443 && !wan_port_taken(80) ? 80 : portal_http_port(m); return portal_http_port(m);
}; };
/** The port in personal links: 443 when the portal also answers there. */ /** The port in personal links: the portal's own. */
export function portal_public_port(m) { export function portal_public_port(m) {
let s = m.settings; return m.settings.portal_port;
if (s.portal_port == 443 || !s.portal_443 || wan443_taken())
return s.portal_port;
return 443;
}; };
/** The link on one address: https for names, plain http for IP addresses. */ /** The link on one address: https for names, plain http for IP addresses. */
@@ -940,7 +945,9 @@ export function portal_link(m, p, host) {
return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`; return `http://${host}${hp == 80 ? '' : `:${hp}`}/${p.code}`;
} }
let pp = portal_public_port(m); let pp = portal_public_port(m);
return `https://${host}${pp == 443 ? '' : `:${pp}`}/${p.code}`; // An IPv6 address needs its brackets in a URL.
let h = index(host, ':') >= 0 && !match(host, /^\[/) ? `[${host}]` : host;
return `https://${h}${pp == 443 ? '' : `:${pp}`}/${p.code}`;
}; };
/** The main link (QR, invite card, Copy link). */ /** The main link (QR, invite card, Copy link). */
@@ -0,0 +1,119 @@
// Dawnline — adding, changing, rotating and removing a person's devices: one
// code path for the admin UI (rpcd) and the portal, with the config lock,
// the runtime sync, the activity log and the "configuration issued" mark.
//
// opts = { by: 'admin' | 'portal', person?: the only person whose devices may
// be touched (the portal), defer?: load new keys a moment later (the portal
// page came through the device being rotated) }. The portal is held to the
// device limit (dawnline.core) and cannot touch a device the admin turned off.
import { sh_bg } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as apply from 'dawnline.apply';
import * as live from 'dawnline.live';
import * as store from 'dawnline.store';
/** AmneziaWG is on the router, so device keys can be made and loaded. */
export function ready() {
return awg.installed();
};
/** Dies with the admin's wording when AmneziaWG is missing. */
export function need_awg() {
if (!awg.installed()) {
let miss = awg.state().missing ?? [];
die(`AmneziaWG is not installed${length(miss) ? ` (${join(', ', miss)})` : ''}: install it in Dawnline → Components.`);
}
};
/** The device `id` as `opts` may touch it (inside a transaction's model). */
function own(m, id, opts) {
let d = m.devices[id];
if (!d || (opts.person != null && d.person != opts.person))
die(opts.person != null ? 'Device not found.' : 'Unknown device.');
if (opts.by == 'portal' && d.disabled)
die('The admin has turned this device off.');
return d;
}
/** New device with fresh keys (or the browser's public key): { id, config }. */
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 s = apply.sync();
let m = core.load();
live.add_event({ type: 'device_added', person, device: id, detail: m.devices[id].name, by });
awg.mark_issued(m, id);
return { id, config: awg.client_config(m, m.devices[id]), warning: s.warning };
};
/**
* Rename and/or turn a device off or on (`ch` = { name?, disabled? }); only
* the admin turns devices off. Returns the runtime sync.
*/
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 d0 = store.transact((c, m) => {
let d = own(m, id, opts);
let was = { ...d };
if (ch.name != null && ch.name != d.name)
core.rename_device(c, m, id, ch.name);
if (ch.disabled != null) {
if (ch.disabled)
c.set(core.CONFIG, id, 'disabled', '1');
else
c.delete(core.CONFIG, id, 'disabled');
}
return was;
});
let r = 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 });
return r;
};
/** New keys for a device: returns its new configuration. */
export function rotate(id, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
store.transact((c, m) => {
own(m, id, opts);
core.rotate_device(c, m, id, awg.new_keys());
});
// 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;
if (opts.defer)
sh_bg('sleep 3; /usr/bin/dawnline sync');
else
s = apply.sync();
let m = core.load();
let d = m.devices[id];
live.add_event({ type: 'device_keys', person: d.person, device: id, detail: d.name, by });
awg.mark_issued(m, id);
let cfg = awg.client_config(m, d);
if (s?.warning)
cfg.warning = s.warning;
return cfg;
};
/** Remove a device. Returns the runtime sync. */
export function remove(id, opts) {
opts ??= {};
let by = opts.by ?? 'admin';
let d = store.transact((c, m) => {
let d = own(m, id, opts);
core.delete_device(c, m, id);
return d;
});
let r = apply.sync();
live.add_event({ type: 'device_removed', person: d.person, device: id, detail: d.name, dname: d.name, dkind: d.kind, by });
return r;
};
@@ -0,0 +1,283 @@
// Dawnline — fw4 and routing around it: each tunnel's zone, its forwardings
// to home and WAN, the WAN rules for the tunnels and the portal (named
// sections dawnline_*), what the watchdog checks about them, and the nft
// table that keeps Dawnline's own answers out of proxies. Only sections
// 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 { cursor } from 'uci';
import * as core from 'dawnline.core';
import * as net from 'dawnline.net';
import * as nft from 'dawnline.nft';
import * as loop from 'dawnline.loop';
const LOOP_ZONE = 'dl_loop';
/*
* Our own answers leave by the main table: the portal's (TCP) and each
* tunnel's (UDP). Proxies on the router (tproxy with an fwmark rule to a
* `local default` table) mark the router's own traffic to internet addresses
* in an output route chain, which diverts replies to outside clients into lo.
* A policy rule on the source port can't exempt them: the reroute after the
* mark is set looks up without ports. So a later output route chain of our
* own clears exactly those proxy marks on packets from our listening ports,
* and the kernel routes them again by main. Forwarded traffic is not touched.
*/
const REPLY_TABLE = 'dawnline_reply';
const REPLY_SIG = `${RUN_DIR}/reply.nft`;
/** Older versions kept answers out of proxies with `ip rule` at this priority; it never matched. */
const PREF_REPLY = 90;
/** With `dry`, only says whether the firewall config differs from what Dawnline wants. */
export function sync(m, dry) {
let c = cursor();
c.load('firewall');
let changed = false, want = {};
let sec = (name, stype, opts) => {
want[name] = true;
changed = uci_section(c, 'firewall', name, stype) || changed;
for (let k, v in opts)
changed = uci_put(c, 'firewall', name, k, v) || changed;
};
let snap = net.snapshot(true);
let portal_zone = null, want_loop = false;
// Where tunnel DNS is sent (dawnline.nft): into the netns for home names
// while any server runs "like a home device", and to the LAN's DNS for
// everyone else. A server that does not forward to those zones on its own
// gets a rule for port 53 alone.
let any_loop = length(filter(values(m.servers), (s) => s.lan_like && length(core.tunnels(s)))) > 0;
let lan_dns = loop.lan_dns();
let lan_dns_zone = null;
if (lan_dns)
for (let dev, d in snap.devices)
if (d.zone && in_nets(lan_dns, d.nets ?? []))
lan_dns_zone ??= d.zone;
for (let id, srv in m.servers) {
if (!length(core.tunnels(srv)))
continue;
let z = `dawnline_${id}`;
let sn = net.server_net(srv, snap);
portal_zone ??= sn.wan.zone;
if (!srv.lan_like && any_loop)
sec(`${z}_loopdns`, 'rule', {
name: `Dawnline-${srv.ifname}-names`, src: srv.ifname, dest: LOOP_ZONE,
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
});
if (lan_dns_zone && lan_dns_zone != srv.ifname && index(sn.zones, lan_dns_zone) < 0)
sec(`${z}_landns`, 'rule', {
name: `Dawnline-${srv.ifname}-dns`, src: srv.ifname, dest: lan_dns_zone, dest_ip: lan_dns,
proto: 'tcp udp', dest_port: 53, target: 'ACCEPT',
});
sec(`${z}_zone`, 'zone', {
// Forward within the zone (device to device) is decided by the inet dawnline table.
name: srv.ifname, network: [ srv.ifname ],
input: 'ACCEPT', output: 'ACCEPT', forward: 'ACCEPT',
});
// Access per person is enforced by the inet dawnline table; the zone
// only needs to be allowed to reach each home-network zone and WAN.
// The home network may open connections to the devices too (a router
// or a NAS on the tunnel); their answers pass the table as established.
for (let i, zone in sn.zones)
if (zone != sn.wan.zone && zone != srv.ifname) {
let sfx = i == 0 ? '' : `_${replace(zone, /[^A-Za-z0-9_]/g, '_')}`;
sec(`${z}_lan${sfx}`, 'forwarding', { src: srv.ifname, dest: zone });
sec(`${z}_from_lan${sfx}`, 'forwarding', { src: zone, dest: srv.ifname });
}
sec(`${z}_wan`, 'forwarding', { src: srv.ifname, dest: sn.wan.zone });
if (srv.lan_like) {
sec(`${z}_loop`, 'forwarding', { src: srv.ifname, dest: LOOP_ZONE });
want_loop = true;
}
sec(`${z}_port`, 'rule', {
name: `Dawnline-${srv.ifname}`, src: sn.wan.zone, proto: 'udp',
dest_port: srv.port, target: 'ACCEPT', enabled: srv.enabled ? null : '0',
});
}
// The link into the netns that re-enters the router from the LAN.
if (want_loop) {
sec('dawnline_loop', 'zone', {
name: LOOP_ZONE, device: [ net.INTERNAL.transit ],
input: 'REJECT', output: 'ACCEPT', forward: 'REJECT',
});
// The Home-only resolver in the netns reaches its upstream DNS this way.
sec('dawnline_loop_wan', 'forwarding', { src: LOOP_ZONE, dest: portal_zone ?? 'wan' });
}
// Never open SSH, DNS or the LuCI web server for the portal, whatever the settings say.
let portal_port_ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
if (m.settings.portal_enabled && portal_port_ok(m.settings.portal_port)) {
let wan = portal_zone ?? 'wan';
sec('dawnline_portal', 'rule', {
name: 'Dawnline-Portal', src: wan, proto: 'tcp',
dest_port: m.settings.portal_port, target: 'ACCEPT',
});
// IP addresses in links: plain HTTP next to the HTTPS port, and 80 forwarded to it.
if (core.portal_http(m) && portal_port_ok(core.portal_http_port(m))) {
sec('dawnline_portal_http', 'rule', {
name: 'Dawnline-Portal-HTTP', src: wan, proto: 'tcp',
dest_port: core.portal_http_port(m), target: 'ACCEPT',
});
}
// The portal keeps its own port: 80 and 443 stay with the LuCI web server.
}
let stale = [];
c.foreach('firewall', null, (s) => {
if (match(s['.name'], /^dawnline_/) && !want[s['.name']])
push(stale, s['.name']);
});
for (let s in stale) {
c.delete('firewall', s);
changed = true;
}
if (dry)
return changed;
if (changed) {
c.commit('firewall');
ack_config([ 'firewall' ]);
system('fw4 -q reload');
system("logger -t dawnline 'firewall updated'");
}
return changed;
};
/**
* For the watchdog: what is wrong with Dawnline's firewall, or null.
* 'off': fw4 is not running at all (not ours to start); 'changed': the config
* lost or changed Dawnline's sections; 'not loaded': fw4 runs without them.
*/
export function drift(m) {
let t = sh_out('nft -t list table inet fw4 2>/dev/null') ?? '';
if (t == '')
return 'off';
if (sync(m, true))
return 'changed';
// Named rules show up in fw4's ruleset as comments.
let names = [];
for (let id, srv in m.servers)
if (srv.enabled && length(core.tunnels(srv)))
push(names, `Dawnline-${srv.ifname}`);
if (m.settings.portal_enabled)
push(names, 'Dawnline-Portal');
for (let n in names)
if (index(t, `${n}"`) < 0)
return 'not loaded';
return null;
};
const MARK_ALL = 0xffffffff;
function hx(n) {
return sprintf('0x%x', n);
}
/**
* Policy rules that send marked traffic into a table with `local default`,
* the way transparent proxies capture the router's own traffic:
* [{ pref, mark, mask, table }], one per mark and mask.
*/
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+)/);
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] };
let key = `${d.mark}/${d.mask}`;
if (seen[key] || !match(sh_out(`ip ${fam} route show table ${d.table} 2>/dev/null`) ?? '', /(^|\n)local default/))
continue;
seen[key] = true;
push(out, d);
}
return out;
};
/** A divert as `ip rule` shows it, for people: "pref 1000 fwmark 0x1 → table 100". */
export function divert_str(d) {
return `pref ${d.pref} fwmark ${hx(d.mark)}${d.mask == MARK_ALL ? '' : `/${hx(d.mask)}`} → table ${d.table}`;
};
/** Ports Dawnline answers on from the outside: { tcp: [...], udp: [...] }. */
function reply_ports(m) {
let p = { tcp: [], udp: [] };
let ok = (n) => n >= 1 && n <= 65535;
if (m.settings.portal_enabled) {
push(p.tcp, +m.settings.portal_port);
if (core.portal_http(m))
push(p.tcp, +core.portal_http_port(m));
}
for (let id, srv in m.servers)
if (srv.private_key && srv.enabled)
push(p.udp, +srv.port);
return { tcp: uniq(filter(p.tcp, ok)), udp: uniq(filter(p.udp, ok)) };
}
/** The reply table for these diverts, or '' when there is nothing to keep out of them. */
function reply_script(m, diverts) {
let p = reply_ports(m);
if (!length(diverts) || !length(p.tcp) && !length(p.udp))
return '';
let t = [];
push(t, `table inet ${REPLY_TABLE} {`);
push(t, ' chain out {');
// After the proxies' own output chains (they mark at mangle, -150).
push(t, ' type route hook output priority filter + 10; policy accept;');
for (let proto in [ 'tcp', 'udp' ]) {
if (!length(p[proto]))
continue;
for (let d in diverts)
// Only the divert's bits: other marks on the packet (multi-WAN) stay.
push(t, ` ${proto} sport { ${join(', ', p[proto])} } ` + (d.mask == MARK_ALL
? `meta mark ${hx(d.mark)} meta mark set 0x0`
: `meta mark & ${hx(d.mask)} == ${hx(d.mark)} meta mark set meta mark & ${hx(~d.mask & MARK_ALL)}`));
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
function reply_loaded() {
return system(`nft list table inet ${REPLY_TABLE} >/dev/null 2>&1`) == 0;
}
/** Are the answers from our ports kept out of these diverts right now (watchdog)? */
export function reply_ok(m, diverts) {
let s = reply_script(m, diverts);
return s == '' || (s == readfile(REPLY_SIG) && reply_loaded());
};
/**
* Keep the reply table in step with our ports and the proxies' diverts (apply
* and every agent tick: a proxy may start after Dawnline). Cheap when nothing changed.
*/
export function sync_reply_routes(m) {
// Rules of older versions ("90: from all iif lo ipproto udp sport 51820 lookup main", once without "iif lo").
for (let fam in [ '-4', '-6' ])
for (let line in split(sh_out(`ip ${fam} rule show priority ${PREF_REPLY} 2>/dev/null`) ?? '', '\n')) {
let mm = match(line, /(iif lo )?ipproto (tcp|udp) sport ([0-9]+) lookup main/);
if (mm)
sh(`ip ${fam} rule del priority ${PREF_REPLY}${mm[1] ? ' iif lo' : ''} ipproto ${mm[2]} sport ${mm[3]} lookup main 2>/dev/null`);
}
let s = reply_script(m, proxy_diverts());
if (s == '') {
if (reply_loaded())
system(`nft delete table inet ${REPLY_TABLE} 2>/dev/null`);
unlink(REPLY_SIG);
return;
}
if (s == readfile(REPLY_SIG) && reply_loaded())
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)}`);
return;
}
write_file(REPLY_SIG, s, 0o644);
};
@@ -1,14 +1,20 @@
// Dawnline — city-level locations for the admin map. // Dawnline — city-level locations for the admin map.
// //
// Client addresses are looked up once with a third-party service (ipwho.is, // Client addresses are looked up once with a third-party service (ipwho.is,
// ipapi.co as fallback) and cached in DATA_DIR/geo.json. Only the agent // ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
// performs lookups, a few per minute at most; the UI reads the cache. // flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
// counters. Only the agent performs lookups, on its minute tick and within a
// time budget, never on the 1-second watcher; the UI reads the cache.
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR } from 'dawnline.util'; import { stat } from 'fs';
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
const CACHE = `${DATA_DIR}/geo.json`; const CACHE = `${RUN_DIR}/geo.json`;
const SAVED = `${DATA_DIR}/geo.json`;
const TTL = 30 * 86400; const TTL = 30 * 86400;
const RETRY = 86400; const RETRY = 86400;
// Entries kept at least; addresses still shown are never pushed out (resolve).
const CAP = 500;
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …). // [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ], const PRIVATE4 = map([ [ '0.0.0.0', 8 ], [ '10.0.0.0', 8 ], [ '100.64.0.0', 10 ], [ '127.0.0.0', 8 ], [ '169.254.0.0', 16 ],
@@ -30,16 +36,30 @@ export function is_public(ip) {
}; };
export function load() { export function load() {
return read_json(CACHE, null) ?? { ips: {}, home: null }; return read_json(CACHE, null) ?? read_json(SAVED, null) ?? { ips: {}, home: null };
}; };
/** The live copy (tmpfs); flush() puts it on flash. */
export function save(cache) { export function save(cache) {
ensure_dir(DATA_DIR, 0o700); ensure_dir(RUN_DIR);
write_json(CACHE, cache, 0o600); write_json(CACHE, cache, 0o600);
}; };
/** Copy the live cache to flash when it is newer (the agent, about hourly and on a clean stop). */
export function flush() {
let live = stat(CACHE);
if (!live || live.mtime <= (stat(SAVED)?.mtime ?? 0))
return false;
let c = read_json(CACHE, null);
if (!c)
return false;
ensure_dir(DATA_DIR, 0o700);
write_json(SAVED, c, 0o600);
return true;
};
function fetch_json(url) { function fetch_json(url) {
let out = sh_out(`uclient-fetch -q -T 8 -O - ${q(url)}`); let out = sh_out(`uclient-fetch -q -T 5 -O - ${q(url)}`);
if (!out) if (!out)
return null; return null;
try { try {
@@ -79,13 +99,17 @@ export function lookup(provider, ip) {
}; };
/** /**
* Resolve up to `max` addresses that are missing or stale. Returns true when * Resolve up to `max` of `ips` that are missing or stale, within `budget`
* the cache changed (the caller saves it). * seconds (each lookup may wait on the network). Returns true when the cache
* changed (the caller saves it). `ips` is also what is still shown: the cache
* is kept bounded by dropping other entries only, oldest first, so a lookup
* is never repeated for an address that is still on the map.
*/ */
export function resolve(settings, cache, ips, max) { export function resolve(settings, cache, ips, max, budget) {
let now = time(), changed = false, done = 0; let now = time(), changed = false, done = 0;
let started = now;
for (let ip in ips) { for (let ip in ips) {
if (done >= max) if (done >= max || (budget != null && time() - started >= budget))
break; break;
if (!is_public(ip)) if (!is_public(ip))
continue; continue;
@@ -103,12 +127,17 @@ export function resolve(settings, cache, ips, max) {
else else
cache.ips[ip] = { fail: now }; cache.ips[ip] = { fail: now };
} }
// Keep the cache bounded: drop the oldest entries beyond 500. let shown = {};
for (let ip in ips)
shown[ip] = true;
let all = keys(cache.ips); let all = keys(cache.ips);
if (length(all) > 500) { if (length(all) > CAP) {
all = sort(all, (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0)); let other = sort(filter(all, (ip) => !shown[ip]),
for (let i = 0; i < length(all) - 500; i++) (a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
delete cache.ips[all[i]]; for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
delete cache.ips[other[i]];
changed = true;
}
} }
return changed; return changed;
}; };
@@ -132,4 +161,6 @@ export function place(cache, ip) {
export function clear() { export function clear() {
save({ ips: {}, home: null }); save({ ips: {}, home: null });
ensure_dir(DATA_DIR, 0o700);
write_json(SAVED, { ips: {}, home: null }, 0o600);
}; };
@@ -0,0 +1,226 @@
// Dawnline — GitHub for the updater and the Components tab: API calls with a
// short cache, releases (with each asset's sha256), the changes between two
// tags, and verified downloads.
//
// Trust: the API is only ever asked directly (TLS to api.github.com). Files
// may come through a mirror when GitHub is unreachable, but only when their
// sha256 is known from the API, and a file is kept only if it matches.
import { stat, popen, access } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR } from 'dawnline.util';
/** Prefixes that fetch github.com files when GitHub itself is unreachable. */
export const MIRRORS = [ 'https://ghfast.top/', 'https://gh-proxy.com/', 'https://ghproxy.net/' ];
function run(cmd) {
let p = popen(cmd + ' 2>&1', 'r');
if (!p)
return { code: 127, out: '' };
let out = p.read('all') ?? '';
return { code: p.close(), out };
}
function have_curl() {
return access('/usr/bin/curl', 'x');
}
/**
* GET a URL: { status, body } (status 0 when there was no answer). curl gives
* the HTTP status, so a 403 rate limit is told apart from a dead network.
*/
function get(url, timeout) {
timeout ??= 12;
if (have_curl()) {
let r = run(`curl -sSL --connect-timeout 6 --max-time ${+timeout} -H 'Accept: application/vnd.github+json' -A Dawnline -w '\\n%{http_code}' ${q(url)}`);
// The body, then the status on the last line (-w).
let i = rindex(r.out, '\n');
let code = i < 0 ? '' : substr(r.out, i + 1);
return match(code, /^[0-9][0-9][0-9]$/) ? { status: +code, body: substr(r.out, 0, i) } : { status: 0, body: '' };
}
let r = run(`uclient-fetch -q -T ${+timeout} -O - ${q(url)}`);
return { status: r.code == 0 ? 200 : 0, body: r.code == 0 ? r.out : '' };
}
/** JSON from the GitHub API, or null when GitHub did not answer; dies on a rate limit or another API error. */
function api_json(url) {
let r = get(url);
if (r.status == 0)
return null;
let j = null;
try {
j = json(r.body);
}
catch (e) {
return null;
}
if (r.status == 403 || r.status == 429 || (type(j) == 'object' && match(j.message ?? '', /rate limit/i)))
die('GitHub API rate limit reached: try again in an hour.');
if (r.status == 404)
return null;
if (r.status >= 400)
die(`GitHub: ${j?.message ?? `HTTP ${r.status}`}`);
return j;
}
function cached(key, ttl, fn) {
let path = `${RUN_DIR}/gh-${replace(key, /[^A-Za-z0-9_.-]/g, '_')}.json`;
let c = read_json(path, null);
if (c && time() - (c.at ?? 0) < ttl)
return c.data;
let data = fn();
if (data != null) {
ensure_dir(RUN_DIR);
write_json(path, { at: time(), data });
}
return data ?? c?.data;
}
/* ---------- releases ---------- */
function slim(x) {
let digests = {};
for (let a in x.assets ?? [])
if (match(a.digest ?? '', /^sha256:[0-9a-f]{64}$/))
digests[a.name] = substr(a.digest, 7);
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,
};
}
/** Releases of a repository, newest first, five per page (drafts skipped). */
export function releases(rp, page) {
page = page ?? 1;
return cached(`rel-${rp}-${page}`, 600, () => {
let j = api_json(`https://api.github.com/repos/${rp}/releases?per_page=5&page=${+page}`);
return type(j) == 'array' ? map(filter(j, (x) => !x.draft), slim) : null;
}) ?? [];
};
/** One release by tag (notes, assets and their sha256), or null. */
export function release(rp, tag) {
return cached(`tag-${rp}-${tag}`, 600, () => {
let j = api_json(`https://api.github.com/repos/${rp}/releases/tags/${tag}`);
return type(j) == 'object' && j.tag_name ? slim(j) : null;
});
};
/** The sha256 GitHub publishes for a release file, or null (unknown: no mirrors for it). */
export function asset_sha256(rp, tag, name) {
try {
return release(rp, tag)?.digests?.[name] ?? null;
}
catch (e) {
return null;
}
};
/** The latest stable release; the /releases/latest redirect when the API is out of reach. */
export function latest(rp) {
let r = null;
try {
r = cached(`latest-${rp}`, 300, () => {
let j = api_json(`https://api.github.com/repos/${rp}/releases/latest`);
return type(j) == 'object' && j.tag_name ? slim(j) : null;
});
}
catch (e) {}
if (r)
return r;
if (have_curl()) {
let o = run(`curl -sI --connect-timeout 15 --max-time 30 -o /dev/null -w '%{redirect_url}' ${q('https://github.com/' + rp + '/releases/latest')}`);
let m = match(trim(o.out), /\/releases\/tag\/([^\/?#]+)$/);
if (m)
return { tag: m[1], name: m[1], published: null, prerelease: false, url: `https://github.com/${rp}/releases/tag/${m[1]}`, body: '', assets: [], digests: {} };
}
return null;
};
/* ---------- what changed ---------- */
/**
* What changed in a commit message, as points: release commits ("Dawnline
* 0.3.1") list their changes as "- " lines in the body; other commits are
* their title. Wrapped points are joined back into one line.
*/
export function points(msg) {
let lines = split(msg ?? '', '\n');
let title = trim(lines[0] ?? '');
if (match(title, /^Merge /))
return [];
let out = [], cur = null;
for (let i = 1; i < length(lines); i++) {
let m = match(lines[i], /^\s*[-*]\s+(.*)$/);
if (m) {
if (cur != null)
push(out, cur);
cur = trim(m[1]);
}
else if (cur != null && match(lines[i], /^\s+\S/))
cur += ' ' + trim(lines[i]);
else if (cur != null) {
push(out, cur);
cur = null;
}
}
if (cur != null)
push(out, cur);
if (!length(out) && !match(title, /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) && title != '')
push(out, title);
return out;
};
/** The changes from one tag to another, newest first: commit by commit, or the release's own commit. */
export function changes(rp, base, head) {
return cached(`changes-${rp}-${base}-${head}`, 600, () => {
let out = [];
let j = base ? api_json(`https://api.github.com/repos/${rp}/compare/${base}...${head}`) : null;
if (type(j?.commits) == 'array') {
for (let i = length(j.commits) - 1; i >= 0; i--)
for (let p in points(j.commits[i]?.commit?.message))
push(out, p);
return slice(out, 0, 20);
}
let c = api_json(`https://api.github.com/repos/${rp}/commits/${head}`);
return c?.commit ? slice(points(c.commit.message), 0, 20) : null;
}) ?? [];
};
/* ---------- downloads ---------- */
export function sha256(path) {
return match(run(`sha256sum ${q(path)}`).out, /^([0-9a-f]{64})/)?.[1];
};
/**
* 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
* file that does not match the sha256 is thrown away and the next source is
* tried. Returns the URL that worked, or null.
*/
export function download(url, dest, o) {
o ??= {};
let want = o.sha256 ? lc(o.sha256) : null;
let tries = [ url ];
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)
o.log?.(`Trying mirror ${host}`);
let r = have_curl()
? run(`curl -fsSL --connect-timeout 15 --max-time 300 --retry 1 -o ${q(dest)} ${q(u)}`)
: run(`uclient-fetch -q -T 30 -O ${q(dest)} ${q(u)}`);
if (r.code == 0 && (stat(dest)?.size ?? 0) > 0) {
if (!want || sha256(dest) == want)
return u;
o.log?.(`Warning: ${host} sent a file that does not match GitHub's sha256, discarded`);
}
system(`rm -f ${q(dest)}`);
if (i == 0 && length(tries) > 1)
o.log?.('GitHub did not answer, trying mirrors');
}
return null;
};
@@ -0,0 +1,580 @@
// Dawnline — Health: what the router has and lacks (packages, listeners,
// networks), the checks shown on Diagnostics → Health, and their fixes.
import { readfile, stat, lsdir } from 'fs';
import { cursor } from 'uci';
import { q, sh, sh_out, parse_cidr, cidr_overlaps, ip2int, in_cidr, file_exists, cloudflare_ip } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as fw from 'dawnline.fw';
import * as loop from 'dawnline.loop';
import * as net from 'dawnline.net';
import * as awg from 'dawnline.awg';
import * as builds from 'dawnline.awg_builds';
import * as lookup from 'dawnline.lookup';
import * as pc from 'dawnline.portalcert';
/* ---------- what the router has ---------- */
/**
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link), awg
* (AmneziaWG: the tools with netifd's protocol script, and the kernel module). Checked by
* files, so it is cheap enough for every page load.
*/
export function needs() {
let tls = false;
for (let d in [ '/lib', '/usr/lib' ])
for (let f in lsdir(d) ?? [])
if (substr(f, 0, 16) == 'libustream-ssl.s')
tls = true;
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let kmod = (name) => stat(`/sys/module/${name}`) != null || file_exists(`/lib/modules/${kver}/${name}.ko`);
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
return {
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ kmod('veth'), 'kmod-veth' ] ]),
// amneziawg-tools ships both the awg tool and netifd's protocol script.
awg: miss([ [ file_exists('/usr/bin/awg') && file_exists('/lib/netifd/proto/amneziawg.sh'), 'amneziawg-tools' ],
[ kmod('amneziawg'), 'kmod-amneziawg' ] ]),
};
};
/** 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 /);
if (m)
out[hex(m[1])] = true;
}
return map(keys(out), (k) => +k);
};
/**
* Programs on 'tcp' or 'udp' ports, our portal left out: { port: "dnsmasq" }.
* Kernel sockets (a tunnel's) have no name.
*/
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]+/);
if (f[0] != proto && f[0] != `${proto}6`)
continue;
let m = match(f[3] ?? '', /:([0-9]+)$/);
let owner = split(f[length(f) - 1], '/');
if (!m || !owner[1] || out[m[1]])
continue;
// Our own portal runs as a dedicated uhttpd instance.
if (index(readfile(`/proc/${+owner[0]}/cmdline`) ?? '', '/usr/share/dawnline/portal') >= 0)
continue;
out[m[1]] = owner[1];
}
return out;
}
export function udp_port_programs() {
return port_programs('udp');
};
export function tcp_port_programs() {
return port_programs('tcp');
};
export function udp_listening(port) {
return index(udp_bound(), +port) >= 0;
};
export function tcp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
for (let line in split(readfile(f) ?? '', '\n'))
// state 0A = LISTEN
if (index(line, hex) > 0 && match(line, / 0A /))
return true;
return false;
};
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
export function tcp_port_owners(port) {
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
let owners = [];
for (let o in split(out, '\n')) {
let name = split(o, '/')[1];
if (!name || index(owners, name) >= 0)
continue;
// Our own portal runs as a dedicated uhttpd instance.
let pid = +split(o, '/')[0];
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
continue;
push(owners, name);
}
return owners;
};
export function service_running(name, instance) {
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
if (!s)
return false;
try {
return !!json(s)?.[name]?.instances?.[instance]?.running;
}
catch (e) {
return false;
}
};
/** IPv4 networks of netifd interfaces: [{ iface, cidr }], without the given server's tunnel. */
function other_subnets(srv_id) {
let out = [];
let st = sh_out('ubus call network.interface dump 2>/dev/null');
let d = null;
try {
d = st ? json(st) : null;
}
catch (e) {
d = null;
}
let ours = {};
for (let id, s in core.load().servers)
ours[s.ifname] = id;
for (let i in d?.interface ?? []) {
if (srv_id != null && ours[i.interface] == srv_id)
continue;
if (srv_id === false && ours[i.interface] != null)
continue;
for (let a in i['ipv4-address'] ?? [])
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
}
return out;
};
/** Subnets in use on the router except the given server's (null: all of them). */
/** The router's IPv4 networks, Dawnline's tunnels included: [{ iface, cidr }]. */
export function networks() {
return other_subnets(null);
};
export function used_subnets(except_srv) {
return map(other_subnets(except_srv), (x) => x.cidr);
};
/** Subnets of interfaces that are not Dawnline tunnels (an imported config is checked against these). */
export function foreign_subnets() {
return used_subnets(false);
};
/* ---------- checks ---------- */
/*
* Checks are named for the healthy state ("Clock is set"); a failed one also
* gets the problem in words for notices ("Clock isn't set"). Longest names
* first; a server's name after the check name is kept.
*/
const PROBLEM = [
[ 'AmneziaWG answers reach devices', 'AmneziaWG answers may not reach devices' ],
[ 'AmneziaWG devices loaded', 'Not every device is loaded into AmneziaWG' ],
[ 'AmneziaWG subnet is unique', 'AmneziaWG subnet overlaps another network' ],
[ 'AmneziaWG port is free', 'AmneziaWG port is taken' ],
[ 'AmneziaWG installed', 'AmneziaWG isn’t ready' ],
[ 'AmneziaWG firewall', 'AmneziaWG firewall rules are missing' ],
[ 'AmneziaWG running', 'AmneziaWG is down' ],
[ 'Portal answers reach visitors', 'Portal answers may not reach visitors' ],
[ 'Portal address points here', 'Portal address doesn’t point here' ],
[ 'Portal address', 'Portal address isn’t set' ],
[ 'Portal certificate', 'Portal certificate needs attention' ],
[ 'Personal portal', 'Personal portal isn’t working' ],
[ 'Plain HTTP links', 'Portal links use plain HTTP' ],
[ 'Internet like a home device', 'Internet like a home device isn’t working' ],
[ 'DNS for Home-only devices', 'DNS for Home-only devices isn’t working' ],
[ 'Background agent running', 'Background agent isn’t running' ],
[ 'Access rules loaded', 'Access rules aren’t loaded' ],
[ 'Server configured', 'No server yet' ],
[ 'Public address', 'Public address needs attention' ],
[ 'Clock is set', 'Clock isn’t set' ],
];
function problem_of(title) {
for (let p in PROBLEM)
if (substr(title, 0, length(p[0])) == p[0])
return p[1] + substr(title, length(p[0]));
return title;
}
/** problem: the failed check in words, when the table's wording does not fit the case. */
function check(id, title, status, detail, fix, problem) {
let bad = status == 'warn' || status == 'error';
return { id, title, status, detail: detail ?? '', fix: fix ?? null, problem: bad ? (problem ?? problem_of(title)) : null };
}
/**
* Answers from our ports and the proxies that would swallow them (fw.sync_reply_routes):
* { ok, diverts: ["pref 1000 fwmark 0x1 → table 100"] }.
*/
function replies(m) {
let d = fw.proxy_diverts();
return { ok: fw.reply_ok(m, d), diverts: map(d, fw.divert_str) };
}
function reply_check(id, title, proto, port, r) {
let via = join(', ', r.diverts);
return check(id, title, r.ok ? 'ok' : 'error',
!r.ok ? `Answers from ${uc(proto)} ${port} are swallowed by a proxy on the router (${via}): clients get no reply.`
: length(r.diverts) ? `Answers from ${uc(proto)} ${port} go straight out. A proxy on the router diverts its own traffic (${via}); these answers skip it.`
: `Answers from ${uc(proto)} ${port} go straight out.`,
r.ok ? null : 'apply');
}
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
/** What kind of IPv4 the WAN has: public, cgnat (100.64/10), private (behind another router), or none. */
export function wan_kind(wan) {
let wc = wan ? ip2int(wan) : null;
if (wc == null)
return 'none';
if (in_cidr(wc, PRIVATE[0]))
return 'cgnat';
return length(filter(PRIVATE, (c) => in_cidr(wc, c))) ? 'private' : 'public';
};
/**
* 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 }.
*/
export function endpoint_facts(srv, host) {
let ips = host ? lookup.resolve(host) : [];
let wan = srv ? (net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone)) : lookup.wan_ipv4('wan');
let ips4 = filter(ips, (a) => ip2int(a) != null), ips6 = filter(ips, (a) => ip2int(a) == null);
return {
host, ips, ips4, ips6, wan: wan ?? null, kind: wan_kind(wan),
cloudflare: length(filter(ips, (a) => cloudflare_ip(a))) > 0,
here: wan != null && index(ips4, wan) >= 0,
v6_only: !length(ips4) && length(ips6) > 0,
};
};
/** The facts in words: { status: ok|warn|error, text }. `proto_note` names what must get through ("UDP 4500"). */
export function endpoint_words(f, proto_note) {
if (!f.host)
return { status: 'error', text: 'No public address: devices will not know where to connect.' };
if (!length(f.ips))
return { status: 'error', text: `${f.host} does not resolve.` };
if (f.cloudflare)
return { status: 'error', text: `${f.host} → ${join(', ', f.ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.` };
if (f.v6_only)
return { status: f.kind == 'public' ? 'warn' : 'ok', text: `${f.host} → ${join(', ', f.ips6)}: IPv6 only, so only devices with IPv6 connect${f.kind == 'public' ? ` (the router's IPv4 ${f.wan} has no name)` : ''}.` };
if (f.kind == 'cgnat' || f.kind == 'private')
return { status: 'warn', text: f.kind == 'cgnat'
? `The WAN address ${f.wan} is CGNAT (shared by the ISP): ${proto_note} cannot be forwarded to this router from outside unless the ISP gives a public address or IPv6.`
: `The WAN address ${f.wan} is private: this router is behind another one. Forward ${proto_note} on it, or devices cannot connect.` };
if (f.wan && !f.here)
return { status: 'warn', text: `${f.host} points at ${join(', ', f.ips4)}, not this router (WAN ${f.wan}). Check your DNS / DDNS.` };
return { status: 'ok', text: f.here ? `${f.host} points at this router (${f.wan}).` : `${f.host} → ${join(', ', f.ips)}` };
};
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
function endpoint_check(id, title, srv, host, proto_note) {
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
return check(id, title, w.status, w.text);
}
/**
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
* Dawnline's (pref < 5205) whose table has a default route of its own sends
* marked tunnel traffic straight out, past "like a home device". Reported,
* since those marks belong to that package. [] when none.
*/
function policy_routing() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
if (!mm || +mm[1] >= 5205)
continue;
let routes = sh_out(`ip -4 route show table ${q(mm[4])} 2>/dev/null`) ?? '';
let def = match(routes, /(^|\n)default [^\n]*/)?.[0] ?? '';
if (def == '' || match(def, /local default/) || index(def, `dev ${net.INTERNAL.transit}`) >= 0)
continue;
push(out, `pref ${mm[1]} fwmark 0x${mm[2]} → table ${mm[4]}`);
}
return out;
}
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
let out = sh('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
let m = match(out ?? '', /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
return m ? +m[1] : null;
}
/** Is AmneziaWG there and usable: packages, kernel module, netifd's protocol handler. */
function awg_check() {
let st = awg.load();
let title = 'AmneziaWG installed';
if (length(st.missing ?? [])) {
// The module was built for the kernel of the firmware it was installed on.
let kc = builds.kernel_changed();
if (kc && index(st.missing, 'kmod-amneziawg') >= 0)
return check('awg', title, 'error',
`The firmware changed (kernel ${kc.was} → ${kc.now}): the AmneziaWG build installed for it is gone. Install the build for this firmware.`,
'install:awg', 'AmneziaWG needs a build for the new firmware');
return check('awg', title, 'error', `${join(' and ', st.missing)} ${length(st.missing) == 1 ? 'is' : 'are'} missing.`, 'install:awg',
'AmneziaWG isn’t installed');
}
if (!st.loaded) {
// load() tried it: the second modprobe only repeats why.
let why = trim(sh('modprobe amneziawg 2>&1; dmesg | grep -i amneziawg | tail -n 3').out);
return check('awg', title, 'error',
`The kernel module doesn't load${why ? `: ${why}` : '.'} Reinstall a build for this kernel in Components.`, 'updates',
'AmneziaWG’s kernel module doesn’t load');
}
if (!st.handler)
return check('awg', title, 'error', NO_PROTO, 'netrestart', 'The network doesn’t know AmneziaWG yet');
return check('awg', title, 'ok', 'Kernel module, awg tool and the netifd protocol are present.');
}
/** Checks of a server's AmneziaWG tunnel. */
function awg_checks(m, id, srv, label, fwc, dmp, rep) {
let out = [];
let st = live.iface_status(srv.ifname);
let up = !!st?.up;
let codes = map(st?.errors ?? [], (e) => e.code);
if (!up && index(codes, 'INVALID_PROTO') >= 0)
push(out, check(`up_${id}`, `AmneziaWG running${label}`, 'error', NO_PROTO, 'netrestart'));
else
push(out, check(`up_${id}`, `AmneziaWG running${label}`, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
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]));
let same = !missing && !extra;
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, same ? 'ok' : 'warn',
same ? `${actual} device${actual == 1 ? ' is' : 's are'} loaded in the tunnel.` :
`${missing} of ${expected} device${expected == 1 ? '' : 's'} missing${extra ? `, ${extra} loaded that should not be` : ''}.`,
same ? null : 'sync'));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `AmneziaWG firewall${label}`, rule && zone ? 'ok' : 'error',
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
rule && zone ? null : 'apply'));
push(out, reply_check(`reply_${id}`, `AmneziaWG answers reach devices${label}`, 'udp', srv.port, rep));
// Port collisions with other tunnels.
let clash = [];
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
push(clash, s['.name']);
});
if (length(clash))
push(out, check(`port_${id}`, `AmneziaWG port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
let overlaps = [];
let sc = parse_cidr(srv.subnet);
for (let o in other_subnets(id)) {
let oc = parse_cidr(o.cidr);
if (sc && oc && cidr_overlaps(sc, oc))
push(overlaps, `${o.iface} (${o.cidr})`);
}
push(out, check(`subnet_${id}`, `AmneziaWG subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
return out;
}
/** The portal's checks: listening, its address, answers, plain HTTP and the certificate. */
function portal_checks(m, need, rep) {
let out = [];
let s = m.settings;
if (length(need.https))
return [ check('portal', 'Personal portal', 'error', `HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https') ];
let owners = tcp_port_owners(s.portal_port);
let listening = tcp_listening(s.portal_port);
if (length(owners))
push(out, check('portal', 'Personal portal', 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
else
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
if (!s.portal_host)
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
else {
let ips = lookup.resolve(s.portal_host), wan = lookup.router_wan(m);
let cf = filter(ips, (x) => cloudflare_ip(x));
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
!length(ips) ? `${s.portal_host} does not resolve.` :
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
}
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, rep));
if (core.portal_http(m)) {
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
push(out, check('portal_http', 'Plain HTTP links', 'warn',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
}
if (ip2int(s.portal_host) != null) {
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
return out;
}
let cert = pc.portal_cert(s);
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
let sans = cert.self_signed ? [] : pc.cert_names(cert.cert);
let covers = !s.portal_host || cert.self_signed || length(filter(sans, (n) => pc.name_covers(n, s.portal_host))) > 0;
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
return out;
}
/**
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
* `fix` names an action accepted by fix(), or one the UI handles itself
* (install:<feature>, updates).
*/
export function health(m) {
m ??= core.load();
let rep = replies(m);
let out = [];
let dmp = live.dump(m);
let need = needs();
if (length(m.servers))
push(out, awg_check());
let y = localtime().year;
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
let agent = service_running('dawnline', 'agent');
push(out, check('agent', 'Background agent running', agent ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', agent ? null : 'restart'));
// A full overlay fails every config write on the router, Dawnline's and
// OpenWrt's own; backups and history are what Dawnline adds to it.
let free = overlay_free_kb();
if (free != null)
push(out, check('flash', 'Free space on the router', free < 512 ? 'error' : free < 2048 ? 'warn' : 'ok',
free < 2048 ? `${int(free / 1024 * 10) / 10} MB free: settings may stop saving. Remove old backups (Settings → Backups) or shorten the history.`
: `${int(free / 1024)} MB free on the overlay.`,
null, 'The router is running out of flash'));
if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
return out;
}
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.'
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.',
nft_ok ? null : 'apply'));
if (length(filter(values(m.servers), (s) => s.lan_like && s.enabled))) {
let pr = policy_routing();
push(out, check('policy', 'Internet like a home device not bypassed', length(pr) ? 'warn' : 'ok',
length(pr) ? `Policy routing on the router (${join('; ', pr)}) sends marked traffic straight out, past the home-device path: tunnel traffic it matches skips your LAN's proxies and filters.`
: 'No other policy routing ahead of the tunnel rules.',
null, 'Other policy routing bypasses the home-device path'));
}
// A device the sync has to leave out (a merged import, a hand-edited config).
let data = core.model_errors(m);
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok',
length(data) ? `${join(' ', slice(data, 0, 4))}${length(data) > 4 ? ` (${length(data) - 4} more)` : ''} Such devices are left out of the tunnels: fix or remove them.`
: 'Every device has a key and an address of its own inside its server.'));
let fwc = cursor();
fwc.load('firewall');
for (let id, srv in m.servers) {
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
if (!srv.enabled) {
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
continue;
}
push(out, ...awg_checks(m, id, srv, label, fwc, dmp, rep));
push(out, endpoint_check(`ep_${id}`, `Public address${label}`, srv, core.endpoint_host(m, srv), `UDP ${srv.port}`));
if (srv.lan_like) {
let ls = loop.status();
let nh = need.home;
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
ls.active ? `The link is up but not attached to ${ls.dev}.` :
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
}
}
// While every server is off the resolver only idles on loopback: nothing to check.
if (length(filter(values(m.servers), (x) => x.enabled && x.private_key))) {
let rt = loop.resolver_target();
let conf = stat(loop.RESOLVER.conf);
let running = conf != null && loop.resolver_running();
// A new config (a server turned on, the home link up) restarts it: give it a few seconds.
let restarting = !running && conf != null && time() - conf.mtime < 10;
let ok = running || restarting;
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
restarting ? 'Restarting with the new settings.' :
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
}
if (m.settings.portal_enabled)
push(out, ...portal_checks(m, need, rep));
return out;
};
/** Run a fix named by a check. */
export function fix(id) {
if (id == 'apply')
return apply.apply();
if (id == 'sync')
return apply.sync();
if (id == 'restart')
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
// netifd learns protocol handlers (amneziawg) only when it starts. In the
// background: the answer goes out before the network blinks.
if (id == 'netrestart') {
system('( sleep 1; /etc/init.d/network restart ) >/dev/null 2>&1 </dev/null &');
return { ok: true, background: true };
}
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
if (m) {
// Only Dawnline's own tunnels: never another interface of the router.
let mine = filter(values(core.load().servers), (s) => s.ifname == m[1] && s.private_key);
if (!length(mine))
die(`${m[1]} is not one of Dawnline's tunnels.`);
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
};
@@ -1,4 +1,4 @@
// Dawnline — live data: peer status from `awg show all dump`, traffic // Dawnline — live data: peer status from the tunnels (dawnline.awg), traffic
// accounting and the connection/event log. // accounting and the connection/event log.
// //
// Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once // Counters live in RUN_DIR (tmpfs) and are flushed to DATA_DIR at most once
@@ -7,34 +7,37 @@
import { readfile, stat, unlink } from 'fs'; import { readfile, stat, unlink } from 'fs';
import { cursor } from 'uci'; import { cursor } from 'uci';
import { import {
q, sh, sh_out, sh_bg, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, uniq, ensure_dir, read_json, write_json, lock, unlock, month_key, day_key, day_key_ago, uniq,
RUN_DIR, DATA_DIR iface_status as util_iface_status, RUN_DIR, DATA_DIR
} from 'dawnline.util'; } from 'dawnline.util';
import * as awg from 'dawnline.awg';
import * as schema from 'dawnline.schema';
export const ONLINE_WINDOW = 300; // Online while the WireGuard session lives: it is dropped 180 s after its
const KEEP_DAYS = 62; // handshake, and a device that is there renews it every 2 min (a little slack
const KEEP_MONTHS = 24; // for a renewal that needs a retry). One that left goes offline 1-3 min later.
const KEEP_EVENTS = 2000; 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`;
/* ---------- retention policy ---------- */ /* ---------- retention policy ---------- */
/** Event type → log category (what Settings lets you switch off or clear). */ /** Event type → log category (what Settings lets you switch off or clear). */
export const CATEGORY = { export const CATEGORY = {
connect: 'connections', disconnect: 'connections', roam: 'connections', connect: 'connections', disconnect: 'connections', roam: 'connections',
device_added: 'devices', device_removed: 'devices', devices_removed: 'devices', // People and their devices: one category (devices used to have their own).
device_added: 'people', device_removed: 'people', devices_removed: 'people',
device_changed: 'people', device_keys: 'people', link_changed: 'people',
person_added: 'people', person_removed: 'people', person_changed: 'people', person_added: 'people', person_removed: 'people', person_changed: 'people',
paused: 'people', resumed: 'people', paused_all: 'people', resumed_all: 'people', paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems', server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
}; };
export const CATEGORIES = [ 'connections', 'devices', 'people', 'problems' ]; export const CATEGORIES = [ 'connections', 'people', 'problems' ];
export function category_of(type) { export function category_of(type) {
return CATEGORY[type] ?? 'problems'; return CATEGORY[type] ?? 'problems';
}; };
function int_or(v, d) {
return (v == null || v == '' || match(`${v}`, /[^0-9]/)) ? d : +v;
}
/** /**
* Log and history retention from /etc/config/dawnline (read fresh, the * Log and history retention from /etc/config/dawnline (read fresh, the
@@ -55,14 +58,15 @@ export function policy(s) {
cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES; cats = (s.log_connections == '0') ? filter(CATEGORIES, (x) => x != 'connections') : CATEGORIES;
else if (type(cats) != 'array') else if (type(cats) != 'array')
cats = split(cats, /[ ,]+/); cats = split(cats, /[ ,]+/);
cats = filter(cats, (x) => index(CATEGORIES, x) >= 0); cats = uniq(filter(map(cats, (x) => x == 'devices' ? 'people' : x), (x) => index(CATEGORIES, x) >= 0));
// Defaults and ranges come from dawnline.schema, like every other setting.
return { return {
keep_days: int_or(s.log_keep_days, 30), keep_days: schema.get(s, 'log_keep_days'),
max: min(max(int_or(s.log_max, KEEP_EVENTS), 100), 20000), max: schema.get(s, 'log_max'),
categories: cats, categories: cats,
persist: index([ '10min', 'hourly', 'off' ], s.log_persist) >= 0 ? s.log_persist : 'hourly', persist: schema.get(s, 'log_persist'),
usage_days: min(max(int_or(s.usage_keep_days, KEEP_DAYS), 7), 1830), usage_days: schema.get(s, 'usage_keep_days'),
usage_months: min(max(int_or(s.usage_keep_months, KEEP_MONTHS), 1), 120), usage_months: schema.get(s, 'usage_keep_months'),
}; };
}; };
@@ -77,39 +81,51 @@ function trim_events(ev, pol) {
return ev; return ev;
} }
/* ---------- awg dump ---------- */ /* ---------- live peers ---------- */
/* ---------- presence (the agent's watcher) ---------- */
/** /**
* Parse `awg show all dump`. Returns { ifaces: { ifname: {...} }, peers: { pubkey: {...} } }. * Written by the agent's watcher on every change: { online: { device id: bool },
* Interface lines have many fields (AmneziaWG adds obfuscation values); peer * endpoint: { device id: ip }, rev, people: { person id: rev } }. `rev` moves on
* lines always have 9. * any connect, disconnect, roam or logged change; `people` per person (the portal).
*/ */
export function dump() { export const PRESENCE = `${RUN_DIR}/presence.json`;
let r = sh('awg show all dump'); // The agent's heartbeat (dawnline.watchdog.BEAT): its presence counts while it runs.
let out = { ifaces: {}, peers: {} }; const BEAT = `${RUN_DIR}/agent.beat`;
if (r.code != 0) const BEAT_STALE = 180;
return out;
for (let line in split(r.out, '\n')) { /** What the watcher sees, or null when the agent isn't running. */
let f = split(line, '\t'); export function presence() {
if (length(f) == 9) { let beat = +(read_json(BEAT, 0) ?? 0);
let ep = f[3] == '(none)' ? '' : f[3]; if (!beat || time() - beat > BEAT_STALE)
out.peers[f[1]] = { return null;
ifname: f[0], return read_json(PRESENCE, null);
endpoint: ep, };
handshake: +f[5],
rx: +f[6], /**
tx: +f[7], * Peers of every tunnel: { ok, ifaces, peers: { public key: { ifname, endpoint,
}; * handshake, rx, tx } }, presence }. See dawnline.awg.
} */
else if (length(f) >= 5) { export function dump(m) {
out.ifaces[f[0]] = { public_key: f[2], port: +f[3] }; // 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;
return out; let d = awg.dump(mine);
d.presence = presence();
return d;
};
/** A device is online: as the agent's watcher says, or (without the agent) by a recent handshake. */
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);
}; };
export function endpoint_ip(ep) { export function endpoint_ip(ep) {
let m = match(ep ?? '', /^\[?([^\]]+?)\]?:[0-9]+$/); let m = match(ep ?? '', /^\[?([^\]]+)\]?:[0-9]+$/);
return m ? m[1] : ep; return m ? m[1] : ep;
}; };
@@ -119,8 +135,16 @@ function empty_usage() {
return { devices: {}, people: {}, updated: 0, flushed: 0 }; return { devices: {}, people: {}, updated: 0, flushed: 0 };
} }
export function load_usage() { /**
return read_json(`${RUN_DIR}/usage.json`, null) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage(); * The usage counters: the live copy in RUN_DIR, else what flash holds. With
* `from_flash` only flash counts (a restore put new counters there, and the
* watcher may have written the old live ones again since).
*/
export function load_usage(from_flash) {
let u = (from_flash ? null : read_json(`${RUN_DIR}/usage.json`, null)) ?? read_json(`${DATA_DIR}/usage.json`, null) ?? empty_usage();
// Per-app counters of earlier test builds are not kept.
delete u.clients;
return u;
}; };
function add(bucket, key, rx, tx) { function add(bucket, key, rx, tx) {
@@ -180,30 +204,41 @@ export function reset_usage(usage, m, scope, id) {
for (let did in m.people[id]?.devices ?? []) for (let did in m.people[id]?.devices ?? [])
wipe(usage.devices[did]); wipe(usage.devices[did]);
} }
else if (scope == 'device') { else if (scope == 'device')
wipe(usage.devices[id]); wipe(usage.devices[id]);
}
}; };
function offline(rec) {
return { online: false, handshake: rec?.handshake ?? 0, endpoint: rec?.endpoint ?? '', present: false };
}
/** /**
* Fold the current kernel counters into `usage`. Counters restart from zero * 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 * 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. * reset. 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.
*/ */
export function collect(m, usage, d) { export function collect(m, usage, d) {
d ??= dump(); d ??= dump(m);
let ts = time(); let ts = time();
let live = {}; let live = {};
let by_key = {}; if (d.ok === false && !length(d.peers)) {
for (let id, dev in m.devices) for (let id in keys(m.devices))
by_key[dev.public_key] = id; live[id] = offline(usage.devices[id]);
return live;
}
for (let id, dev in m.devices) { for (let id, dev in m.devices) {
let rec = usage.devices[id] ??= { raw: [ 0, 0 ] }; let rec = usage.devices[id] ??= { raw: [ 0, 0 ] };
let peer = d.peers[dev.public_key]; let peer = d.peers[dev.public_key];
if (!peer) { if (!peer) {
rec.raw = [ 0, 0 ]; let ifname = m.servers[m.people[dev.person]?.server]?.ifname;
live[id] = { online: false, handshake: rec.handshake ?? 0, endpoint: rec.endpoint ?? '', present: false }; if (d.ok !== false || d.ifaces[ifname] != null)
rec.raw = [ 0, 0 ];
live[id] = offline(rec);
continue; continue;
} }
let raw = rec.raw ?? [ 0, 0 ]; let raw = rec.raw ?? [ 0, 0 ];
@@ -258,9 +293,8 @@ export function save_usage(usage, persist) {
/** Sum of [rx, tx] over the last `days` days for a usage record. */ /** Sum of [rx, tx] over the last `days` days for a usage record. */
export function recent(rec, days) { export function recent(rec, days) {
let out = [ 0, 0 ]; let out = [ 0, 0 ];
let ts = time();
for (let i = 0; i < days; i++) { for (let i = 0; i < days; i++) {
let v = rec?.days?.[day_key(ts - i * 86400)]; let v = rec?.days?.[day_key_ago(i)];
if (v) { if (v) {
out[0] += v[0]; out[0] += v[0];
out[1] += v[1]; out[1] += v[1];
@@ -276,9 +310,8 @@ export function month(rec) {
/** Daily series for the last `days` days: [{ day, rx, tx }]. */ /** Daily series for the last `days` days: [{ day, rx, tx }]. */
export function series(recs, days) { export function series(recs, days) {
let out = []; let out = [];
let ts = time();
for (let i = days - 1; i >= 0; i--) { for (let i = days - 1; i >= 0; i--) {
let k = day_key(ts - i * 86400); let k = day_key_ago(i);
let rx = 0, tx = 0; let rx = 0, tx = 0;
for (let r in recs) { for (let r in recs) {
let v = r?.days?.[k]; let v = r?.days?.[k];
@@ -298,17 +331,33 @@ export function load_events() {
return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []); return read_json(`${RUN_DIR}/events.json`, null) ?? read_json(`${DATA_DIR}/events.json`, []);
}; };
/*
* Names as they are now (pname, dname, dkind), so the log still reads well
* once the person or device is gone. Callers that delete first pass them.
*/
function with_names(e, c) {
if (e.person && !e.pname)
e.pname = c.get('dawnline', e.person, 'name');
if (e.device && !e.dname)
e.dname = c.get('dawnline', e.device, 'name');
if (e.device && !e.dkind)
e.dkind = c.get('dawnline', e.device, 'kind');
return e;
}
export function add_events(list, pol) { export function add_events(list, pol) {
pol ??= policy(); pol ??= policy();
list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0); list = filter(list ?? [], (e) => index(pol.categories, category_of(e.type)) >= 0);
if (!length(list)) if (!length(list))
return; return;
let c = cursor();
c.load('dawnline');
let l = lock('events'); let l = lock('events');
let ev = load_events(); let ev = load_events();
let ts = time(); let ts = time();
for (let e in list) { for (let e in list) {
e.ts ??= ts; e.ts ??= ts;
push(ev, e); push(ev, with_names(e, c));
} }
ev = trim_events(ev, pol); ev = trim_events(ev, pol);
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
@@ -335,8 +384,10 @@ export function add_event_merged(e, window) {
last.ts = ts; last.ts = ts;
} }
else { else {
let c = cursor();
c.load('dawnline');
e.ts = ts; e.ts = ts;
push(ev, e); push(ev, with_names(e, c));
} }
ev = trim_events(ev, pol); ev = trim_events(ev, pol);
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
@@ -352,6 +403,10 @@ export function persist_events(pol) {
unlink(`${DATA_DIR}/events.json`); unlink(`${DATA_DIR}/events.json`);
return; return;
} }
// Only when something was logged since the last copy: flash is written rarely.
let live_st = stat(`${RUN_DIR}/events.json`);
if (!live_st || live_st.mtime <= (stat(`${DATA_DIR}/events.json`)?.mtime ?? 0))
return;
let ev = read_json(`${RUN_DIR}/events.json`, null); let ev = read_json(`${RUN_DIR}/events.json`, null);
if (ev != null) { if (ev != null) {
ensure_dir(DATA_DIR, 0o700); ensure_dir(DATA_DIR, 0o700);
@@ -389,17 +444,7 @@ export function clear_events(f) {
/* ---------- health ---------- */ /* ---------- health ---------- */
export function iface_status(ifname) { export function iface_status(ifname) {
if (!match(ifname ?? '', /^[A-Za-z0-9_.@-]{1,32}$/)) return util_iface_status(ifname);
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)
return null;
try {
return json(s);
}
catch (e) {
return null;
}
}; };
export function uptime() { export function uptime() {
@@ -0,0 +1,102 @@
// Dawnline — where names point and the router's public address, for Health
// and the portal settings. Lookups are cached in RUN_DIR for a few minutes
// and made in parallel with a short timeout: rpcd answers one call at a
// time, so a slow DNS server must not hold up the whole admin UI.
import { readfile } from 'fs';
import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
import * as live from 'dawnline.live';
import * as net from 'dawnline.net';
const CACHE = `${RUN_DIR}/resolve.json`;
// Answers are kept 5 minutes, failures 1 minute.
const TTL = 300;
const TTL_FAIL = 60;
const TIMEOUT = 2;
const MAX_NAMES = 16;
// Public resolvers first: local DNS often rewrites the router's own name to
// its LAN address (split horizon).
const SERVERS = [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ];
function valid_name(h) {
return type(h) == 'string' && length(h) <= 253 && match(h, /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$/) != null;
}
/**
* Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
* does not resolve). IP addresses map to themselves. Every uncached name is
* asked of every server at once, A and AAAA; the first server (in SERVERS
* order) that answers wins.
*/
export function resolve_all(hosts) {
let out = {}, now = time(), todo = [];
let cache = read_json(CACHE, {});
for (let h in hosts) {
if (h == null || out[h] != null)
continue;
if (ip2int(h) != null || is_ip6(h)) {
out[h] = [ h ];
continue;
}
let c = cache[h];
if (c && now - c.ts < (length(c.ips) ? TTL : TTL_FAIL))
out[h] = c.ips;
else if (valid_name(h) && length(todo) < MAX_NAMES) {
out[h] = [];
push(todo, h);
}
else
out[h] = [];
}
if (!length(todo))
return out;
ensure_dir(RUN_DIR);
let dir = `${RUN_DIR}/resolve.${rand_hex(4)}`;
let cmds = [];
for (let i = 0; i < length(todo); i++)
for (let j = 0; j < length(SERVERS); j++)
for (let t in [ 'a', 'aaaa' ])
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
for (let i = 0; i < length(todo); i++) {
let ips = [];
for (let j = 0; j < length(SERVERS) && !length(ips); j++)
for (let t in [ 'a', 'aaaa' ]) {
let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
}
out[todo[i]] = ips;
cache[todo[i]] = { ts: now, ips };
}
system(`rm -rf ${dir}`);
// Only what is still fresh is kept.
for (let h, c in cache)
if (now - c.ts >= TTL)
delete cache[h];
write_json(CACHE, cache, 0o644);
return out;
};
/** IPv4 addresses of one name (see resolve_all). */
export function resolve(host) {
return resolve_all([ host ])[host] ?? [];
};
/** 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);
return st?.['ipv4-address']?.[0]?.address;
};
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
export function router_wan(m) {
for (let id, srv in m.servers)
if (srv.private_key) {
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
if (a)
return a;
}
return wan_ipv4('wan');
};
@@ -14,12 +14,11 @@
// Clients also use the netns address as DNS: it forwards to the DNS the LAN // 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. // gets from DHCP, from the LAN side, so DNS interception applies as well.
// //
// Separately, people with Home-only access get a plain resolver (real // Separately, people with Home-only access get a plain resolver
// addresses from the WAN's DNS, home names from the LAN DNS): their internet // (dawnline.resolver). While the netns exists it runs inside it and sends its
// does not use the tunnel, so fake-IP answers would break it. While the netns // upstream queries back out through the transit link as forwarded traffic —
// exists the resolver runs inside it and sends its upstream queries back out // not as the router's own traffic and not from the LAN — so tools that
// through the transit link as forwarded traffic — not as the router's own // capture either leave it alone. This module says where it runs.
// traffic and not from the LAN — so tools that capture either leave it alone.
// //
// Everything is derived from the router at run time; nothing assumes a // Everything is derived from the router at run time; nothing assumes a
// particular subnet or tool. If the LAN is not a bridge or setup fails, the // particular subnet or tool. If the LAN is not a bridge or setup fails, the
@@ -27,21 +26,24 @@
import { readfile, writefile, readlink, stat, unlink } from 'fs'; import { readfile, writefile, readlink, stat, unlink } from 'fs';
import { cursor } from 'uci'; import { cursor } from 'uci';
import { sh, sh_out, q, ip2int, int2ip, ensure_dir, read_json, write_json, uniq, RUN_DIR } from 'dawnline.util'; import {
sh, sh_out, q, ip2int, int2ip, parse_cidr, cidr_any, ensure_dir, read_json, write_json, slog, RUN_DIR
} from 'dawnline.util';
import * as net from 'dawnline.net'; import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
import * as resolver from 'dawnline.resolver';
export const NS = 'dawnline'; export const NS = 'dawnline';
const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1'; const TX_ROOT = net.INTERNAL.transit, TX_NS = 'dlx1', LAN_ROOT = net.INTERNAL.lan, LAN_NS = 'dll1';
const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290; const PREF_LOOP_DNS = 5205, PREF_MAIN = 5210, PREF_LOOP = 5290;
const RESOLVER_PORT = 5354; export const RESOLVER_CONF = resolver.CONF;
export const RESOLVER_CONF = '/var/etc/dawnline-dns.conf';
const RESOLVER_RESOLV = '/var/etc/dawnline-dns.resolv';
const RESOLVER_PID = '/var/run/dawnline-dns.pid';
const STATE = `${RUN_DIR}/loop.json`; const STATE = `${RUN_DIR}/loop.json`;
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
function log(msg) { const WHO = 'Internet like a home device';
system(`logger -t dawnline ${q(msg)}`);
function log(msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, WHO);
} }
function run(cmds) { function run(cmds) {
@@ -58,17 +60,6 @@ function exists(dev) {
return stat(`/sys/class/net/${dev}`) != null; return stat(`/sys/class/net/${dev}`) != null;
} }
function cidr_of(a) {
let m = match(a ?? '', /^([0-9.]+)\/([0-9]+)$/);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = +m[2];
if (ip == null || prefix < 8 || prefix > 30)
return null;
let size = 1 << (32 - prefix);
return { ip, prefix, size, net: ip - ip % size };
}
/* ---------- facts about the LAN ---------- */ /* ---------- facts about the LAN ---------- */
/** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */ /** DHCP pool, static leases and the DNS handed to LAN clients, for one netifd interface. */
@@ -158,12 +149,8 @@ function pick_transit(saved) {
push(busy, n); push(busy, n);
let free = (base) => { let free = (base) => {
for (let b in busy) { for (let b in busy) {
let c = match(b, /^([0-9.]+)(\/([0-9]+))?$/); let c = cidr_any(b);
if (!c) if (c && base < c.net + c.size && c.net < base + 4)
continue;
let ip = ip2int(c[1]), size = 1 << (32 - (c[3] != null ? +c[3] : 32));
let bn = ip - ip % size;
if (base < bn + size && bn < base + 4)
return false; return false;
} }
return true; return true;
@@ -201,9 +188,14 @@ function settings() {
return c.get_all('dawnline', 'settings') ?? {}; return c.get_all('dawnline', 'settings') ?? {};
} }
/** Servers that want "like a home device" (default on). */ /** Servers that want "like a home device" (default on) and run a core. */
function wanted(m) { function wanted(m) {
return filter(values(m.servers), (s) => s.private_key && s.enabled && s.lan_like); return filter(values(m.servers), (s) => length(core.tunnels(s)) && s.enabled && s.lan_like);
}
/** Every server's interface, for rules. */
function all_ifnames(m) {
return map(values(m.servers), (s) => s.ifname);
} }
/** /**
@@ -221,7 +213,7 @@ export function plan(m) {
return { error: 'No LAN detected.' }; return { error: 'No LAN detected.' };
if (d.kind != 'bridge') if (d.kind != 'bridge')
return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` }; return { error: `${dev} is not a bridge, so Dawnline cannot join the LAN as a device.` };
let lan = cidr_of(d.addrs[0]); let lan = parse_cidr(d.addrs[0]);
if (!lan) if (!lan)
return { error: `${dev} has no IPv4 address.` }; return { error: `${dev} has no IPv4 address.` };
let facts = dhcp_facts(d.logical, lan); let facts = dhcp_facts(d.logical, lan);
@@ -239,7 +231,8 @@ export function plan(m) {
let servers = []; let servers = [];
for (let srv in srvs) { for (let srv in srvs) {
let sn = net.server_net(srv, snap); let sn = net.server_net(srv, snap);
push(servers, { ifname: srv.ifname, subnet: srv.subnet, direct: net.collapse([ srv.subnet, ...sn.nets ]) }); for (let t in core.tunnels(srv))
push(servers, { ifname: t.ifname, subnet: t.subnet, direct: net.collapse([ t.subnet, ...sn.nets ]) });
} }
return { return {
dev, dev,
@@ -289,8 +282,9 @@ table inet dawnline {
function current_rules(ifnames) { function current_rules(ifnames) {
let out = []; let out = [];
try { try {
// Ours, plus ours left behind by a removed tunnel (its interface is gone).
for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? []) for (let r in json(sh_out('ip -j -4 rule show') || '[]') ?? [])
if (r.priority >= 5200 && r.priority < 5300 && r.iif && index(ifnames, r.iif) >= 0) if (r.priority >= 5200 && r.priority < 5300 && r.iif && (index(ifnames, r.iif) >= 0 || 'iif_detached' in r))
push(out, r); push(out, r);
} }
catch (e) {} catch (e) {}
@@ -299,6 +293,9 @@ function current_rules(ifnames) {
function rule_key(pref, iif, to, table) { 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}`; return `${pref} ${iif} ${to ?? 'all'} ${table}`;
} }
@@ -326,7 +323,9 @@ function tunnel_ifnames() {
let c = cursor(); let c = cursor();
c.load('dawnline'); c.load('dawnline');
let out = []; let out = [];
c.foreach('dawnline', 'server', (s) => push(out, s.ifname ?? s['.name'])); c.foreach('dawnline', 'server', (s) => {
push(out, s.ifname ?? s['.name']);
});
return out; return out;
} }
@@ -354,15 +353,17 @@ export function remove(ifnames) {
* last applied plan and only checks that links, bridge port and rules exist. * last applied plan and only checks that links, bridge port and rules exist.
*/ */
export function ensure(m, force) { export function ensure(m, force) {
let ifnames = map(values(m.servers), (s) => s.ifname); let ifnames = all_ifnames(m);
let p = plan(m); let p = plan(m);
if (p.off || p.error) { if (p.off || p.error) {
if (stat(STATE) || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames))) // Read before remove(), which deletes it: the error is logged once, not every tick.
let was = read_json(STATE, {});
if (was.plan || exists(TX_ROOT) || exists(LAN_ROOT) || length(current_rules(ifnames)))
remove(ifnames); remove(ifnames);
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
write_json(STATE, { error: p.error, off: !!p.off }, 0o644); write_json(STATE, { error: p.error, off: !!p.off }, 0o644);
if (p.error) if (p.error && p.error != was.error)
log(`like-home routing off: ${p.error}`); log('is off', 'error', p.error);
return p; return p;
} }
let last = read_json(STATE, {}); let last = read_json(STATE, {});
@@ -410,26 +411,35 @@ export function ensure(m, force) {
push(errs, ...run(sync_rules(p, ifnames))); push(errs, ...run(sync_rules(p, ifnames)));
if (length(errs)) { if (length(errs)) {
log(`like-home routing failed, using the direct path: ${errs[0]}`); if (read_json(STATE, {}).error != `Setup failed: ${errs[0]}`)
log('failed — internet goes out directly for now', 'error', errs[0]);
remove(ifnames); remove(ifnames);
write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644); write_json(STATE, { error: `Setup failed: ${errs[0]}` }, 0o644);
return { error: errs[0] }; return { error: errs[0] };
} }
// Keep the chosen LAN address stable across restarts.
let c = cursor();
c.load('dawnline');
if (c.get('dawnline', 'settings', 'lan_address') != p.address) {
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', 'settings', 'lan_address', p.address);
c.commit('dawnline');
system('chmod 600 /etc/config/dawnline');
}
ensure_dir(RUN_DIR); ensure_dir(RUN_DIR);
write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644); write_json(STATE, { applied: time(), plan: p, transit: p.transit }, 0o644);
log(`like-home routing: ${p.dev} as ${p.address}`); if (!last.applied || last.plan?.dev != p.dev || last.plan?.address != p.address)
log(`is on · traffic enters ${p.dev} as ${p.address}`, 'up');
else if (!healthy)
log(`was broken — set up again (${p.dev} as ${p.address})`, 'repair');
return p; return p;
}; };
/**
* Keep the chosen LAN address stable across restarts (settings.lan_address).
* Called by dawnline.apply once its own lock is released: the config lock is
* never taken inside it.
*/
export function remember(p) {
if (!p?.address || settings().lan_address == p.address)
return;
store.transact((c, m) => {
c.set('dawnline', 'settings', 'settings');
c.set('dawnline', 'settings', 'lan_address', p.address);
});
};
/** Last applied state for views and health checks. */ /** Last applied state for views and health checks. */
export function status() { export function status() {
let s = read_json(STATE, {}); let s = read_json(STATE, {});
@@ -450,33 +460,6 @@ export function client_dns() {
/* ---------- plain resolver for Home-only clients ---------- */ /* ---------- plain resolver for Home-only clients ---------- */
function wan_dns() {
let out = [];
let snap = net.snapshot();
let wan = snap.devices[snap.wan]?.logical;
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
if (!name)
continue;
try {
let st = json(sh_out(`ubus call network.interface.${name} status 2>/dev/null`) || 'null');
for (let a in st?.['dns-server'] ?? [])
if (match(a, /^[0-9.]+$/))
push(out, a);
}
catch (e) {}
}
return length(out) ? uniq(out) : FALLBACK_DNS;
}
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
function lan_domain(m) {
let c = cursor();
c.load('dhcp');
let d = null;
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
return uniq(filter([ d, m.settings.domain ], (x) => x));
}
/** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */ /** The DNS your LAN gets from DHCP (option 6), else the router on the LAN. */
export function lan_dns() { export function lan_dns() {
let st = status(); let st = status();
@@ -485,7 +468,10 @@ export function lan_dns() {
let snap = net.snapshot(); let snap = net.snapshot();
let d = snap.devices[snap.lan]; let d = snap.devices[snap.lan];
let a = d?.addrs?.[0]; let a = d?.addrs?.[0];
return a ? (dhcp_facts(d.logical, cidr_of(a))?.dns ?? split(a, '/')[0]) : null; if (!a)
return null;
let lan = parse_cidr(a);
return (lan ? dhcp_facts(d.logical, lan).dns : null) ?? split(a, '/')[0];
}; };
/** /**
@@ -494,62 +480,17 @@ export function lan_dns() {
*/ */
export function resolver_target() { export function resolver_target() {
let st = status(); let st = status();
return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: RESOLVER_PORT }; return st.active && st.transit ? { mode: 'ns', address: st.transit, port: 53 } : { mode: 'root', port: resolver.PORT };
}; };
/** /** Write the resolver config where it should run now; true when it changed (see dawnline.resolver). */
* Write the resolver config; returns true when it changed (the running
* instance is then restarted by procd's respawn after a kill). The first line
* tells /usr/libexec/dawnline/resolver where to run it.
*/
export function sync_resolver(m) { export function sync_resolver(m) {
ensure_dir('/var/etc'); return resolver.sync(m, resolver_target(), lan_dns());
let ifs = map(filter(values(m.servers), (s) => s.private_key), (s) => s.ifname);
let target = resolver_target();
let lan = lan_dns();
let lines = [
`# mode=${target.mode}`,
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
`port=${target.port}`,
'no-hosts',
'bogus-priv',
'cache-size=1000',
`pid-file=${RESOLVER_PID}`,
'user=dnsmasq',
'group=dnsmasq',
];
if (target.mode == 'ns') {
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
// Upstream from the transit address: forwarded through the router to the WAN.
for (let a in wan_dns())
push(lines, `server=${a}@${target.address}`);
}
else {
push(lines, 'bind-dynamic', ...map(ifs, (i) => `interface=${i}`), `resolv-file=${RESOLVER_RESOLV}`);
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
if ((readfile(RESOLVER_RESOLV) ?? '') != resolv) {
writefile(RESOLVER_RESOLV, resolv);
system(`chmod 644 ${RESOLVER_RESOLV}`);
}
}
if (lan)
for (let d in lan_domain(m))
push(lines, `server=/${d}/${lan}`);
let conf = join('\n', lines) + '\n';
if ((readfile(RESOLVER_CONF) ?? '') == conf)
return false;
writefile(RESOLVER_CONF, conf);
system(`chmod 644 ${RESOLVER_CONF}`);
let pid = trim(readfile(RESOLVER_PID) ?? '');
if (match(pid, /^[0-9]+$/))
system(`kill ${pid} 2>/dev/null`);
return true;
}; };
/** True when the resolver process is alive. */ /** True when the resolver process is alive. */
export function resolver_running() { export function resolver_running() {
let pid = trim(readfile(RESOLVER_PID) ?? ''); return resolver.running();
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
}; };
export const RESOLVER = { port: RESOLVER_PORT, conf: RESOLVER_CONF }; export const RESOLVER = { port: resolver.PORT, conf: resolver.CONF };
@@ -0,0 +1,104 @@
// Dawnline — one-time steps for routers set up by older versions. Each one
// checks first and writes nothing when there is nothing to do; dawnline.apply
// runs them before it takes its own lock (changes to /etc/config/dawnline go
// through dawnline.store and its config lock).
import { cursor } from 'uci';
import { stat, unlink } from 'fs';
import { q, slog } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as store from 'dawnline.store';
const LAN_CGI = '/www/cgi-bin/dawnline-portal';
const LAN_CGI_URL = '/cgi-bin/dawnline-portal';
/** Every personal code is a word code; older random ones are replaced (their links stop working). */
function word_codes() {
let old = (s) => s.code != null && !match(s.code, core.WORD_CODE);
let c = cursor();
c.load('dawnline');
let any = false;
c.foreach('dawnline', 'person', (s) => {
if (old(s))
any = true;
});
if (!any)
return;
store.transact((w, m) => {
w.foreach('dawnline', 'person', (s) => {
if (old(s)) {
w.set('dawnline', s['.name'], 'code', core.new_code());
w.delete('dawnline', s['.name'], 'words');
}
});
});
slog('dawnline', 'info', 'moved to word codes', null, 'Personal links');
}
/*
* Older versions answered on 443 at home through LuCI's web server (its error
* page ran the portal CGI). The portal now keeps its own port: remove that.
*/
export function uhttpd() {
let c = cursor();
c.load('uhttpd');
if (c.get('uhttpd', 'main', 'error_page') == LAN_CGI_URL) {
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')}`);
}
if (stat(LAN_CGI))
unlink(LAN_CGI);
// The old setting itself.
let d = cursor();
d.load('dawnline');
if (d.get('dawnline', 'settings', 'portal_443') != null)
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
};
/*
* Steps that cannot tell from the config whether they ran are recorded in
* `settings.migrated` (a list), so they run exactly once.
*/
function migrated(c, name) {
let done = c.get('dawnline', 'settings', 'migrated') ?? [];
return index(type(done) == 'array' ? done : [ done ], name) >= 0;
}
function mark_migrated(w, name) {
let done = w.get('dawnline', 'settings', 'migrated') ?? [];
w.set('dawnline', 'settings', 'migrated', [ ...(type(done) == 'array' ? done : [ done ]), name ]);
}
/*
* 1380 was every server's stored MTU before it became automatic (by device
* type and disguise). Once only: an admin may choose 1380 again on purpose.
*/
function auto_mtu() {
let c = cursor();
c.load('dawnline');
if (migrated(c, 'auto_mtu'))
return;
let any = false;
c.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
any = true;
});
store.transact((w, m) => {
w.foreach('dawnline', 'server', (s) => {
if (s.mtu == '1380')
w.delete('dawnline', s['.name'], 'mtu');
});
mark_migrated(w, 'auto_mtu');
});
if (any)
slog('dawnline', 'info', 'MTU is now automatic', null, 'Servers');
}
/** All of them, in order. */
export function run() {
word_codes();
uhttpd();
auto_mtu();
};
@@ -9,17 +9,22 @@
// lan_device extra interfaces that count as the home network (list) // lan_device extra interfaces that count as the home network (list)
// //
// Home access is enforced by destination: the networks routed out of the // Home access is enforced by destination: the networks routed out of the
// chosen interfaces form the nft `lan_nets` set, and the tunnel's firewall // chosen interfaces form the server's nft `home_<id>` set, and the tunnel's
// zone gets a forwarding to each of their zones. // firewall zone gets a forwarding to each of their zones.
import { readfile, readlink, lsdir, stat } from 'fs'; import { readfile, readlink, lsdir, stat } from 'fs';
import { cursor } from 'uci'; import { cursor } from 'uci';
import { sh_out, ip2int, int2ip, uniq } from 'dawnline.util'; import { sh_out, ip2int, int2ip, cidr_any, uniq } from 'dawnline.util';
const SYS = '/sys/class/net'; const SYS = '/sys/class/net';
/** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */ /** Links Dawnline creates itself (dawnline.loop); never offered as interfaces. */
export const INTERNAL = { transit: 'dlx0', lan: 'dll0' }; export const INTERNAL = { transit: 'dlx0', lan: 'dll0' };
const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ]; const VPN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc', 'pptp', 'l2tp', 'gre', 'gretap', 'vti', 'xfrm' ];
const VPN_NAMES = /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/;
// Never the WAN while another default route exists: VPN clients. (PPTP and
// L2TP stay eligible: some ISPs connect the WAN with them.)
const NOT_WAN_PROTOS = [ 'amneziawg', 'wireguard', 'openvpn', 'openconnect', 'vpnc' ];
const NOT_WAN_NAMES = /^(wg|awg|tun|tap|ovpn)/;
// Kernel placeholder devices that never carry a network on their own. // Kernel placeholder devices that never carry a network on their own.
const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/; const NOISE = /^(ifb|teql|sit|ip6tnl|gre|gretap|erspan|ip6gre|ip6gretap|ip_vti|ip6_vti|tunl|bond)[0-9]*$/;
const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ]; const PRIVATE = [ [ '10.0.0.0', 8 ], [ '172.16.0.0', 12 ], [ '192.168.0.0', 16 ], [ '100.64.0.0', 10 ] ];
@@ -48,16 +53,8 @@ function ubus_json(path, method) {
/** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */ /** "a.b.c.d[/len]" → { net, prefix, size } for any prefix 1-32; null for default or junk. */
function net_of(s) { function net_of(s) {
let m = match(s ?? '', /^([0-9.]+)(\/([0-9]+))?$/); let c = cidr_any(s);
if (!m) return c && c.prefix >= 1 ? c : null;
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
if (ip == null || prefix < 1 || prefix > 32)
return null;
let size = 1 << (32 - prefix);
if (prefix == 1)
size = 2147483648;
return { net: ip - ip % size, prefix, size };
} }
function net_str(n) { function net_str(n) {
@@ -107,12 +104,12 @@ export function snapshot(fresh) {
return cache; return cache;
// Networks reachable through each device (main table, IPv4). // Networks reachable through each device (main table, IPv4).
let routes = {}, wan_dev = null; let routes = {}, defaults = [];
for (let r in ip_json('-4 route show table main')) { for (let r in ip_json('-4 route show table main')) {
if (!r.dev) if (!r.dev)
continue; continue;
if (r.dst == 'default') { if (r.dst == 'default') {
wan_dev ??= r.dev; push(defaults, r);
continue; continue;
} }
push(routes[r.dev] ??= [], r.dst); push(routes[r.dev] ??= [], r.dst);
@@ -130,6 +127,19 @@ export function snapshot(fresh) {
if (dev && !logical[dev]) if (dev && !logical[dev])
logical[dev] = { name: i.interface, proto: i.proto, up: i.up }; logical[dev] = { name: i.interface, proto: i.proto, up: i.up };
} }
// The WAN: the default route with the lowest metric that does not go into
// a VPN client (its default route is not where the tunnels listen); only
// VPN routes: the lowest of them.
let vpn = (dev) => index(NOT_WAN_PROTOS, logical[dev]?.proto) >= 0 || match(dev, NOT_WAN_NAMES) != null;
let wan_dev = null, wan_metric = null, wan_vpn = true;
for (let r in defaults) {
let v = vpn(r.dev), metric = r.metric ?? 0;
if (wan_dev == null || (wan_vpn && !v) || (wan_vpn == v && metric < wan_metric)) {
wan_dev = r.dev;
wan_metric = metric;
wan_vpn = v;
}
}
let zone_by_net = {}, zone_by_dev = {}, zones = []; let zone_by_net = {}, zone_by_dev = {}, zones = [];
let fc = cursor(); let fc = cursor();
fc.load('firewall'); fc.load('firewall');
@@ -163,7 +173,7 @@ export function snapshot(fresh) {
let cat; let cat;
if (wifi) if (wifi)
cat = 'wifi'; cat = 'wifi';
else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, /^(wg|awg|tun|tap|ovpn|ipsec|vti|xfrm)/)) else if ((lg && index(VPN_PROTOS, lg.proto) >= 0) || kind == 65534 || ((flags & 0x10) && kind != 1) || match(dev, VPN_NAMES))
cat = 'vpn'; cat = 'vpn';
else if (kind == 1 || bridge) else if (kind == 1 || bridge)
cat = 'ethernet'; cat = 'ethernet';
@@ -238,7 +248,9 @@ export function server_net(srv, snap) {
if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master) if (dev == wan.dev || dev == srv.ifname || devs[dev]?.master)
continue; continue;
let d = devs[dev]; let d = devs[dev];
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? null, missing: !d }; // The detected LAN missing for a moment (bridge recreated) keeps its zone,
// so its forwardings are not removed meanwhile.
let h = { dev, auto: p[1], nets: d?.nets ?? [], zone: d?.zone ?? (p[1] ? srv.lan_zone : null), missing: !d };
push(home, h); push(home, h);
push(nets, ...h.nets); push(nets, ...h.nets);
if (h.zone) if (h.zone)
@@ -266,3 +278,28 @@ export function wan_address(srv, snap) {
let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0]; let a = snap.devices[server_net(srv, snap).wan.dev]?.addrs?.[0];
return a ? split(a, '/')[0] : null; return a ? split(a, '/')[0] : null;
}; };
/** Names of devices at home by address: DHCP leases, then static hosts. */
export function lan_names() {
let out = {};
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
let f = split(line, ' ');
if (length(f) >= 4 && f[3] != '*')
out[f[2]] = f[3];
}
let c = cursor();
c.foreach('dhcp', 'host', (h) => {
if (h.ip && h.name)
out[h.ip] ??= h.name;
});
return out;
};
/** 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) ?? [])
if (names[ip[0]])
(out ??= {})[ip[0]] = names[ip[0]];
return out;
};
@@ -0,0 +1,134 @@
// Dawnline — netifd: one AmneziaWG interface per server, named after its
// ifname and marked `_dawnline` = server id. Only interfaces Dawnline created
// are changed or removed: a name already used by another interface (`lan`, a
// tunnel of your own, one from an imported config) is left alone and the
// server is reported instead.
import { cursor } from 'uci';
import { stat, unlink, writefile } from 'fs';
import { q, uci_put, uci_section, ack_config, iface_intent, ensure_dir, read_json, write_json, slog, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
// Set while AmneziaWG is missing and that was logged (once until it is back).
const NO_AWG = `${RUN_DIR}/netifd-no-awg`;
function log(who, msg, level, detail) {
slog('dawnline', level ?? 'info', msg, detail, who);
}
/** The server id that owns network.<ifname>: null when the section is free, '' when someone else's. */
export function owner(ifname, c) {
if (!c) {
c = cursor();
c.load('network');
}
if (c.get('network', ifname) == null)
return null;
return c.get('network', ifname, '_dawnline') ?? '';
};
/** Bring network config in line with the servers; true when it changed. */
export function sync(m) {
let c = cursor();
c.load('network');
let changed = false, touched = [], want = {};
// Servers whose interface can't be set up (core.BLOCKED), each logged once while it lasts.
let was = read_json(core.BLOCKED, {}), blocked = {};
let block = (srv, msg, detail) => {
blocked[srv.id] = msg;
// The rest of this apply works from the same model: no tunnel for it there either.
srv.blocked = msg;
if (was[srv.id] != msg)
log(srv.name, msg, 'error', detail);
};
// Without amneziawg-tools there is no protocol script: changing or bringing
// up an interface would only stop a tunnel that is still running.
let tools = awg.state().tools;
if (tools && stat(NO_AWG))
unlink(NO_AWG);
else if (!tools && length(filter(values(m.servers), (s) => s.private_key)) && !stat(NO_AWG)) {
log('AmneziaWG', "isn't installed: tunnels were left as they are", 'error', 'Install it in Dawnline → Components.');
ensure_dir(RUN_DIR);
writefile(NO_AWG, `${time()}`);
}
for (let id, srv in m.servers) {
if (!srv.private_key)
continue;
let ifn = srv.ifname;
if (!core.valid_ifname(ifn)) {
block(srv, `has an invalid interface name "${ifn}"`, 'Interface name: 1-12 lowercase letters, digits or _.');
continue;
}
let own = owner(ifn, c);
if (own != null && own != id) {
block(srv, `can't use the network interface ${ifn}: it exists and isn't Dawnline's`,
'Dawnline never changes interfaces it did not create. Choose another interface name for this server.');
continue;
}
// 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;
if (why) {
block(srv, `is kept down: ${why}`, 'Install that AmneziaWG build in Dawnline → Components, or switch the disguise on the Server page.');
continue;
}
delete srv.blocked;
want[ifn] = true;
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))
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);
// For the log once the server is gone.
set('_dawnline_name', srv.name);
if (mine) {
changed = true;
push(touched, ifn);
// The hotplug log says why the tunnel goes down (not a failure).
iface_intent(ifn, srv.enabled ? 'settings' : 'off', srv.name);
}
}
if (sprintf('%J', blocked) != sprintf('%J', was)) {
ensure_dir(RUN_DIR);
write_json(core.BLOCKED, blocked, 0o644);
}
// Remove interfaces Dawnline created for servers that no longer exist.
let stale = [];
c.foreach('network', 'interface', (s) => {
if (s._dawnline && !want[s['.name']])
push(stale, s['.name']);
});
for (let ifn in stale) {
iface_intent(ifn, 'removed', c.get('network', ifn, '_dawnline_name') ?? ifn);
system(`ifdown ${q(ifn)} 2>/dev/null`);
c.delete('network', ifn);
changed = true;
}
if (changed) {
c.commit('network');
ack_config([ 'network' ]);
system('ubus call network reload');
for (let ifn in touched)
if (m.servers[c.get('network', ifn, '_dawnline')]?.enabled)
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;
};
@@ -0,0 +1,264 @@
// Dawnline — the nft table `inet dawnline`: each person's access, enforced
// on the tunnel interfaces before anything else on the router sees the
// traffic, and where tunnel DNS goes. Its shape follows the servers and their
// home networks (rebuild); who is in which set follows people's state and
// 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 * 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' ];
/** 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' ];
function ip4(a) {
return ip2int(a ?? '') != null;
}
/** Per-person runtime membership: which tunnel addresses may reach what. */
export function access_sets(m, usage, states) {
// 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);
// svc_ok: device . service . port; svc_host: device . service with no ports (all of them).
let sets = {};
for (let k in SETS)
sets[k] = [];
let snap = net.snapshot();
let homes = {}, groups = {};
for (let id, d in m.devices) {
let p = m.people[d.person];
// Off: paused, ended, over quota or out of hours. Addresses go into nft as they are: IPv4 only.
if (!p || d.disabled || !ip4(d.address) || states[p.id] != 'active')
continue;
// Home names: the plain resolver (their internet does not use the tunnel).
if (p.access == 'lan' && p.dns_mode == 'home')
push(sets.dns_real, d.address);
if (p.access == 'internet' || p.access == 'both')
push(sets.inet_ok, d.address);
if (p.access == 'both' || (p.access == 'lan' && !length(p.services))) {
push(sets.lan_ok, d.address);
let srv = m.servers[p.server];
let h = homes[p.id] ??= srv ? core.person_home(srv, p, snap) : { all: true, nets: [] };
if (h.all)
push(sets.lan_all, d.address);
else
for (let n in h.nets)
push(sets.lan_part, `${d.address} . ${n}`);
// Who this device may reach directly: its circle, or at least its owner's devices.
if (srv?.mesh == 'circles') {
let ci = core.person_circle(m, p);
push(groups[ci ? `c:${ci.id}` : `p:${p.id}`] ??= [], d.address);
}
}
else if (p.access == 'lan')
for (let sid in p.services) {
let s = m.services[sid];
if (!s || !ip4(s.address))
continue;
if (!length(s.ports))
push(sets.svc_host, `${d.address} . ${s.address}`);
for (let port in s.ports)
if (match(port, /^[0-9]+$/))
push(sets.svc_ok, `${d.address} . ${s.address} . ${port}`);
}
}
for (let g, addrs in groups)
for (let a in addrs)
for (let b in addrs)
if (a != b)
push(sets.mesh_pairs, `${a} . ${b}`);
return sets;
};
// Duplicate members (two devices with one address) would make the whole load fail.
function set_elems(arr) {
arr = uniq(arr);
return length(arr) ? `elements = { ${join(', ', arr)} }` : '';
}
/** The portal's TCP ports people may reach through the tunnel (never SSH, DNS or LuCI, whatever is stored). */
function portal_ports(m) {
if (!m.settings.portal_enabled)
return [];
let ok = (p) => p >= 1 && p <= 65535 && index([ 22, 53, 80, 443 ], p) < 0;
let ports = filter([ m.settings.portal_port ], ok);
if (core.portal_http(m) && ok(core.portal_http_port(m)))
push(ports, core.portal_http_port(m));
return ports;
}
function table(m, sets) {
let ifs = [], tun = [];
let dns_addr = loop.client_dns();
if (!ip4(dns_addr))
dns_addr = null;
let rt = loop.resolver_target();
let snap = net.snapshot();
// 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 = {};
for (let id, srv in m.servers) {
// Only valid interface names reach here (core.tunnels): they are written into the rules as strings.
let tns = core.tunnels(srv);
for (let t in tns) {
push(ifs, `"${t.ifname}"`);
push(tun, t.subnet);
}
if (length(tns))
homes[id] = net.collapse(net.server_net(srv, snap).nets);
}
tun = net.collapse(tun);
let t = [];
push(t, 'table inet dawnline {');
for (let id, nets in homes)
push(t, ` set home_${id} { type ipv4_addr; flags interval; auto-merge; ${set_elems(nets)} }`);
// Tunnel subnets are never "home", even inside a wider route to the LAN.
push(t, ` set tun_nets { type ipv4_addr; flags interval; auto-merge; ${set_elems(tun)} }`);
push(t, ` set lan_ok { type ipv4_addr; ${set_elems(sets.lan_ok)} }`);
push(t, ` set lan_all { type ipv4_addr; ${set_elems(sets.lan_all)} }`);
push(t, ` set lan_part { type ipv4_addr . ipv4_addr; flags interval; ${set_elems(sets.lan_part)} }`);
push(t, ` set mesh_pairs { type ipv4_addr . ipv4_addr; ${set_elems(sets.mesh_pairs)} }`);
push(t, ` set inet_ok { type ipv4_addr; ${set_elems(sets.inet_ok)} }`);
push(t, ` set svc_ok { type ipv4_addr . ipv4_addr . inet_service; ${set_elems(sets.svc_ok)} }`);
push(t, ` set svc_host { type ipv4_addr . ipv4_addr; ${set_elems(sets.svc_host)} }`);
push(t, ` set dns_real { type ipv4_addr; ${set_elems(sets.dns_real)} }`);
push(t, ' chain pre {');
// Ahead of mangle-priority hooks (transparent proxies mark at -150).
push(t, ' type filter hook prerouting priority -160; policy accept;');
if (length(ifs))
push(t, ` iifname { ${join(', ', ifs)} } jump guard`);
push(t, ' }');
push(t, ' chain guard {');
push(t, ' meta nfproto ipv6 drop');
// Every packet is judged by the rules below, not only the first of a
// connection: a change of access cuts open connections too, instead of
// letting a session or a long UDP flow run on for days. Only what has no
// rule of its own passes on its connection: errors and the like, answers
// to the admin's port forwards, and the router's own pings.
push(t, ' ct state related accept');
push(t, ' ct status dnat accept');
push(t, ' icmp type { echo-request, echo-reply } fib daddr type local accept');
push(t, ' fib daddr type local meta l4proto { tcp, udp } th dport 53 accept');
let pp = portal_ports(m);
if (length(pp))
// Their own portal, also with the VPN on (the address may be this router's).
push(t, ` fib daddr type local tcp dport { ${join(', ', pp)} } accept`);
// The router itself is part of home: for everyone with all of it, and for
// people limited to some networks only on the addresses in those.
push(t, ' fib daddr type local ip saddr @lan_all accept');
push(t, ' fib daddr type local ip saddr . ip daddr @lan_part accept');
push(t, ' fib daddr type local counter drop');
if (dns_addr)
// DNS through the netns (it forwards to the LAN's DNS), for everyone.
push(t, ` ip daddr ${dns_addr} meta l4proto { tcp, udp } th dport 53 accept`);
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` iifname "${tn.ifname}" ip daddr @home_${id} ip daddr != @tun_nets ip saddr @lan_all accept`);
push(t, ' ip saddr . ip daddr @lan_part ip daddr != @tun_nets accept');
// Devices with home access are part of home: they reach each other, where the
// server allows it (everyone, or within circles). Within one server: the
// firewall has no forwarding between different servers' zones.
for (let id, srv in m.servers)
for (let tn in core.tunnels(srv))
if (srv.mesh == 'all')
push(t, ` iifname "${tn.ifname}" ip saddr @lan_ok ip daddr @lan_ok accept`);
else if (srv.mesh == 'circles')
push(t, ` iifname "${tn.ifname}" ip saddr . ip daddr @mesh_pairs accept`);
push(t, ' meta l4proto { tcp, udp } ip saddr . ip daddr . th dport @svc_ok accept');
push(t, ' ip saddr . ip daddr @svc_host accept');
push(t, ` ip daddr { ${join(', ', PRIVATE4)} } counter drop`);
push(t, ' ip saddr @inet_ok accept');
push(t, ' counter drop');
push(t, ' }');
// The other way: fw4 lets the server's home zones reach the tunnel; here
// only connections from its home networks to people with home access pass
// (paused, ended and internet-only people are not reachable). The admin's
// own port forwards (DNAT) stay with fw4.
push(t, ' chain inbound {');
push(t, ' type filter hook forward priority filter - 5; policy accept;');
if (length(ifs))
push(t, ` oifname { ${join(', ', ifs)} } iifname != { ${join(', ', ifs)} } ct state new jump to_device`);
push(t, ' }');
push(t, ' chain to_device {');
push(t, ' meta nfproto ipv6 drop');
push(t, ' ct status dnat accept');
for (let id, nets in homes)
for (let tn in core.tunnels(m.servers[id]))
push(t, ` oifname "${tn.ifname}" ip saddr @home_${id} ip saddr != @tun_nets ip daddr @lan_all accept`);
push(t, ' ip daddr . ip saddr @lan_part ip saddr != @tun_nets accept');
push(t, ' counter reject with icmpx admin-prohibited');
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();
if (!ip4(lan_dns))
lan_dns = null;
push(t, ' chain dns {');
push(t, ' type nat hook prerouting priority dstnat - 5; policy accept;');
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}`);
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.
let target = srv.lan_like && dns_addr ? `dnat ip to ${dns_addr}:53` : lan_dns ? `dnat ip to ${lan_dns}:53` : to_resolver;
push(t, ` iifname "${tn.ifname}" ip daddr ${tn.address} meta l4proto { tcp, udp } th dport 53 ${target}`);
}
push(t, ' }');
push(t, '}');
return join('\n', t) + '\n';
}
/** Run an nft script (one transaction); null when it loaded, else what nft said. */
export function load(script) {
ensure_dir(RUN_DIR);
// A file of its own: two writers must never load each other's script.
let f = `${RUN_DIR}/nft.${rand_hex(4)}.rules`;
if (!write_file(f, script))
return `couldn't write ${f}`;
let r = sh(`nft -f ${f}`);
unlink(f);
if (r.code == 0)
return null;
// Without the random file name, so the same failure reads the same every time.
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);
};
/** 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));
};
/**
* Replace the members of every runtime set at once; null or the error. Fails
* as a whole when the table or one of its sets is missing (not loaded yet,
* or an older shape): the caller then rebuilds.
*/
export function update(sets) {
let s = '';
for (let name in SETS) {
let members = uniq(sets[name]);
s += `flush set inet dawnline ${name}\n`;
if (length(members))
s += `add element inet dawnline ${name} { ${join(', ', members)} }\n`;
}
return load(s);
};
/** Is the table loaded (watchdog). */
export function present() {
return system('nft list table inet dawnline >/dev/null 2>&1') == 0;
};
export function remove() {
system('nft delete table inet dawnline 2>/dev/null');
};
@@ -1,660 +0,0 @@
// Dawnline — operations: health checks (with fixes), backups, export/import.
import { readfile, writefile, stat, unlink, lsdir } from 'fs';
import { cursor } from 'uci';
import {
q, sh, sh_out, ensure_dir, read_json, write_json, write_file, parse_cidr, cidr_overlaps, cidr_str,
ip2int, in_cidr, file_exists, valid_host, cloudflare_ip, DATA_DIR, RUN_DIR, VERSION
} from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop';
import * as net from 'dawnline.net';
const BACKUP_DIR = `${DATA_DIR}/backups`;
const KEEP_BACKUPS = 10;
/**
* Packages a feature needs that are missing, by feature: https (the portal: openssl-util and any
* TLS module for uhttpd), acme (Let's Encrypt certificates), home (the home-like link). Checked by
* files, so it is cheap enough for every page load.
*/
export function needs() {
let tls = false;
for (let d in [ '/lib', '/usr/lib' ])
for (let f in lsdir(d) ?? [])
if (substr(f, 0, 16) == 'libustream-ssl.s')
tls = true;
let kver = trim(readfile('/proc/sys/kernel/osrelease') ?? '');
let veth = stat('/sys/module/veth') != null || file_exists(`/lib/modules/${kver}/veth.ko`);
let miss = (list) => map(filter(list, (x) => !x[0]), (x) => x[1]);
return {
https: miss([ [ file_exists('/usr/bin/openssl'), 'openssl-util' ], [ tls, 'libustream-openssl' ] ]),
acme: miss([ [ file_exists('/usr/lib/acme/client/acme.sh'), 'acme' ], [ file_exists('/usr/lib/acme/client/dnsapi/dns_cf.sh'), 'acme-acmesh-dnsapi' ],
[ file_exists('/www/luci-static/resources/view/acme.js'), 'luci-app-acme' ] ]),
home: miss([ [ file_exists('/usr/libexec/ip-full'), 'ip-full' ], [ veth, 'kmod-veth' ] ]),
};
};
/** ACME certificates on the router and the names each covers. */
function acme_certs() {
let out = [];
for (let f in sort(lsdir('/etc/ssl/acme') ?? [])) {
let m = match(f, /^(.+)\.fullchain\.crt$/);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
if (!file_exists(k))
continue;
let sans = sh_out(`openssl x509 -in ${q(c)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
push(out, { cert: c, key: k, names: filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '') });
}
return out;
}
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
function acme_cert_for(host) {
for (let a in acme_certs())
for (let n in a.names)
if (n == host || (substr(n, 0, 2) == '*.' && index(host, '.') > 0 && substr(host, index(host, '.')) == substr(n, 1)))
return a;
return null;
}
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
export function portal_cert(s) {
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
if (s.portal_host) {
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
let c = `${base}.fullchain.crt`, k = `${base}.key`;
if (file_exists(c) && file_exists(k))
return { cert: c, key: k, self_signed: false };
}
// An ACME certificate issued for several names, the portal's among them.
let a = acme_cert_for(s.portal_host);
if (a)
return { cert: a.cert, key: a.key, self_signed: false };
}
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
if (!file_exists(c) || !file_exists(k)) {
ensure_dir(DATA_DIR, 0o700);
let cn = s.portal_host || 'dawnline';
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
system(`chmod 600 ${k}`);
}
return { cert: c, key: k, self_signed: true };
};
/* ---------- health ---------- */
function check(id, title, status, detail, fix) {
return { id, title, status, detail: detail ?? '', fix: fix ?? null };
}
function udp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/udp', '/proc/net/udp6' ])
if (index(readfile(f) ?? '', hex) >= 0)
return true;
return false;
}
function tcp_listening(port) {
let hex = sprintf(':%04X ', port);
for (let f in [ '/proc/net/tcp', '/proc/net/tcp6' ])
for (let line in split(readfile(f) ?? '', '\n'))
// state 0A = LISTEN
if (index(line, hex) > 0 && match(line, / 0A /))
return true;
return false;
}
/** Processes other than our portal listening on a TCP port: [ "name" ]. */
export function tcp_port_owners(port) {
let out = sh_out(`netstat -lntp 2>/dev/null | awk '$4 ~ /:${+port}$/ {print $7}'`) ?? '';
let owners = [];
for (let o in split(out, '\n')) {
let name = split(o, '/')[1];
if (!name || index(owners, name) >= 0)
continue;
// Our own portal runs as a dedicated uhttpd instance.
let pid = +split(o, '/')[0];
let cmd = readfile(`/proc/${pid}/cmdline`) ?? '';
if (index(cmd, '/usr/share/dawnline/portal') >= 0)
continue;
push(owners, name);
}
return owners;
};
function resolve(host) {
if (ip2int(host) != null)
return [ host ];
// Public resolvers first: local DNS often rewrites the router's own name
// to its LAN address (split horizon).
for (let srv in [ '1.1.1.1', '8.8.8.8', '127.0.0.1' ]) {
let out = sh_out(`timeout 5 nslookup ${q(host)} ${srv} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}'`);
let ips = out ? filter(split(out, '\n'), (x) => ip2int(x) != null) : [];
if (length(ips))
return ips;
}
return [];
}
function wan_ipv4(zone) {
let st = live.iface_status(zone == 'wan' ? 'wan' : zone);
return st?.['ipv4-address']?.[0]?.address;
}
/** The router's public IPv4 (the first server's WAN, else the wan interface). */
function router_wan(m) {
for (let id, srv in m.servers)
if (srv.private_key) {
let a = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
if (a)
return a;
}
return wan_ipv4('wan');
}
/*
* Addresses the portal could use in links, found on the router: names in ACME
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
* Each says where it points and whether a certificate covers it.
*/
export function portal_candidates(m) {
let wan = router_wan(m);
let names = [];
let add = (h) => {
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
push(names, h);
};
for (let a in acme_certs())
for (let n in a.names)
add(n);
for (let id, srv in m.servers)
add(srv.endpoint);
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (sv) => {
if (sv.enabled != '0') {
add(sv.lookup_host);
add(sv.domain);
}
});
for (let h in core.portal_hosts(m))
add(h);
let out = [];
for (let h in names) {
let ips = resolve(h);
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: acme_cert_for(h) != null });
}
if (wan)
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
for (let ph in core.portal_hosts(m))
if (ip2int(ph) != null && ph != wan)
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
// Best first: here with a certificate, then here, then the rest.
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
return sort(out, (a, b) => score(b) - score(a));
};
function service_running(name, instance) {
let s = sh_out(`ubus call service list '{"name":"${name}"}' 2>/dev/null`);
if (!s)
return false;
try {
let j = json(s);
let inst = j?.[name]?.instances?.[instance];
return !!inst?.running;
}
catch (e) {
return false;
}
}
function other_subnets(srv_id) {
let out = [];
let st = sh_out('ubus call network.interface dump 2>/dev/null');
let d = st ? json(st) : null;
let ours = {};
let m = core.load();
for (let id, s in m.servers)
ours[s.ifname] = id;
for (let i in d?.interface ?? []) {
if (srv_id != null && ours[i.interface] == srv_id)
continue;
for (let a in i['ipv4-address'] ?? [])
push(out, { iface: i.interface, cidr: `${a.address}/${a.mask}` });
}
return out;
}
export function used_subnets(except_srv) {
return map(other_subnets(except_srv), (x) => x.cidr);
};
/**
* Run all checks. Each result: { id, title, status: ok|warn|error|skip, detail, fix }.
* `fix` names an action accepted by fix().
*/
/*
* Policy rules that send the router's own (marked) traffic into a local table,
* the way transparent proxies capture it: "pref 1000 fwmark 0x1 → table 100".
*/
function proxy_diverts() {
let out = [];
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
let mm = match(line, /^(\d+):.*fwmark (\S+).* lookup (\S+)/);
if (!mm || +mm[1] >= 32766)
continue;
if (match(sh_out(`ip -4 route show table ${mm[3]} 2>/dev/null`) ?? '', /(^|\n)local default/))
push(out, `pref ${mm[1]} fwmark ${mm[2]} → table ${mm[3]}`);
}
return out;
}
/** Our "answers leave by main" rule for this port (see apply.sync_reply_routes). */
function reply_rule(proto, port) {
return index(sh_out('ip -4 rule show priority 90 2>/dev/null') ?? '', `ipproto ${proto} sport ${+port} lookup main`) >= 0;
}
function reply_check(id, title, proto, port, diverts) {
let ok = reply_rule(proto, port);
let via = length(diverts) ? ` A proxy on the router diverts its own traffic (${join(', ', diverts)}); these answers skip it.` : '';
return check(id, title, ok ? 'ok' : (length(diverts) ? 'error' : 'warn'),
ok ? `Answers from ${uc(proto)} ${port} go straight out.${via}`
: length(diverts) ? `Answers from ${uc(proto)} ${port} can be swallowed by a proxy on the router (${join(', ', diverts)}): clients get no reply.`
: `The rule that keeps answers from ${uc(proto)} ${port} out of proxies is missing.`,
ok ? null : 'apply');
}
export function health(m) {
let diverts = proxy_diverts();
m ??= core.load();
let out = [];
let dmp = live.dump();
let kmod = file_exists('/sys/module/amneziawg');
let tools = file_exists('/usr/bin/awg');
push(out, check('awg', 'AmneziaWG installed', kmod && tools ? 'ok' : 'error',
kmod && tools ? 'Kernel module and awg tool present.' :
(!tools ? 'amneziawg-tools is missing.' : 'The kmod-amneziawg module is not loaded.'), kmod && tools ? null : 'updates'));
let y = localtime().year;
push(out, check('clock', 'Clock is set', y >= 2025 ? 'ok' : 'error',
y >= 2025 ? 'End dates and quotas use the router clock.' : 'The router clock looks wrong; end dates will misbehave. Check NTP.'));
push(out, check('agent', 'Background agent running', service_running('dawnline', 'agent') ? 'ok' : 'error',
'Counts traffic and enforces end dates and quotas.', service_running('dawnline', 'agent') ? null : 'restart'));
if (!length(m.servers)) {
push(out, check('server', 'Server configured', 'warn', 'Run the setup wizard on the Server tab.'));
return out;
}
let nft_ok = system('nft list table inet dawnline >/dev/null 2>&1') == 0;
push(out, check('nft', 'Access rules loaded', nft_ok ? 'ok' : 'error',
nft_ok ? 'Table inet dawnline enforces who may reach LAN and the internet.' : 'Table inet dawnline is missing: access is not enforced.',
nft_ok ? null : 'apply'));
let fwc = cursor();
fwc.load('firewall');
for (let id, srv in m.servers) {
let label = length(m.servers) > 1 ? ` (${srv.name})` : '';
if (!srv.enabled) {
push(out, check(`srv_${id}`, `Server${label}`, 'skip', 'Server is disabled.'));
continue;
}
let st = live.iface_status(srv.ifname);
let up = !!st?.up;
push(out, check(`up_${id}`, `Tunnel interface up${label}`, up ? 'ok' : 'error',
up ? `${srv.ifname} is up, listening on UDP ${srv.port}.` :
(st ? `${srv.ifname} is down${st.errors ? ': ' + join(', ', map(st.errors, (e) => e.code)) : ''}.` : `${srv.ifname} does not exist.`),
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
if (up) {
let expected = 0;
let states = apply.states_for(m, core.load_usage());
for (let did, d in m.devices)
if (m.people[d.person]?.server == id && !d.disabled && states[d.person] == 'active')
expected++;
let actual = 0;
for (let k, p in dmp.peers)
if (p.ifname == srv.ifname)
actual++;
push(out, check(`peers_${id}`, `Devices loaded${label}`, expected == actual ? 'ok' : 'warn',
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
}
let rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
push(out, check(`fw_${id}`, `Firewall${label}`, rule && zone ? 'ok' : 'error',
rule && zone ? `Zone ${srv.ifname} and the WAN rule for UDP ${srv.port} exist.` : 'Firewall zone or WAN rule is missing.',
rule && zone ? null : 'apply'));
push(out, reply_check(`reply_${id}`, `Answers reach clients${label}`, 'udp', srv.port, diverts));
// Port collisions with other tunnels.
let clash = [];
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s['.name'] != srv.ifname && (s.proto == 'amneziawg' || s.proto == 'wireguard') && +s.listen_port == srv.port)
push(clash, s['.name']);
});
if (length(clash))
push(out, check(`port_${id}`, `Port is free${label}`, 'error', `UDP ${srv.port} is also used by ${join(', ', clash)}.`));
let overlaps = [];
let sc = parse_cidr(srv.subnet);
for (let o in other_subnets(id)) {
let oc = parse_cidr(o.cidr);
if (sc && oc && cidr_overlaps(sc, oc))
push(overlaps, `${o.iface} (${o.cidr})`);
}
push(out, check(`subnet_${id}`, `Subnet is unique${label}`, length(overlaps) ? 'error' : 'ok',
length(overlaps) ? `${srv.subnet} overlaps ${join(', ', overlaps)}.` : `${srv.subnet} does not overlap other networks.`));
let host = core.endpoint_host(m, srv);
if (!host)
push(out, check(`ep_${id}`, `Public address${label}`, 'error', 'No endpoint hostname: clients will not know where to connect.'));
else {
let ips = resolve(host);
let wan = net.wan_address(srv) ?? wan_ipv4(srv.wan_zone);
let wc = wan ? ip2int(wan) : null;
let cgnat = wc != null && (in_cidr(wc, parse_cidr('100.64.0.0/10')) || in_cidr(wc, parse_cidr('10.0.0.0/8')) ||
in_cidr(wc, parse_cidr('172.16.0.0/12')) || in_cidr(wc, parse_cidr('192.168.0.0/16')));
let stv = 'ok', det;
if (!length(ips)) {
stv = 'error';
det = `${host} does not resolve.`;
}
else if (cgnat) {
stv = 'warn';
det = `WAN address ${wan} is private: forward UDP ${srv.port} on the upstream router, or clients cannot connect.`;
}
else if (length(filter(ips, (a) => cloudflare_ip(a))))
det = `${host} → ${join(', ', ips)} (Cloudflare). The tunnel is UDP: it reaches the router only if this name is DNS-only there.`;
else if (wan && index(ips, wan) < 0) {
stv = 'warn';
det = `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`;
}
else
det = `${host} → ${join(', ', ips)}`;
push(out, check(`ep_${id}`, `Public address${label}`, stv, det));
}
if (srv.lan_like) {
let ls = loop.status();
let nh = needs().home;
push(out, check(`home_${id}`, `Internet like a home device${label}`, ls.active && ls.bridged ? 'ok' : 'warn',
ls.active && ls.bridged ? `Traffic enters ${ls.dev} as ${ls.address}, so it is handled like any device on your LAN.` :
length(nh) ? `Needs ${join(' and ', nh)}. Internet traffic leaves through WAN directly until then.` :
ls.active ? `The link is up but not attached to ${ls.dev}.` :
`${ls.error ?? 'Not set up.'} Internet traffic leaves through WAN directly.`,
ls.active && ls.bridged ? null : length(nh) ? 'install:home' : 'apply'));
}
}
if (length(filter(values(m.servers), (x) => x.private_key))) {
let rt = loop.resolver_target();
let ok = stat(loop.RESOLVER.conf) != null && loop.resolver_running();
push(out, check('resolver', 'DNS for Home-only devices', ok ? 'ok' : 'warn',
ok ? (rt.mode == 'ns' ? `Plain resolver running next to the LAN (${rt.address}).` : `Plain resolver on port ${rt.port}.`)
: 'The resolver is not running; Home-only devices cannot resolve names.', ok ? null : 'apply'));
}
let s = m.settings;
let need = needs();
if (s.portal_enabled && length(need.https))
push(out, check('portal', 'Personal portal', 'error',
`HTTPS isn't available on this router: install ${join(' and ', need.https)}.`, 'install:https'));
else if (s.portal_enabled) {
let owners = tcp_port_owners(s.portal_port);
let listening = tcp_listening(s.portal_port);
if (length(owners))
push(out, check('portal', 'Personal portal', 'error',
`TCP ${s.portal_port} is already used by ${join(', ', owners)}. Choose another port in Settings.`));
else
push(out, check('portal', 'Personal portal', listening ? 'ok' : 'error',
listening ? `Listening on TCP ${s.portal_port}.` : `Nothing listens on TCP ${s.portal_port}.`, listening ? null : 'restart'));
if (!s.portal_host)
push(out, check('portal_host', 'Portal address', 'error', 'Set the public hostname in Settings so links can be generated.'));
else {
let ips = resolve(s.portal_host), wan = router_wan(m);
let cf = filter(ips, (x) => cloudflare_ip(x));
push(out, check('portal_dns', 'Portal address points here', !length(ips) ? 'error' : length(cf) ? 'ok' : wan && index(ips, wan) < 0 ? 'warn' : 'ok',
!length(ips) ? `${s.portal_host} does not resolve.` :
length(cf) ? `${s.portal_host} goes through Cloudflare; in Russia such connections often stall after ~16 KB.` :
wan && index(ips, wan) < 0 ? `${s.portal_host} points at ${join(', ', ips)}, not this router (${wan}).` :
`${s.portal_host} → ${join(', ', ips)}${wan ? ' (this router)' : ''}.`));
}
push(out, reply_check('portal_reply', 'Portal answers reach visitors', 'tcp', s.portal_port, diverts));
if (core.portal_http(m)) {
let ipl = filter(core.portal_hosts(m), (h) => ip2int(h) != null);
push(out, check('portal_http', 'Plain HTTP links', 'warn',
`Links on ${join(', ', ipl)} use plain HTTP: the link and the VPN keys in configurations travel unencrypted.`));
}
// Links on 443: forwarded from outside, and the same link at home through LuCI's web server.
let pub = core.portal_public_port(m);
if (s.portal_port != 443) {
if (!s.portal_443)
push(out, check('portal_443', 'Links without a port', 'skip',
`Off: links use port ${s.portal_port}. Mobile networks often drop HTTPS on ports other than 443.`));
else if (pub != 443)
push(out, check('portal_443', 'Links without a port', 'warn',
`TCP 443 is already forwarded to another device, so links use port ${s.portal_port}.`));
else {
let fw = system(`nft list ruleset 2>/dev/null | grep -q 'Dawnline-Portal-443'`) == 0;
push(out, check('portal_443', 'Links without a port', fw ? 'ok' : 'error',
fw ? `From the internet TCP 443 reaches the portal only (LuCI stays closed there).` : 'The 443 forward to the portal is missing.',
fw ? null : 'apply'));
let uc_ = cursor();
uc_.load('uhttpd');
let ep = uc_.get('uhttpd', 'main', 'error_page');
let mine = ep == '/cgi-bin/dawnline-portal' && stat('/www/cgi-bin/dawnline-portal') != null;
push(out, check('portal_lan', 'Same link at home', mine ? 'ok' : ep ? 'warn' : 'error',
mine ? 'At home the link opens through LuCI\'s web server, which hands unknown paths to the portal.'
: ep ? `LuCI's web server already uses ${ep} for unknown paths, so at home links need :${s.portal_port}.`
: 'LuCI\'s web server does not hand portal links to the portal: at home they show Not found.',
mine || ep ? null : 'apply'));
}
}
let cert = portal_cert(s);
if (ip2int(s.portal_host) != null)
push(out, check('cert', 'Portal certificate', 'skip', 'The main address is an IP: its links use plain HTTP.'));
else {
let ok = system(`openssl x509 -checkend 1209600 -noout -in ${q(cert.cert)} >/dev/null 2>&1`) == 0;
let sans = cert.self_signed ? [] : split(replace(sh_out(`openssl x509 -in ${q(cert.cert)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '', /DNS:/g, ''), /[ \t\r\n]+/);
let covers = !s.portal_host || cert.self_signed || index(sans, s.portal_host) >= 0 ||
length(filter(sans, (n) => substr(n, 0, 2) == '*.' && substr(s.portal_host, index(s.portal_host, '.')) == substr(n, 1)));
push(out, check('cert', 'Portal certificate', cert.self_signed || !ok || !covers ? 'warn' : 'ok',
cert.self_signed ? `Using a self-signed certificate: browsers will show a warning.${length(need.acme) ? ' ACME can get a free Let’s Encrypt one.' : ''}` :
!covers ? `${cert.cert} does not cover ${s.portal_host} (it has ${join(', ', sans)}): browsers will warn.` :
ok ? `${cert.cert} covers ${s.portal_host} and is valid for more than 14 days.` : `${cert.cert} expires within 14 days.`));
}
}
return out;
};
export function fix(id) {
if (id == 'apply')
return apply.apply();
if (id == 'sync')
return apply.sync();
if (id == 'restart')
return { code: system('/etc/init.d/dawnline restart >/dev/null 2>&1') };
let m = match(id ?? '', /^ifup:([a-z][a-z0-9_]{0,11})$/);
if (m) {
system(`ifup ${q(m[1])}`);
return { ok: true };
}
die('Unknown fix.');
};
/* ---------- backups ---------- */
function backup_files() {
let out = [ '/etc/config/dawnline' ];
for (let f in [ 'usage.json', 'events.json' ])
if (file_exists(`${DATA_DIR}/${f}`))
push(out, `${DATA_DIR}/${f}`);
return out;
}
export function backup_list() {
let out = [];
for (let f in lsdir(BACKUP_DIR) ?? []) {
let mm = match(f, /^dawnline-([0-9]{8}-[0-9]{6})(-([a-z0-9-]+))?\.tar\.gz$/);
if (!mm)
continue;
let st = stat(`${BACKUP_DIR}/${f}`);
push(out, { name: f, created: st?.mtime ?? 0, size: st?.size ?? 0, reason: mm[3] ?? 'manual' });
}
return sort(out, (a, b) => b.created - a.created);
};
export function backup_create(reason) {
// Flush live counters first so the backup has current usage.
let u = read_json(`${RUN_DIR}/usage.json`, null);
if (u)
write_json(`${DATA_DIR}/usage.json`, u, 0o600);
live.persist_events();
ensure_dir(BACKUP_DIR, 0o700);
let t = localtime();
let tag = reason && match(reason, /^[a-z0-9-]{1,24}$/) ? `-${reason}` : '';
let name = sprintf('dawnline-%04d%02d%02d-%02d%02d%02d%s.tar.gz', t.year, t.mon, t.mday, t.hour, t.min, t.sec, tag);
let files = join(' ', map(backup_files(), (f) => q(substr(f, 1))));
let r = sh(`tar -czf ${q(BACKUP_DIR + '/' + name)} -C / ${files}`);
if (r.code != 0)
die(`Backup failed: ${trim(r.out)}`);
system(`chmod 600 ${q(BACKUP_DIR + '/' + name)}`);
let all = backup_list();
for (let i = KEEP_BACKUPS; i < length(all); i++)
unlink(`${BACKUP_DIR}/${all[i].name}`);
return name;
};
function backup_path(name) {
if (!match(name ?? '', /^dawnline-[0-9]{8}-[0-9]{6}(-[a-z0-9-]+)?\.tar\.gz$/))
die('Invalid backup name.');
let p = `${BACKUP_DIR}/${name}`;
if (!file_exists(p))
die('Backup not found.');
return p;
}
/** Validate an archive: only Dawnline's own files may be inside. */
function check_archive(path) {
let r = sh(`tar -tzf ${q(path)}`);
if (r.code != 0)
die('Not a valid backup archive.');
let allowed = { 'etc/config/dawnline': true };
let has_config = false;
for (let f in split(trim(r.out), '\n')) {
f = replace(f, /^\.?\//, '');
// The config plus Dawnline's own data files (older versions had more of them).
if (!allowed[f] && !match(f, /^etc\/dawnline\/[a-z0-9_-]+\.json$/))
die(`Unexpected file in backup: ${f}`);
if (f == 'etc/config/dawnline')
has_config = true;
}
if (!has_config)
die('Backup does not contain /etc/config/dawnline.');
}
export function backup_restore(name, path) {
path ??= backup_path(name);
check_archive(path);
backup_create('pre-restore');
let r = sh(`tar -xzf ${q(path)} -C /`);
if (r.code != 0)
die(`Restore failed: ${trim(r.out)}`);
system('chmod 600 /etc/config/dawnline');
// Live counters must follow the restored file.
unlink(`${RUN_DIR}/usage.json`);
unlink(`${RUN_DIR}/events.json`);
return apply.apply();
};
export function backup_delete(name) {
unlink(backup_path(name));
return true;
};
export function backup_read(name) {
return b64enc(readfile(backup_path(name)));
};
export function backup_upload(data_b64) {
let data = b64dec(data_b64 ?? '');
if (!data || length(data) > 4 * 1024 * 1024)
die('Upload is empty or too large.');
ensure_dir(RUN_DIR);
let tmp = `${RUN_DIR}/upload.tar.gz`;
write_file(tmp, data);
let res;
try {
res = backup_restore(null, tmp);
}
catch (e) {
unlink(tmp);
die(e.message);
}
unlink(tmp);
return res;
};
/* ---------- export / import (JSON) ---------- */
export function export_json() {
let c = cursor();
c.load('dawnline');
let sections = [];
c.foreach('dawnline', null, (s) => {
let o = { '.type': s['.type'], '.name': s['.name'] };
for (let k, v in s)
if (substr(k, 0, 1) != '.')
o[k] = v;
push(sections, o);
});
return { format: 'dawnline', version: VERSION, exported: time(), sections };
};
export function import_json(data) {
if (type(data) != 'object' || data.format != 'dawnline' || type(data.sections) != 'array')
die('Not a Dawnline export.');
let types = { settings: true, server: true, person: true, device: true, service: true };
for (let s in data.sections) {
if (!types[s['.type']] || !match(s['.name'] ?? '', /^[A-Za-z0-9_]{1,64}$/))
die(`Invalid section ${s['.name']}.`);
for (let k, v in s)
if (substr(k, 0, 1) != '.' && (!match(k, /^[a-z0-9_]{1,32}$/) || (type(v) != 'string' && type(v) != 'array')))
die(`Invalid option ${k}.`);
}
backup_create('pre-import');
let lines = [];
for (let s in data.sections) {
push(lines, `config ${s['.type']} '${s['.name']}'`);
for (let k, v in s) {
if (substr(k, 0, 1) == '.')
continue;
let esc = (x) => replace(`${x}`, "'", "'\\''");
if (type(v) == 'array')
for (let x in v)
push(lines, `\tlist ${k} '${esc(x)}'`);
else
push(lines, `\toption ${k} '${esc(v)}'`);
}
push(lines, '');
}
write_file('/etc/config/dawnline', join('\n', lines), 0o600);
return apply.apply();
};
@@ -0,0 +1,158 @@
// Dawnline — one interface over the router's package manager: opkg on
// OpenWrt 24.10, apk on 25.12. Commands that change packages take a log(line)
// callback, which gets their output line by line.
import { access, popen, stat } from 'fs';
import { q } from 'dawnline.util';
function run(cmd) {
let p = popen(cmd + ' 2>&1', 'r');
if (!p)
return { code: 127, out: '' };
let out = p.read('all') ?? '';
return { code: p.close(), out };
}
function logged(cmd, log) {
let r = run(cmd);
for (let line in split(trim(r.out), '\n'))
if (length(trim(line)))
log?.(` ${line}`);
return r;
}
export function is_apk() {
return access('/usr/bin/apk', 'x');
};
export function ext() {
return is_apk() ? 'apk' : 'ipk';
};
/** The installed version of a package, or null. */
export function version(name) {
let esc = replace(name, /[.+]/g, '\\$&');
if (is_apk()) {
let m = match(run(`apk list --installed ${q(name)}`).out, regexp(`^${esc}-([^ ]+) `));
return m ? m[1] : null;
}
// Libraries carry their ABI in the name (libustream-openssl20201210).
let re = regexp(`^${esc}([0-9]+)? - (.+)$`), found = null;
for (let line in split(run('opkg list-installed').out, '\n')) {
let m = match(trim(line), re);
if (m && (found == null || m[1] == null))
found = m;
}
return found ? trim(found[2]) : null;
};
/** 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];
};
/**
* Compare two package versions the way the package manager does (so -r10 is
* newer than -r9 and ~rc before the release): -1, 0 or 1; null when unknown.
*/
export function cmp(a, b) {
if (a == null || b == null)
return null;
if (a == b)
return 0;
if (is_apk()) {
let r = trim(run(`apk version -t ${q(a)} ${q(b)}`).out);
return r == '<' ? -1 : r == '>' ? 1 : r == '=' ? 0 : null;
}
if (run(`opkg compare-versions ${q(a)} '<<' ${q(b)}`).code == 0)
return -1;
if (run(`opkg compare-versions ${q(a)} '>>' ${q(b)}`).code == 0)
return 1;
return 0;
};
export function refresh(log) {
return logged(is_apk() ? 'apk update' : 'opkg update', log).code == 0;
};
/** Free space on the overlay in KB (null when unknown). */
function overlay_free_kb() {
let out = run('df -Pk /overlay 2>/dev/null || df -Pk / 2>/dev/null').out;
let m = match(out, /\n\S+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s/);
return m ? +m[1] : null;
}
/**
* Room for `files` (or `need_kb` from the feeds): the package manager
* unpacks before it removes, so a full flash leaves half an install behind.
* Dies with the numbers.
*/
function preflight(files, need_kb, log) {
let free = overlay_free_kb();
if (free == null)
return;
let need = need_kb ?? 512;
for (let f in files ?? [])
need += int(((stat(f)?.size ?? 0) * 3) / 1024);
if (free < need)
die(`Not enough free space on the router: ${int(free / 1024)} MB free, about ${int(need / 1024) + 1} MB needed. Remove old backups or packages first`);
log?.(` ${int(free / 1024)} MB free on the overlay`);
}
/** Package files (from a release): force also reinstalls the same version or goes back to an older one. */
export function install_files(files, force, log) {
preflight(files, 0, log);
let args = join(' ', map(files, q));
if (!is_apk())
return logged(`opkg install ${force ? '--force-reinstall --force-downgrade ' : ''}${args}`, log).code == 0;
// apk leaves an installed version alone, whatever the file: a reinstall
// that changed nothing is a failure, not a silent "done".
let marker = '/usr/share/ucode/dawnline/util.uc';
let before = force ? stat(marker)?.mtime : null;
let ok = logged(`apk add --allow-untrusted ${args}`, log).code == 0;
if (ok && force && before != null && stat(marker)?.mtime == before) {
log?.(' apk did not reinstall the version that is already installed');
die("apk doesn't reinstall an installed version. Install a different release, or run install.sh on the router");
}
return ok;
};
/** Packages by name from the feeds. */
export function add(names, log) {
preflight(null, 2048, log);
return logged(is_apk() ? `apk add ${join(' ', map(names, q))}` : `opkg install ${join(' ', map(names, q))}`, log).code == 0;
};
export function upgrade(names, log) {
preflight(null, 2048, log);
return logged(is_apk() ? `apk upgrade ${join(' ', map(names, q))}` : `opkg upgrade ${join(' ', map(names, q))}`, log).code == 0;
};
export function remove(names, log) {
return logged(is_apk() ? `apk del ${join(' ', map(names, q))}` : `opkg remove ${join(' ', map(names, q))}`, log).code == 0;
};
/** Installed packages with a newer version in the feeds: { name: latest }. */
export function upgradable() {
let up = {};
if (is_apk()) {
for (let line in split(run('apk version -l "<"').out, '\n')) {
// "name-version-rN < newer": the version is what follows the last dash
// before the release suffix (a name may hold digits, a version no dash).
let m = match(line, /^(\S+)-([^- ]+-r[0-9]+)\s+<\s+(\S+)/);
if (m)
up[m[1]] = m[3];
}
}
else
for (let line in split(run('opkg list-upgradable').out, '\n')) {
let m = match(line, /^(\S+) - (\S+) - (\S+)/);
if (m)
up[m[1]] = m[3];
}
return up;
};
@@ -0,0 +1,555 @@
// Dawnline — the personal portal.
//
// GET /<code> the app shell
// GET /<code>/assets/<file> its script, styles and fonts
// GET /<code>/api/state
// POST /<code>/api/devices { name, kind, public_key? }
// GET /<code>/api/devices/<id>/config
// POST /<code>/api/devices/<id> { action: rename|rotate|delete, name? }
//
// 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 —
// the root, a person's link, the API and the assets alike — so nothing tells
// a scanner there is a portal here. Wrong codes are rate-limited per client
// (blocked clients get the same 404 even with the right code): per IPv4
// address or IPv6 /64; behind Cloudflare per visitor (CF-Connecting-IP), with
// a higher ceiling for all Cloudflare visitors together.
// Regenerating the code in LuCI locks the old link out at once. POST bodies
// must be JSON from the same origin; Referrer-Policy keeps the code out of
// other sites' logs. The portal can only manage the person's own devices
// within their limits, and not those the admin turned off (dawnline.devices).
//
// Changes through a link are limited too (a link is not a terminal: a few
// dozen every quarter hour), and the configurations themselves (keys, the
// disguise) only go over HTTPS: a plain-HTTP link (an IP address in Settings)
// shows the page, but gets them from its HTTPS twin.
//
// handle() serves one request: `io` = { env, headers, read(n), write(s) }; the
// CGI script (cgi.uc) is its wrapper, behind the shell door www/cgi-bin/portal
// that answers anything not shaped like a link (its not_found() twin).
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 * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as schema from 'dawnline.schema';
import * as devices from 'dawnline.devices';
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 FAIL_LIMIT = 8;
const FAIL_WINDOW = 900;
// All Cloudflare visitors together (three-word codes can't be guessed anyway).
const SHARED_LIMIT = FAIL_LIMIT * 25;
const SHARED_KEY = 'cloudflare';
// Clients remembered at most (the oldest go first).
const RATE_MAX = 2000;
// Changes one link may make within FAIL_WINDOW (each one writes flash and syncs the tunnels).
const ACTION_LIMIT = 40;
const BODY_MAX = 8192;
// The early end of a request (a response was written).
const DONE = '__dawnline_done__';
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'X-Frame-Options': 'DENY',
'Cache-Control': 'no-store',
};
const NOT_READY = "Adding devices isn't available right now: the VPN server isn't ready. Ask whoever sent you this link.";
// States the admin stopped the person in: the portal only shows, it changes nothing.
const LOCKED = {
paused: 'Your access is paused by the admin.',
expired: 'Your access has ended. Ask the admin to extend it.',
};
function html_escape(s) {
return replace(`${s}`, /[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
/* ---------- answering ---------- */
function headers(r, status, extra) {
let h = `Status: ${status}\r\n`;
let all = { ...SECURITY_HEADERS, ...(extra ?? {}) };
// HSTS pins the whole name: only when the visitor is on the standard port.
if (r.hsts)
all['Strict-Transport-Security'] = 'max-age=31536000';
for (let k, v in all)
h += `${k}: ${v}\r\n`;
r.io.write(h + '\r\n');
}
function finish() {
die(DONE);
}
function send_json(r, status, obj) {
headers(r, status, { 'Content-Type': 'application/json' });
r.io.write(sprintf('%J', obj));
finish();
}
function fail(r, status, msg) {
send_json(r, status, { error: msg });
}
/**
* The one answer for anything without a valid code: a bare 404, or the redirect from Settings.
* Files always get the 404: a missing asset must not turn into someone's website.
*/
function not_found(r) {
let redirect = r.m.settings.portal_redirect;
let parts = split(r.path, '/');
let file = match(r.path, /^\/(luci-static|cgi-bin|ubus)(\/|$)/) || match(parts[length(parts) - 1], /\./);
if (redirect && !file) {
headers(r, '302 Found', { 'Location': redirect, 'Cache-Control': 'no-store', 'Content-Type': 'text/plain' });
r.io.write('Moved\n');
}
else {
headers(r, '404 Not Found', { 'Content-Type': 'text/plain' });
r.io.write('Not found\n');
}
finish();
}
/** The JSON object a POST carries ({} without a body). */
function body(r) {
let len = +(r.env.CONTENT_LENGTH ?? 0);
if (len <= 0)
return {};
if (len > BODY_MAX)
fail(r, '413 Payload Too Large', 'Request too large.');
let raw = '';
while (length(raw) < len) {
let chunk = r.io.read(len - length(raw));
if (chunk == null || chunk == '')
break;
raw += chunk;
}
try {
let j = json(raw);
return type(j) == 'object' ? j : {};
}
catch (e) {
fail(r, '400 Bad Request', 'Invalid JSON.');
}
}
/** Run a change; what it refuses becomes a 400 with its message. */
function guard(r, fn) {
try {
return fn();
}
catch (e) {
if (e.message == DONE)
die(DONE);
fail(r, '400 Bad Request', e.message);
}
}
/* ---------- rate limiting ---------- */
/** The rate-limit key of an address: an IPv4 address, or the /64 of an IPv6 one. */
function addr_key(a) {
if (schema.ipv4(a))
return a;
let g = schema.ipv6_groups(a);
if (!g)
return null;
// An IPv4 address seen through an IPv6 socket.
if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff)
return sprintf('%d.%d.%d.%d', g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255);
return sprintf('%x:%x:%x:%x::/64', g[0], g[1], g[2], g[3]);
}
/**
* The buckets a request counts against, [{ key, limit }]: its client, and
* behind Cloudflare (the only proxy whose CF-Connecting-IP is believed) also
* the bucket all Cloudflare visitors share.
*/
function buckets(env) {
let peer = env.REMOTE_ADDR ?? '';
if (!cloudflare_ip(peer))
return [ { key: addr_key(peer) ?? peer, limit: FAIL_LIMIT } ];
let out = [ { key: SHARED_KEY, limit: SHARED_LIMIT } ];
let visitor = addr_key(trim(env.HTTP_CF_CONNECTING_IP ?? ''));
if (visitor && !cloudflare_ip(visitor))
unshift(out, { key: visitor, limit: FAIL_LIMIT });
return out;
}
function rate_state() {
let st = read_json(RATE, {});
let now = time();
for (let k, v in st)
if (type(v) != 'object' || now - v.first > FAIL_WINDOW)
delete st[k];
return st;
}
function rate_blocked(r) {
let st = rate_state();
return length(filter(r.buckets, (b) => (st[b.key]?.count ?? 0) >= b.limit)) > 0;
}
function rate_fail(r) {
let l = lock('portal-rate');
let st = rate_state();
let now = time();
let hit = [];
for (let b in r.buckets) {
let v = st[b.key] ?? { first: now, count: 0 };
v.count++;
st[b.key] = v;
if (v.count == b.limit)
push(hit, b.key);
}
// Bounded: an attacker with many addresses cannot grow the file without end.
let all = keys(st);
if (length(all) > RATE_MAX) {
all = sort(all, (a, b) => st[a].first - st[b].first);
for (let i = 0; i < length(all) - RATE_MAX; i++)
delete st[all[i]];
}
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
for (let k in hit)
live.add_event({ type: 'portal_blocked', detail: k == SHARED_KEY ? 'all Cloudflare visitors' : k });
}
/** One more change through this link; refused beyond ACTION_LIMIT per window. */
function rate_action(r) {
let key = `act:${r.person.id}`;
let l = lock('portal-rate');
let st = rate_state();
let v = st[key] ?? { first: time(), count: 0 };
v.count++;
st[key] = v;
ensure_dir(RUN_DIR);
write_json(RATE, st, 0o600);
unlock(l);
if (v.count > ACTION_LIMIT)
fail(r, '429 Too Many Requests', 'Too many changes in a short time. Try again in a few minutes.');
}
/* ---------- pages ---------- */
/** 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.
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
let base = r.base, title = r.title;
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'; " +
"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="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}">
</head>
<body>
<div id="app" data-base="${html_escape(base)}" data-title="${html_escape(title)}"></div>
<script src="${base}/assets/portal.js${v}" defer></script>
</body>
</html>
`);
finish();
}
/** Script, styles, icon and fonts (kept outside the web root). */
function asset(r, name) {
let ext = match(name, /^[a-z0-9-]+\.(js|css|svg|woff2|png)$/)?.[1];
let data = 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' });
r.io.write(data);
finish();
}
/* ---------- the API ---------- */
/** The model again after a change. */
function reload(r) {
r.m = core.load();
r.person = r.m.people[r.person.id];
if (!r.person)
not_found(r);
}
/**
* The person's state for the page: a stop by the admin (pause, end of access)
* wins over their server being off, so they learn that their access is stopped.
*/
function person_state(m, p, usage) {
let st = core.person_state(m, p, usage);
if (st == 'server_off') {
let own = core.own_state(m, p, usage);
if (LOCKED[own])
return own;
}
return st;
}
/** Why the person can't change anything right now, or null. */
function locked(r) {
return LOCKED[person_state(r.m, r.person, core.load_usage())] ?? null;
}
/** Refuses a change (or a config) while the person is stopped. */
function need_open(r) {
let why = locked(r);
if (why)
fail(r, '403 Forbidden', why);
}
/** The same link over HTTPS (for a plain-HTTP visitor), or null when this is it. */
function https_url(r) {
if (r.https)
return null;
let host = r.host;
let h = match(host, /^\[/) ? match(host, /^(\[[^\]]*\])/)?.[1] : split(host, ':')[0];
let port = r.m.settings.portal_port;
return `https://${h}${port == 443 ? '' : `:${port}`}${r.base}`;
}
/**
* Keys and the disguise never travel in the clear: over plain HTTP a
* configuration is refused, and the answer names the HTTPS link to use.
*/
function need_https(r) {
let u = https_url(r);
if (u)
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u });
}
/** Everything the page shows. */
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));
v.state = person_state(m, person, usage);
let srv = m.servers[person.server];
// The device this page was opened from, when it came through the tunnel.
let here = null;
for (let id, d in m.devices)
if (d.person == person.id && d.address == r.peer)
here = id;
return {
title: r.title,
person: v,
here,
server: {
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
},
can_add: length(person.devices) < person.device_limit,
locked: LOCKED[v.state] != null,
// Over plain HTTP: where the configurations are (keys only travel encrypted).
https_url: https_url(r),
kinds: core.KINDS,
// The router's day: access ends and usage days follow its clock, not the browser's.
today: today(),
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
now: time(),
version: VERSION,
};
}
/** One of the person's own devices, or a 404. */
function own_device(r, id) {
let d = r.m.devices[id];
if (!d || d.person != r.person.id)
fail(r, '404 Not Found', 'Device not found.');
return d;
}
function api_state(r) {
send_json(r, '200 OK', state(r));
}
function api_add(r) {
need_open(r);
need_https(r);
let b = body(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 }));
reload(r);
send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
}
function api_config(r, id) {
let d = own_device(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));
}
/** POST /devices/<id> { action }: what each action does; the answer carries the new state. */
const ACTIONS = {
rename: (r, d, b) => {
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
return {};
},
rotate: (r, d, b) => {
need_https(r);
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
return { config };
},
'delete': (r, d, b) => {
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
return {};
},
};
function api_device(r, id) {
let d = own_device(r, id);
need_open(r);
let b = body(r);
let act = ACTIONS[b.action];
if (!act)
fail(r, '400 Bad Request', 'Unknown action.');
rate_action(r);
let res = act(r, d, b);
reload(r);
send_json(r, '200 OK', { ok: true, ...res, state: state(r) });
}
/** API routes: method, path under /<code>/api ('*' matches one segment, passed to run). */
const API = [
{ method: 'GET', path: [ 'state' ], run: api_state },
{ method: 'POST', path: [ 'devices' ], run: api_add },
{ method: 'GET', path: [ 'devices', '*', 'config' ], run: api_config },
{ method: 'POST', path: [ 'devices', '*' ], run: api_device },
];
/** The route for a request: { run, args } or null (routes take at most one '*'). */
function route(table, method, segs) {
for (let rt in table) {
if (rt.method != method || length(rt.path) != length(segs))
continue;
let args = [], ok = true;
for (let i = 0; i < length(segs) && ok; i++)
if (rt.path[i] == '*')
push(args, segs[i]);
else if (rt.path[i] != segs[i])
ok = false;
if (ok)
return { run: rt.run, args };
}
return null;
}
/* ---------- one request ---------- */
export function handle(io) {
let env = io.env ?? {};
// Header names arrive lower-case from uhttpd; CGI has only HTTP_* variables.
let hdr = {};
for (let k, v in io.headers ?? {})
hdr[lc(k)] = v;
let header = (name) => hdr[name] ?? env[`HTTP_${uc(replace(name, /-/g, '_'))}`];
let uri = env.REQUEST_URI ?? '/';
let qpos = index(uri, '?');
let path = qpos >= 0 ? substr(uri, 0, qpos) : uri;
let https = env.HTTPS == 'on';
let host = header('host') ?? '';
let m = core.load();
let r = {
io, env, m, path, https, host,
method: env.REQUEST_METHOD ?? 'GET',
peer: env.REMOTE_ADDR ?? '',
buckets: buckets(env),
title: m.settings.portal_title || 'Dawnline',
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null,
base: '',
};
let segs = filter(split(path, '/'), (s) => s != '');
// Plain HTTP only for an IP address chosen in Settings (no certificate exists
// for it); names stay HTTPS-only.
if (!https) {
let h = match(host, /^\[/) ? host : split(host, ':')[0];
if (ip2int(h) == null || index(core.portal_hosts(m), h) < 0)
not_found(r);
}
// The link is /<word-code>[/assets/…|/api/…]: the code is the address.
if (length(segs) < 1 || !match(segs[0], core.WORD_CODE))
not_found(r);
let code = segs[0];
for (let id, p in m.people)
if (p.code == code)
r.person = p;
// A wrong code is indistinguishable from a path that does not exist. Only
// well-formed guesses count towards the limit, and a client over it is just
// no longer counted: a valid link always opens, so guesses from a shared
// address (every Cloudflare visitor) cannot lock its owner out.
if (r.person == null) {
if (!rate_blocked(r))
rate_fail(r);
not_found(r);
}
r.base = `/${code}`;
let rest = slice(segs, 1);
if (length(rest) == 0 && r.method == 'GET')
shell(r);
if (rest[0] == 'assets' && length(rest) == 2 && r.method == 'GET')
asset(r, rest[1]);
if (rest[0] != 'api')
not_found(r);
// CSRF: only same-origin JSON requests (a cross-site page cannot send
// application/json without CORS, and it would need the code anyway).
if (r.method == 'POST') {
let origin = header('origin');
if (!match(env.CONTENT_TYPE ?? '', /^application\/json/) ||
(origin != null && origin != `${https ? 'https' : 'http'}://${host}`))
fail(r, '403 Forbidden', 'Cross-site request refused.');
}
else if (r.method != 'GET')
fail(r, '405 Method Not Allowed', 'Method not allowed.');
let rt = route(API, r.method, slice(rest, 1));
if (!rt)
fail(r, '404 Not Found', 'Not found.');
rt.run(r, rt.args[0]);
fail(r, '404 Not Found', 'Not found.');
};
/** Run handle() and swallow its early end. */
export function serve(io) {
try {
handle(io);
}
catch (e) {
if (e.message != DONE)
io.write(`Status: 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\nError\n`);
}
};
@@ -0,0 +1,116 @@
// Dawnline — the portal's certificate (configured, ACME or self-signed) and
// the addresses its links could use.
import { lsdir } from 'fs';
import { cursor } from 'uci';
import { q, sh, sh_out, ensure_dir, file_exists, valid_host, ip2int, cloudflare_ip, DATA_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as lookup from 'dawnline.lookup';
/** The DNS names a certificate file covers. */
export function cert_names(path) {
let sans = sh_out(`openssl x509 -in ${q(path)} -noout -text 2>/dev/null | grep -o 'DNS:[^,]*'`) ?? '';
return filter(split(replace(sans, /DNS:/g, ''), /[ \t\r\n]+/), (x) => x != '');
};
/** A certificate name covers host: the same name, or a wildcard one level up. */
export function name_covers(name, host) {
if (name == host)
return true;
let dot = index(host ?? '', '.');
return substr(name, 0, 2) == '*.' && dot > 0 && substr(host, dot) == substr(name, 1);
};
/** 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$/);
if (!m)
continue;
let c = `/etc/ssl/acme/${f}`, k = `/etc/ssl/acme/${m[1]}.key`;
if (file_exists(k))
push(out, { cert: c, key: k, names: cert_names(c) });
}
return out;
};
/** The ACME certificate that covers host (exact name or a wildcard), if any. */
export function acme_cert_for(host) {
for (let a in acme_certs())
for (let n in a.names)
if (name_covers(n, host))
return a;
return null;
};
/** Certificate the portal should use: configured, ACME for the host, or self-signed. */
export function portal_cert(s) {
if (s.portal_cert && s.portal_key && file_exists(s.portal_cert) && file_exists(s.portal_key))
return { cert: s.portal_cert, key: s.portal_key, self_signed: false };
if (s.portal_host) {
for (let base in [ `/etc/ssl/acme/${s.portal_host}`, `/etc/acme/${s.portal_host}_ecc/${s.portal_host}` ]) {
let c = `${base}.fullchain.crt`, k = `${base}.key`;
if (file_exists(c) && file_exists(k))
return { cert: c, key: k, self_signed: false };
}
// An ACME certificate issued for several names, the portal's among them.
let a = acme_cert_for(s.portal_host);
if (a)
return { cert: a.cert, key: a.key, self_signed: false };
}
let c = `${DATA_DIR}/portal.crt`, k = `${DATA_DIR}/portal.key`;
if (!file_exists(c) || !file_exists(k)) {
ensure_dir(DATA_DIR, 0o700);
let cn = s.portal_host || 'dawnline';
sh(`openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj ${q('/CN=' + cn)} -keyout ${k} -out ${c}`);
system(`chmod 600 ${k}`);
}
return { cert: c, key: k, self_signed: true };
};
/*
* Addresses the portal could use in links, found on the router: names in ACME
* certificates, server endpoints, DDNS names, the current one, and the WAN IP.
* Each says where it points and whether a certificate covers it.
*/
export function portal_candidates(m) {
let wan = lookup.router_wan(m);
let names = [];
let add = (h) => {
if (h && valid_host(h) && ip2int(h) == null && substr(h, 0, 2) != '*.' && index(names, h) < 0)
push(names, h);
};
let certs = acme_certs();
for (let a in certs)
for (let n in a.names)
add(n);
for (let id, srv in m.servers)
add(srv.endpoint);
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (sv) => {
if (sv.enabled != '0') {
add(sv.lookup_host);
add(sv.domain);
}
});
for (let h in core.portal_hosts(m))
add(h);
let found = lookup.resolve_all(names);
let covered = (h) => length(filter(certs, (a) => length(filter(a.names, (n) => name_covers(n, h))) > 0)) > 0;
let out = [];
for (let h in names) {
let ips = found[h] ?? [];
push(out, { host: h, kind: 'name', ips, here: wan != null && index(ips, wan) >= 0,
cloudflare: length(filter(ips, (x) => cloudflare_ip(x))) > 0, cert: covered(h) });
}
if (wan)
push(out, { host: wan, kind: 'ip', ips: [ wan ], here: true, cloudflare: false, cert: false });
for (let ph in core.portal_hosts(m))
if (ip2int(ph) != null && ph != wan)
push(out, { host: ph, kind: 'ip', ips: [ ph ], here: false, cloudflare: false, cert: false });
// Best first: here with a certificate, then here, then the rest.
let score = (c) => (c.here ? 4 : 0) + (c.cert ? 2 : 0) + (c.kind == 'name' ? 1 : 0) - (c.cloudflare ? 8 : 0);
return sort(out, (a, b) => score(b) - score(a));
};
@@ -0,0 +1,101 @@
// Dawnline — the plain resolver for people with Home-only access: real
// addresses from the WAN's DNS, home names from the LAN DNS. Their internet
// does not use the tunnel, so fake-IP answers would break it. dawnline.loop
// says where it runs (inside the netns while it exists, otherwise on the
// tunnel interfaces); procd runs dnsmasq through /usr/libexec/dawnline/resolver.
import { readfile, writefile, stat } from 'fs';
import { cursor } from 'uci';
import { ensure_dir, iface_status, uniq } from 'dawnline.util';
import * as net from 'dawnline.net';
import * as core from 'dawnline.core';
/** Port on the tunnel addresses while it runs on the router itself. */
export const PORT = 5354;
export const CONF = '/var/etc/dawnline-dns.conf';
const RESOLV = '/var/etc/dawnline-dns.resolv';
const PID = '/var/run/dawnline-dns.pid';
const FALLBACK_DNS = [ '1.1.1.1', '8.8.8.8' ];
function wan_dns() {
let out = [];
let snap = net.snapshot();
let wan = snap.devices[snap.wan]?.logical;
for (let name in uniq([ wan, 'wan', 'wan6' ])) {
if (!name)
continue;
for (let a in iface_status(name)?.['dns-server'] ?? [])
if (match(a, /^[0-9.]+$/))
push(out, a);
}
return length(out) ? uniq(out) : FALLBACK_DNS;
}
/** Local domain of the LAN DNS (dnsmasq `domain`, else the Dawnline hostname domain). */
function lan_domain(m) {
let c = cursor();
c.load('dhcp');
let d = null;
c.foreach('dhcp', 'dnsmasq', (s) => { d ??= s.domain; });
return uniq(filter([ d, m.settings.domain ], (x) => x));
}
/** True when the resolver process is alive. */
export function running() {
let pid = trim(readfile(PID) ?? '');
return match(pid, /^[0-9]+$/) != null && stat(`/proc/${pid}`) != null;
};
/**
* Write the config for `target` (dawnline.loop resolver_target) with home
* names from `lan` (the LAN's DNS); returns true when it changed (the running
* instance is then restarted by procd's respawn after a kill). The first line
* tells /usr/libexec/dawnline/resolver where to run it.
*/
export function sync(m, target, lan) {
ensure_dir('/var/etc');
// Servers that are on: with none, the resolver idles on loopback.
let ifs = [];
for (let id, s in m.servers)
if (s.enabled)
for (let t in core.tunnels(s))
push(ifs, t.ifname);
let lines = [
`# mode=${target.mode}`,
'# Generated by Dawnline: plain DNS for Home-only tunnel clients.',
`port=${target.port}`,
'no-hosts',
'bogus-priv',
'cache-size=1000',
`pid-file=${PID}`,
'user=dnsmasq',
'group=dnsmasq',
];
if (target.mode == 'ns') {
push(lines, `listen-address=${target.address}`, 'bind-interfaces', 'no-resolv');
// Upstream from the transit address: forwarded through the router to the WAN.
for (let a in wan_dns())
push(lines, `server=${a}@${target.address}`);
}
else {
// No tunnel on: loopback only (without any interface= line dnsmasq would answer everywhere).
push(lines, 'bind-dynamic', ...(length(ifs) ? map(ifs, (i) => `interface=${i}`) : [ 'listen-address=127.0.0.1' ]), `resolv-file=${RESOLV}`);
let resolv = join('', map(wan_dns(), (a) => `nameserver ${a}\n`));
if ((readfile(RESOLV) ?? '') != resolv) {
writefile(RESOLV, resolv);
system(`chmod 644 ${RESOLV}`);
}
}
if (lan)
for (let d in lan_domain(m))
push(lines, `server=/${d}/${lan}`);
let conf = join('\n', lines) + '\n';
if ((readfile(CONF) ?? '') == conf)
return false;
writefile(CONF, conf);
system(`chmod 644 ${CONF}`);
let pid = trim(readfile(PID) ?? '');
if (match(pid, /^[0-9]+$/))
system(`kill ${pid} 2>/dev/null`);
return true;
};
@@ -0,0 +1,130 @@
// Dawnline — what the rpcd method modules (dawnline.rpc.*) share: the call
// wrapper, argument helpers, the disguise check and the portal port check.
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as health from 'dawnline.health';
import * as schema from 'dawnline.schema';
import { uniq } from 'dawnline.util';
/**
* An rpcd handler from fn(args): an object result is passed on, anything else
* is wrapped as { result }, and a failure becomes { error } (the UI shows it).
*/
export function wrap(fn) {
return function(req) {
try {
let r = fn(req.args ?? {});
return type(r) == 'object' ? r : { result: r };
}
catch (e) {
return { error: e.message ?? `${e}` };
}
};
};
/** An argument as a trimmed string ('' for null). */
export function str(v) {
return v == null ? '' : trim(`${v}`);
};
/** Days of history a caller may ask for: 1–400, default 30. */
export function clamp_days(v) {
let n = +(v ?? 30);
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
};
export const METHODS = [ 'off', 'balanced', 'max' ];
/** The disguise a new server gets: the strongest this router can run. */
export function default_method() {
let c = awg.caps();
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
};
/** A disguise method the installed AmneziaWG can run. */
export function check_method(name) {
if (index(METHODS, name) < 0)
die('Unknown disguise method.');
let c = awg.caps();
if (name == 'max' && !c.v3)
die(awg.installed()
? 'Maximum needs AmneziaWG 3.1 on the router (kmod-amneziawg, amneziawg-tools 3.1): install a 3.1 build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Maximum.');
if (name == 'balanced' && !c.v2)
die(awg.installed()
? 'Balanced needs AmneziaWG 2.0 or newer on the router: install a current build in Dawnline → Components.'
: 'AmneziaWG is not installed: install it in Dawnline → Components, then choose Balanced.');
return name;
};
/**
* The portal's ports in the final configuration `m` (compared with `was`,
* before the change) are acceptable: its HTTPS port and, when links on IP
* addresses use plain HTTP, the next port too — both get a WAN ACCEPT rule.
* Neither may be 22, 53, 80 or 443, beyond 65535, or taken by another program.
*/
/** TCP port forwards from the servers' WAN zones: [{ from, to, name }]. */
function tcp_forwards(m) {
let out = [];
for (let z in uniq([ 'wan', ...map(values(m.servers), (s) => s.wan_zone) ]))
push(out, ...core.wan_forwards(z, 'tcp'));
return out;
}
/**
* TCP ports the portal can't take, and who holds them: [{ from, to, who }].
* The router's own (22, 53, 80, 443), other programs and port forwards from WAN.
*/
export function tcp_taken(m) {
let out = [];
let held = {};
let hold = (p, who) => {
if (!held[p]) {
held[p] = true;
push(out, { from: p, to: p, who });
}
};
for (let p in schema.RESERVED_PORTS)
hold(p, 'the router itself');
for (let p, name in health.tcp_port_programs())
hold(+p, `${name} on this router`);
for (let f in tcp_forwards(m))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
return out;
};
export function check_portal(m, was) {
let s = m.settings;
if (!s.portal_enabled)
return;
let port = s.portal_port;
if (!schema.valid_port(port) || index(schema.RESERVED_PORTS, port) >= 0)
die('Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).');
let ports = [ port ];
if (core.portal_http(m)) {
let hp = core.portal_http_port(m);
if (!schema.valid_port(hp) || index(schema.RESERVED_PORTS, hp) >= 0)
die(`Links on IP addresses use plain HTTP on the next port (${hp}), which the portal cannot take. Choose another portal port.`);
push(ports, hp);
}
// Only ports the portal does not hold already: our own uhttpd is not an owner anyway.
let held = [];
if (was?.settings?.portal_enabled) {
push(held, was.settings.portal_port);
if (core.portal_http(was))
push(held, core.portal_http_port(was));
}
for (let p in ports) {
if (index(held, p) >= 0)
continue;
let owners = health.tcp_port_owners(p);
if (length(owners))
die(`TCP ${p} is already used by ${join(', ', owners)}.${p != port ? ' Links on IP addresses use plain HTTP on the port after the portal\'s.' : ''} Choose another portal port.`);
}
// A forwarded port never reaches the router: the portal would be unreachable.
for (let p in ports)
for (let f in tcp_forwards(m))
if (f.from <= p && p <= f.to)
die(`TCP ${p} is sent on by port forward “${f.name}”. Choose another portal port.`);
};
@@ -0,0 +1,214 @@
// Dawnline rpcd methods: what people reach at home — services (home
// devices and ports), circles (who reaches whom), the devices found at home,
// and "Check access".
import { readfile } from 'fs';
import { cursor } from 'uci';
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength, NAME_RULE } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as access from 'dawnline.access';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import { wrap, str } from 'dawnline.rpc.common';
/* ---------- services ---------- */
/** A new id from make() that no section has yet. */
function new_id(m, make) {
for (let i = 0; i < 20; i++) {
let id = make();
if (!store.id_taken(m, id))
return id;
}
die('Could not find a free id, try again.');
}
function service_set(a) {
let name = str(a.name);
if (!valid_name(name))
die(`Service: ${NAME_RULE}`);
let address = str(a.address);
if (!schema.ipv4(address))
die('Address must be an IPv4 address.');
let ports = filter(map(type(a.ports) == 'array' ? a.ports : split(str(a.ports), /[ ,]+/), str), (x) => x != '');
for (let pt in ports)
if (!schema.valid_port(pt))
die(`Invalid port ${pt}.`);
let id = store.transact((c, m) => {
let id = str(a.id);
if (id == '')
id = new_id(m, () => `svc_${rand_int(100000, 999999)}`);
else if (!match(id, /^[A-Za-z0-9_]{1,32}$/))
die('Invalid service id.');
// Never turn a person, device, server, circle or the settings into a service.
else if (!m.services[id] && store.id_taken(m, id))
die('That id is taken.');
c.set(core.CONFIG, id, 'service');
c.set(core.CONFIG, id, 'name', name);
c.set(core.CONFIG, id, 'address', address);
if (length(ports))
c.set(core.CONFIG, id, 'port', ports);
else
c.delete(core.CONFIG, id, 'port');
return id;
});
let s = apply.sync();
return { id, warning: s.warning };
}
function service_delete(a) {
store.transact((c, m) => {
if (!m.services[a.id])
die('Unknown service.');
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (index(p.services, a.id) >= 0) {
let rest = filter(p.services, (x) => x != a.id);
if (length(rest))
c.set(core.CONFIG, pid, 'service', rest);
else
c.delete(core.CONFIG, pid, 'service');
}
});
let s = apply.sync();
return { ok: true, warning: s.warning };
}
/* ---------- circles ---------- */
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
function circle_set(a) {
let name = str(a.name);
if (!valid_name(name) || ulength(name) > 32)
die('Enter a circle name: up to 32 characters, without < > " or \\.');
let res = store.transact((c, m) => {
let ci = a.id ? m.circles[a.id] : null;
if (a.id && !ci)
die('Unknown circle.');
let server = ci?.server ?? a.server;
if (!m.servers[server])
die('Unknown server.');
for (let id, o in m.circles)
if (id != a.id && o.server == server && lc(o.name) == lc(name))
die(`${name} already exists.`);
let id = ci?.id ?? new_id(m, () => `c_${rand_hex(4)}`);
let n = core.CIRCLE_COLORS;
c.set(core.CONFIG, id, 'circle');
c.set(core.CONFIG, id, 'server', server);
c.set(core.CONFIG, id, 'name', name);
c.set(core.CONFIG, id, 'color', `${((int(a.color) || 0) % n + n) % n}`);
if (type(a.members) == 'array') {
let want = {};
for (let pid in a.members)
if (m.people[pid]?.server == server)
want[pid] = true;
for (let pid, p in m.people)
if (want[pid])
c.set(core.CONFIG, pid, 'circle', id);
else if (p.circle == id)
c.delete(core.CONFIG, pid, 'circle');
}
return { id, edit: !!ci, server: m.servers[server].name };
});
let s = apply.sync();
admin_log('awg', res.edit ? 'changed' : 'added', 'circle', name, res.server);
return { id: res.id, circles: values(core.load().circles), warning: s.warning };
}
function circle_delete(a) {
let res = store.transact((c, m) => {
let ci = m.circles[a.id];
if (!ci)
die('Unknown circle.');
c.delete(core.CONFIG, a.id);
for (let pid, p in m.people)
if (p.circle == a.id)
c.delete(core.CONFIG, pid, 'circle');
return { name: ci.name, server: m.servers[ci.server]?.name };
});
let s = apply.sync();
admin_log('awg', 'removed', 'circle', res.name, res.server);
return { circles: values(core.load().circles), warning: s.warning };
}
/* ---------- devices at home ---------- */
/** True while OpenWrt's mDNS daemon answers on ubus. */
function mdns_running() {
return index(split(sh_out('ubus list umdns 2>/dev/null') ?? '', '\n'), 'umdns') >= 0;
}
/**
* Services announced on the home networks (Bonjour), from umdns:
* [{ type: '_airplay._tcp', name, host, address, port, txt }].
*/
function mdns_services() {
if (!mdns_running())
return [];
let r = {};
try {
r = json(sh_out(`ubus call umdns browse '{"address":true,"array":true}' 2>/dev/null`) || '{}') ?? {};
}
catch (e) {
r = {};
}
let out = [];
for (let t, insts in r)
for (let name, i in insts) {
let addr = type(i.ipv4) == 'array' ? i.ipv4[0] : i.ipv4;
if (addr)
push(out, { type: t, name, host: replace(i.host ?? '', /\.local\.?$/, ''), address: addr, port: i.port ?? 0, txt: i.txt ?? [] });
}
return out;
}
/**
* Devices at home for the Home services picker: DHCP leases and static hosts
* in the server's home networks, with the services they announce (Bonjour,
* when umdns runs).
*/
function home_hosts(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
let nets = [];
for (let cidr in net.server_net(srv).nets) {
let x = match(cidr, /^([0-9.]+)\/([0-9]+)$/);
if (x && ip2int(x[1]) != null)
push(nets, [ ip2int(x[1]), 1 << (32 - +x[2]) ]);
}
let inside = (ip) => {
let n = ip2int(ip);
return n != null && length(filter(nets, (r) => n >= r[0] && n < r[0] + r[1])) > 0;
};
let hosts = {};
for (let line in split(readfile('/tmp/dhcp.leases') ?? '', '\n')) {
let f = split(line, ' ');
if (length(f) >= 4 && inside(f[2]))
hosts[f[2]] = { address: f[2], name: f[3] == '*' ? '' : f[3], mac: f[1], services: [] };
}
let c = cursor();
if (c.load('dhcp'))
c.foreach('dhcp', 'host', (h) => {
if (h.ip && inside(h.ip))
hosts[h.ip] ??= { address: h.ip, name: h.name ?? '', mac: type(h.mac) == 'array' ? h.mac[0] : h.mac ?? '', services: [] };
});
for (let s in mdns_services())
if (hosts[s.address])
push(hosts[s.address].services, { type: s.type, name: s.name, port: s.port });
else if (inside(s.address))
hosts[s.address] = { address: s.address, name: s.host ?? '', mac: '', services: [ { type: s.type, name: s.name, port: s.port } ] };
return { hosts: sort(values(hosts), (x, y) => ip2int(x.address) - ip2int(y.address)), mdns: mdns_running() };
}
export const methods = {
service_set: { args: { id: '', name: '', address: '', ports: [] }, call: wrap(service_set) },
service_delete: { args: { id: '' }, call: wrap(service_delete) },
circle_set: { args: { id: '', server: '', name: '', color: 0, members: [] }, call: wrap(circle_set) },
circle_delete: { args: { id: '' }, call: wrap(circle_delete) },
home_hosts: { args: { id: '' }, call: wrap(home_hosts) },
access_check: { args: { from: '', to: '' }, call: wrap((a) => access.check(core.load(), a.from, a.to)) },
};
@@ -0,0 +1,89 @@
// Dawnline rpcd methods: Diagnostics (Health, the service log), backups,
// export / import, and removing Dawnline.
import { slog_clear, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as apply from 'dawnline.apply';
import * as watchdog from 'dawnline.watchdog';
import * as upd from 'dawnline.updates';
import * as store from 'dawnline.store';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import { wrap } from 'dawnline.rpc.common';
function health_view(extra) {
return { ...(extra ?? {}), checks: health.health(), ...watchdog.view(core.load()) };
}
function service_log_clear(a) {
let removed = slog_clear(+a.older_days || 0);
if (removed)
admin_log('dawnline', 'cleared', null, 'the service log', `${removed} entr${removed == 1 ? 'y' : 'ies'}${+a.older_days ? ` older than ${a.older_days} days` : ''}`);
return { removed };
}
function backup_restore(a) {
let r = backup.backup_restore(a.name);
admin_log('dawnline', 'restored', 'backup', a.name);
return r;
}
function backup_upload(a) {
let r = backup.backup_upload(a.data);
admin_log('dawnline', 'restored', 'backup', 'from a file');
return r;
}
function export_all(a) {
let r = backup.export_json();
admin_log('dawnline', 'exported', null, 'all settings', 'the file holds private keys');
return r;
}
function import_all(a) {
let r = backup.import_json(a.data);
admin_log('dawnline', 'imported', null, 'settings from a file');
return r;
}
/** Remove Dawnline's state from the router (the package is removed by the UI afterwards). */
function uninstall(a) {
if (a.confirm != 'remove')
die('Type "remove" to confirm.');
// Not in the middle of an update (opkg/apk may be installing Dawnline itself).
if (upd.busy())
die('An update is running: wait for it to finish, then remove Dawnline.');
backup.backup_create('pre-remove');
// Stop first: the agent would put back what teardown removes, and could start an automatic update.
system('/etc/init.d/dawnline stop >/dev/null 2>&1; /etc/init.d/dawnline disable >/dev/null 2>&1');
apply.teardown();
store.transact((c, m) => {
let rm = [];
c.foreach(core.CONFIG, null, (s) => {
if (s['.type'] != 'settings')
push(rm, s['.name']);
});
for (let n in rm)
c.delete(core.CONFIG, n);
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, 'settings', 'portal_enabled', '0');
});
return { ok: true };
}
export const methods = {
apply: { call: wrap((a) => apply.apply()) },
health: { call: wrap((a) => health_view()) },
health_fix: { args: { id: '' }, call: wrap((a) => health_view({ result: health.fix(a.id) })) },
service_log: { call: wrap((a) => watchdog.view(core.load())) },
service_log_clear: { args: { older_days: '' }, call: wrap(service_log_clear) },
backup_list: { call: wrap((a) => ({ backups: backup.backup_list() })) },
backup_create: { call: wrap((a) => ({ name: backup.backup_create(null) })) },
backup_restore: { args: { name: '' }, call: wrap(backup_restore) },
backup_delete: { args: { name: '' }, call: wrap((a) => ({ ok: backup.backup_delete(a.name) })) },
backup_read: { args: { name: '' }, call: wrap((a) => ({ data: backup.backup_read(a.name) })) },
backup_upload: { args: { data: '' }, call: wrap(backup_upload) },
'export': { call: wrap(export_all) },
'import': { args: { data: {} }, call: wrap(import_all) },
uninstall: { args: { confirm: '' }, call: wrap(uninstall) },
};
@@ -0,0 +1,176 @@
// Dawnline rpcd methods: people (adding, editing, pausing, their personal
// links and traffic) and their devices.
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
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 { wrap, str, clamp_days } from 'dawnline.rpc.common';
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
/* ---------- people ---------- */
function person_create(a) {
let id = store.transact((c, m) => core.create_person(c, m, {
name: str(a.name), slug: str(a.slug) || null, server: str(a.server) || null, access: a.access,
device_limit: str(a.device_limit), expires: str(a.expires), quota_gb: str(a.quota_gb), quota_period: a.quota_period,
}));
let m = core.load();
live.add_event({ type: 'person_added', person: id, detail: m.people[id].name, by: 'admin' });
return { id, link: core.portal_url(m, m.people[id]) };
}
/** Immediate edits from the person's page; returns the person as the page shows them. */
function person_update(a) {
let fields = {};
for (let k in PERSON_FIELDS)
if (a[k] != null)
fields[k] = a[k];
if (a.paused != null)
fields.paused = a.paused;
if (type(a.services) == 'array')
fields.services = a.services;
if (a.circle != null)
fields.circle = a.circle;
if (type(a.home_nets) == 'array')
fields.home_nets = a.home_nets;
let m0 = null;
let before = store.transact((c, m) => {
let p = m.people[a.id];
m0 = m;
core.update_person(c, m, a.id, fields);
return p;
});
// "moved to Test" says more than "server".
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
if (changes)
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
// Access changes affect the nft sets and client AllowedIPs.
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 };
}
function person_pause(a) {
store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
if (a.paused)
c.set(core.CONFIG, a.id, 'paused', '1');
else
c.delete(core.CONFIG, a.id, 'paused');
});
live.add_event({ type: a.paused ? 'paused' : 'resumed', person: a.id, by: 'admin' });
return apply.sync();
}
/**
* A new personal link: the old one stops working at once (every portal
* request carries the code). What the old link already handed out stays
* unless asked: `remove` lists the person's devices to take away with it.
*/
function person_regen(a) {
let gone = store.transact((c, m) => {
if (!m.people[a.id])
die('Unknown person.');
c.set(core.CONFIG, a.id, 'code', core.new_code());
c.set(core.CONFIG, a.id, 'code_set', `${time()}`);
let gone = [];
for (let id in (type(a.remove) == 'array' ? a.remove : []))
if (m.devices[id]?.person == a.id) {
push(gone, m.devices[id]);
core.delete_device(c, m, id);
}
return gone;
});
live.add_event({ type: 'link_changed', person: a.id, by: 'admin' });
let s = null;
if (length(gone)) {
for (let d in gone)
live.add_event({ type: 'device_removed', person: a.id, device: d.id, detail: d.name, dname: d.name, dkind: d.kind, by: 'admin' });
s = apply.sync();
}
let m = core.load();
return { link: core.portal_url(m, m.people[a.id]), removed: length(gone), warning: s?.warning };
}
/** The personal code and links (Copy link, QR, invite): admins only, unlike status. */
function person_links(a) {
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
return { code: p.code, link: core.portal_url(m, p), links: core.portal_urls(m, p) };
}
function person_delete(a) {
let name = store.transact((c, m) => {
let name = m.people[a.id]?.name;
core.delete_person(c, m, a.id);
return name;
});
live.add_event({ type: 'person_removed', person: a.id, detail: name, pname: name, by: 'admin' });
return apply.sync();
}
function person_usage(a) {
let usage = core.load_usage();
let m = core.load();
let p = m.people[a.id];
if (!p)
die('Unknown person.');
let days = clamp_days(a.days);
let devs = {};
for (let d in p.devices)
devs[d] = live.series([ usage.devices?.[d] ], days);
return { person: live.series([ usage.people?.[a.id] ], days), devices: devs };
}
/* ---------- devices ---------- */
function device_create(a) {
devices.need_awg();
return devices.add(a.person, a.name, a.kind, { by: 'admin' });
}
function device_config(a) {
let m = core.load();
let d = m.devices[a.id];
if (!d)
die('Unknown device.');
awg.mark_issued(m, d.id);
return awg.client_config(m, d);
}
function device_update(a) {
return devices.update(a.id, { name: a.name, disabled: a.disabled }, { by: 'admin' });
}
export const methods = {
person_create: {
args: { name: '', slug: '', server: '', access: '', device_limit: '', expires: '', quota_gb: '', quota_period: '' },
call: wrap(person_create),
},
person_update: {
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
call: wrap(person_update),
},
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
person_regen: { args: { id: '', remove: [] }, call: wrap(person_regen) },
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_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' })) },
};
@@ -0,0 +1,654 @@
// Dawnline rpcd methods: setting up a server, its General / Network /
// Interfaces settings, its disguise, and removing it.
import { cursor } from 'uci';
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, NAME_RULE, rand_int, uniq, admin_log } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as net from 'dawnline.net';
import * as loop from 'dawnline.loop';
import * as awg from 'dawnline.awg';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as backup from 'dawnline.backup';
import * as devices from 'dawnline.devices';
import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
/** Server ids that would shadow a portal path. */
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
const MESH_WORDS = { off: 'devices kept apart', all: 'devices reach each other', circles: 'devices reach each other in circles' };
/* ---------- free names, ports and subnets ---------- */
/**
* UDP ports a server can't listen on, and who holds them: [{ from, to, who }].
* Other servers, tunnel interfaces, programs on the router and port forwards
* from its WAN zone. `srv` is the server being edited: its own port isn't counted.
*/
function udp_taken(m, srv, wan_zone) {
let out = [];
let held = {};
let hold = (p, who) => {
if (p > 0 && !held[p]) {
held[p] = true;
push(out, { from: p, to: p, who });
}
};
for (let id, o in m.servers)
if (id != srv?.id)
hold(o.port, `server “${o.name}”`);
let nc = cursor();
nc.load('network');
nc.foreach('network', 'interface', (s) => {
if (s.listen_port && s['.name'] != srv?.ifname)
hold(+s.listen_port, `interface ${s['.name']}`);
});
let progs = health.udp_port_programs();
for (let p in health.udp_bound())
if (p != srv?.port)
hold(p, progs[`${p}`] ? `${progs[`${p}`]} on this router` : 'another program on this router');
for (let f in core.wan_forwards(wan_zone, 'udp'))
push(out, { from: f.from, to: f.to, who: `port forward “${f.name}”` });
return out;
}
function check_udp_port(port, taken) {
for (let t in taken)
if (t.from <= port && port <= t.to)
die(`UDP ${port} is used by ${t.who}. Choose another port.`);
}
/** The usual AmneziaWG port when free, otherwise a random high one. */
const DEFAULT_PORT = 4500;
function free_port(taken) {
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
if (!used(DEFAULT_PORT))
return DEFAULT_PORT;
for (let i = 0; i < 50; i++) {
let p = rand_int(40000, 60000);
if (!used(p))
return p;
}
return 51830;
}
function free_subnet(taken) {
for (let i = 0; i < 300; i++) {
// 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
let bad = false;
for (let t in taken) {
let tc = parse_cidr(t);
if (tc && cidr_overlaps(cand, tc)) {
bad = true;
break;
}
}
if (!bad)
return cidr_str(cand);
}
return '10.77.0.0/24';
}
/**
* A portal port free together with the next one (plain HTTP for IP links):
* `first` (the server's UDP number, TCP is another port) before the usual ones.
*/
function free_portal_port(first, cur, taken) {
let used = (p) => length(filter(taken, (t) => t.from <= p && p <= t.to)) > 0;
for (let p in uniq([ first, cur || 8443, 8443, 9443, 10443, 7443, 4443 ]))
if (!used(p) && !used(p + 1))
return p;
return 9443;
}
/** A network section name nothing uses: not the router's, not Dawnline's own links, not another server's. */
function ifname_free(m, nc, n) {
if (nc.get('network', n) != null || index(values(net.INTERNAL), n) >= 0)
return false;
for (let id, s in m.servers)
if (s.ifname == n)
return false;
return true;
}
function free_ifname(m) {
let nc = cursor();
nc.load('network');
for (let i = 0; i < 10; i++)
if (ifname_free(m, nc, `dawn${i}`))
return `dawn${i}`;
return 'dawnx';
}
function id_free(m, id) {
return !store.id_taken(m, id) && index(PORTAL_PATHS, id) < 0;
}
/** A free server id: home, then server2, server3, … (never an id anything else has). */
function free_server_id(m) {
if (id_free(m, 'home'))
return 'home';
for (let n = 2; ; n++)
if (id_free(m, `server${n}`))
return `server${n}`;
}
/** Networks a new server must not overlap, by name: the router's and the other servers'. */
function taken_networks(m) {
let out = [];
let seen = {};
let add = (name, cidr) => {
let c = parse_cidr(cidr);
if (c && !seen[cidr_str(c)]) {
seen[cidr_str(c)] = true;
push(out, { name, cidr: cidr_str(c) });
}
};
for (let n in health.networks())
add(n.iface, n.cidr);
for (let id, s in m.servers)
add(s.name, s.subnet);
return out;
}
/* ---------- setup ---------- */
function setup_defaults(a) {
let m = core.load();
let networks = taken_networks(m);
let zones = [];
let fc = cursor();
fc.load('firewall');
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
let snap = net.snapshot(true);
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
let kind = health.wan_kind(wan_ip || null);
let host = m.settings.portal_host, from = host ? 'portal' : '';
if (!host) {
// Prefer a DDNS name, then an ACME certificate's, then the WAN address —
// but never a private or CGNAT one: nobody on the internet reaches it.
let dc = cursor();
if (dc.load('ddns'))
dc.foreach('ddns', 'service', (s) => {
if (!host && s.lookup_host && s.enabled == '1') {
host = s.lookup_host;
from = 'ddns';
}
});
if (!host) {
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
from = host ? 'cert' : '';
}
if (!host && kind == 'public') {
host = wan_ip;
from = 'wan';
}
}
// The zones the WAN and LAN devices are in, whatever they are called.
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
let udp = udp_taken(m, null, wan_zone);
let tcp = tcp_taken(m);
let port = free_port(udp);
return {
id: free_server_id(m),
name: length(m.servers) ? `Server ${length(m.servers) + 1}` : 'Home',
ifname: free_ifname(m),
port,
subnet: free_subnet(map(networks, (n) => n.cidr)),
endpoint: host,
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
endpoint_from: from,
wan_kind: kind,
wan_ip: wan_ip || null,
// Automatic.
mtu: 0,
zones,
lan_zone,
wan_zone,
// A portal already on keeps its port; a new one takes the server's number when it can.
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
awg: awg.caps(),
awg_state: awg.load(),
networks,
udp_taken: udp,
tcp_taken: tcp,
};
}
/**
* Where a public address points, as the admin types it (debounced in the
* UI): the same facts Health uses, in words. `id` names the server whose WAN
* to compare with (a new one: the default WAN).
*/
function endpoint_probe(a) {
let host = str(a.host);
if (host != '' && !valid_host(host))
die('Public address must be a hostname or IP address.');
let m = core.load();
let srv = m.servers[str(a.id)] ?? null;
let f = health.endpoint_facts(srv, host);
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
return { ...f, status: w.status, text: w.text };
}
/** AmneziaWG can run a server: installed, and its kernel module loads. */
function need_awg_loaded() {
devices.need_awg();
if (!awg.load().loaded)
die("AmneziaWG's kernel module doesn't load on this firmware: reinstall a build for this kernel in Components.");
}
/** An MTU as typed: '' (automatic) or 1280-1500. */
function check_mtu(v) {
let s = str(v);
if (s != '' && (!match(s, /^[0-9]{1,4}$/) || +s < 1280 || +s > 1500))
die('MTU must be 1280-1500.');
return s;
}
function server_create(a) {
need_awg_loaded();
let snap = net.snapshot(true);
let router_subnets = health.used_subnets(null);
let id = store.transact((c, m) => {
let id = str(a.id) || 'home';
// A UCI section name: a dash would make uci drop it silently.
if (!match(id, /^[a-z][a-z0-9_]{0,23}$/))
die('Server ID may use lowercase letters, digits and underscores.');
if (!id_free(m, id))
die(`"${id}" is already taken.`);
let nc = cursor();
nc.load('network');
let ifname = str(a.ifname) || free_ifname(m);
if (!ifname_free(m, nc, ifname))
die(`Network interface ${ifname} already exists.`);
let udp = udp_taken(m, null, str(a.wan_zone) || 'wan');
let port = free_port(udp);
if (a.port != null && str(a.port) != '' && str(a.port) != '0') {
if (!schema.valid_port(a.port))
die('UDP port must be 1-65535.');
port = +str(a.port);
}
check_udp_port(port, udp);
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
let preset = str(a.preset) || default_method();
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
let pc = parse_cidr(srv.subnet);
if (pc)
srv.subnet = cidr_str(pc);
// Public addresses inside the tunnel would hide the real hosts behind them.
// New servers only: a restored backup keeps what it had.
if (pc && !core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
let taken = [ ...router_subnets ];
for (let sid, o in m.servers)
push(taken, o.subnet);
let errs = core.server_errors(m, srv, taken);
push(errs, ...awg.obf_errors(srv.obf));
if (length(errs))
die(join(' ', errs));
let set = (k, v) => c.set(core.CONFIG, id, k, v);
c.set(core.CONFIG, 'settings', 'settings');
c.set(core.CONFIG, id, 'server');
if (!valid_name(str(a.name) || 'Home'))
die(`Server: ${NAME_RULE}`);
set('name', str(a.name) || 'Home');
set('ifname', ifname);
set('port', `${port}`);
set('subnet', srv.subnet);
if (srv.endpoint)
set('endpoint', srv.endpoint);
if (mtu)
set('mtu', mtu);
set('keepalive', '25');
let kp = awg.server_keys();
set('private_key', kp.private_key);
set('public_key', kp.public_key);
set('preset', preset);
for (let ok, ov in srv.obf)
set(ok, ov);
set('lan_zone', str(a.lan_zone) || 'lan');
set('wan_zone', str(a.wan_zone) || 'wan');
set('auto_wan', '1');
set('auto_lan', '1');
if (snap.wan)
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');
set('enabled', '1');
if (a.portal_enabled != null) {
let on = a.portal_enabled === true || a.portal_enabled === 1 || a.portal_enabled === '1';
c.set(core.CONFIG, 'settings', 'portal_enabled', on ? '1' : '0');
if (a.portal_port != null && str(a.portal_port) != '' && str(a.portal_port) != '0') {
if (!schema.valid_port(a.portal_port))
die('Portal port must be 1-65535.');
c.set(core.CONFIG, 'settings', 'portal_port', `${+str(a.portal_port)}`);
}
}
if (srv.endpoint && !c.get(core.CONFIG, 'settings', 'portal_host') && valid_host(srv.endpoint))
c.set(core.CONFIG, 'settings', 'portal_host', srv.endpoint);
// The portal as it will be, whatever this call changed.
check_portal(core.load(c), m);
return id;
});
let r = apply.apply();
system('/etc/init.d/dawnline enabled || /etc/init.d/dawnline enable');
let made = core.load().servers[id];
admin_log('dawnline', 'created', 'server', made?.name ?? id, made ? `UDP ${made.port}` : null);
// netifd reads its protocol handlers when it starts: AmneziaWG installed
// after that (by hand, or by an older installer) needs a network restart.
let network_restart = !awg.state().handler;
sh_bg(network_restart ? '/etc/init.d/network restart; /etc/init.d/dawnline restart' : '/etc/init.d/dawnline restart');
return { id, applied: r, network_restart, warning: r.warning };
}
/* ---------- interfaces ---------- */
/** Interfaces card on the Server page: what exists, what is detected, what the server uses. */
function interfaces_view(m, srv, snap) {
let sn = net.server_net(srv, snap);
let home = {};
for (let h in sn.home)
home[h.dev] = h;
let devs = [];
for (let dev, d in snap.devices)
push(devs, {
...d,
own: dev == srv.ifname,
home: !!home[dev],
auto: !!home[dev]?.auto,
});
// Saved names that no longer exist still show, so they can be removed.
for (let h in sn.home)
if (h.missing)
push(devs, { name: h.dev, category: 'other', kind: 'other', missing: true, nets: [], addrs: [], members: [], home: true, auto: h.auto });
let lan_only = 0;
for (let id, p in m.people)
if (p.server == srv.id && p.access == 'lan')
lan_only++;
return {
server: srv.id,
ifname: srv.ifname,
detected: { wan: snap.wan, lan: snap.lan },
saved: { wan: srv.detected_wan, lan: srv.detected_lan },
config: { auto_wan: srv.auto_wan, wan_device: srv.wan_device, auto_lan: srv.auto_lan, lan_devices: srv.lan_devices, lan_like: srv.lan_like,
device_mesh: srv.device_mesh, mesh: srv.mesh },
like_home: loop.status(),
needs: health.needs().home,
effective: sn,
zones: snap.zones,
devices: devs,
lan_only,
};
}
function interfaces_get(a) {
let m = core.load();
let srv = m.servers[a.id] ?? values(m.servers)[0];
if (!srv)
die('No server yet.');
return interfaces_view(m, srv, net.snapshot(true));
}
function server_interfaces(a) {
let snap = net.snapshot(true);
let auto_wan = a.auto_wan != false && a.auto_wan != '0';
let auto_lan = a.auto_lan != false && a.auto_lan != '0';
let wan_dev = str(a.wan_device);
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
if (!auto_wan) {
if (!snap.devices[wan_dev])
die('Choose the interface that leads to the internet.');
if (!snap.devices[wan_dev].zone)
die(`${wan_dev} is not in a firewall zone, so the server port cannot be opened on it.`);
}
let lans = [];
for (let d in (type(a.lan_devices) == 'array' ? a.lan_devices : [])) {
d = str(d);
// Unknown names are kept only if they were saved before (interface down right now).
if (d == '' || d == srv.ifname || (!snap.devices[d] && index(srv.lan_devices, d) < 0))
continue;
if (snap.devices[d]?.master)
die(`${d} is part of ${snap.devices[d].master}; choose ${snap.devices[d].master} instead.`);
if (d == (auto_wan ? snap.wan : wan_dev))
die(`${d} is the WAN.`);
push(lans, d);
}
lans = uniq(lans);
let id = srv.id;
if (a.lan_like != null)
c.set(core.CONFIG, id, 'lan_like', a.lan_like === false || a.lan_like === '0' ? '0' : '1');
let mesh = index(core.MESH, a.mesh) >= 0 ? a.mesh
: a.device_mesh == null ? srv.mesh : (a.device_mesh === false || a.device_mesh === '0' ? 'off' : 'all');
c.set(core.CONFIG, id, 'mesh', mesh);
c.delete(core.CONFIG, id, 'device_mesh');
c.set(core.CONFIG, id, 'auto_wan', auto_wan ? '1' : '0');
c.set(core.CONFIG, id, 'auto_lan', auto_lan ? '1' : '0');
if (auto_wan || wan_dev == '')
c.delete(core.CONFIG, id, 'wan_device');
else
c.set(core.CONFIG, id, 'wan_device', wan_dev);
if (length(lans))
c.set(core.CONFIG, id, 'lan_device', lans);
else
c.delete(core.CONFIG, id, 'lan_device');
// Remember what was detected, as the fallback while an interface is down.
if (snap.wan)
c.set(core.CONFIG, id, 'detected_wan', snap.wan);
if (snap.lan)
c.set(core.CONFIG, id, 'detected_lan', snap.lan);
// Keep the legacy zone options in step (older code paths, health checks).
let now = core.load(c).servers[id];
let sn = net.server_net(now, snap);
if (sn.wan.zone)
c.set(core.CONFIG, id, 'wan_zone', sn.wan.zone);
if (length(sn.zones))
c.set(core.CONFIG, id, 'lan_zone', sn.zones[0]);
return { was: srv, now: core.load(c).servers[id], mesh };
});
let srv = res.was;
// What the admin changed here: the networks, and/or whether devices reach each other.
let sig = (x) => {
let sn = net.server_net(x, snap);
return `${join(',', sn.nets)}|${sn.wan.dev}|${x.lan_like}`;
};
let what = [];
if (sig(res.now) != sig(srv))
push(what, 'home network and internet path');
if (res.mesh != srv.mesh)
push(what, MESH_WORDS[res.mesh]);
if (length(what))
admin_log('awg', 'changed', 'server', srv.name, join(', ', what));
let before = join(',', net.server_net(srv, snap).nets);
apply.apply();
let m = core.load();
let v = interfaces_view(m, m.servers[srv.id], net.snapshot(true));
v.nets_changed = before != join(',', v.effective.nets);
return v;
}
/* ---------- settings ---------- */
/** A list of DNS servers as typed (array or "a, b"): each an IPv4 or IPv6 address. */
function dns_list(v) {
let list = filter(map(type(v) == 'array' ? v : split(str(v), /[ ,]+/), str), (x) => x != '');
for (let d in list)
if (!schema.ip(d))
die(`${d} is not an IP address.`);
return list;
}
/** Server settings from the General and Network tabs; applied at once. */
function server_update(a) {
let v = a.values ?? {};
if (v.device_mesh != null && v.mesh == null)
v.mesh = v.device_mesh === true || v.device_mesh == '1' ? 'all' : 'off';
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
if (v.name != null) {
if (!valid_name(str(v.name)))
die(`Server: ${NAME_RULE}`);
set('name', str(v.name));
}
// Empty = the portal's address (core.endpoint_host), as at creation.
if (v.endpoint != null) {
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
die('Public address must be a hostname or IP address.');
set('endpoint', str(v.endpoint));
}
if (v.port != null) {
if (!schema.valid_port(v.port))
die('UDP port must be 1-65535.');
let n = +str(v.port);
if (n != srv.port)
check_udp_port(n, udp_taken(m, srv, srv.wan_zone));
set('port', `${n}`);
}
if (v.enabled != null)
set('enabled', v.enabled === true || v.enabled == '1' ? '1' : '0');
if (v.mesh != null) {
if (index(core.MESH, v.mesh) < 0)
die('Unknown choice for devices reaching each other.');
set('mesh', v.mesh);
set('device_mesh', null);
}
if (v.mtu != null)
set('mtu', check_mtu(v.mtu));
if (v.keepalive != null) {
if (str(v.keepalive) != '' && (!match(str(v.keepalive), /^[0-9]{1,3}$/) || +v.keepalive > 600))
die('Keep-alive must be 0-600 seconds.');
set('keepalive', str(v.keepalive));
}
if (v.dns != null) {
let list = dns_list(v.dns);
if (length(list))
c.set(core.CONFIG, srv.id, 'dns', list);
else
c.delete(core.CONFIG, srv.id, 'dns');
}
// A new tunnel network: private, free, and every device renumbered into it.
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
let pc = parse_cidr(str(v.subnet));
if (!pc)
die('Subnet must look like 10.77.0.0/24.');
if (!core.private_cidr(pc))
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
for (let t in taken)
if (cidr_overlaps(pc, parse_cidr(t)))
die(`Subnet overlaps ${t}.`);
core.renumber_server(c, m, srv, cidr_str(pc));
}
return srv;
});
// For the log: what changed, in words. Turning on or off is its own line.
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
let what = [];
for (let k, label in labels) {
if (v[k] == null)
continue;
let was = k == 'dns' ? join(' ', srv.dns ?? []) : k == 'mtu' && !srv.mtu ? '' : `${srv[k] ?? ''}`;
let now = k == 'dns' ? join(' ', dns_list(v.dns)) : str(v[k]);
if (trim(was) != trim(now))
push(what, label);
}
let turned = v.enabled == null ? null : (v.enabled === true || v.enabled == '1');
let name = v.name != null ? str(v.name) : srv.name;
let r = apply.apply();
if (turned != null && turned != srv.enabled)
admin_log('dawnline', turned ? 'turned on' : 'turned off', 'server', name);
if (length(what))
admin_log('dawnline', 'changed', 'server', name, join(', ', what));
if (v.mesh != null && v.mesh != srv.mesh)
admin_log('dawnline', 'changed', 'server', name, MESH_WORDS[v.mesh]);
return r;
}
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
function server_ports(a) {
let m = core.load();
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
}
function server_obfuscation(a) {
let preset = str(a.preset) || default_method();
let o = awg.obf_preset(check_method(preset));
let srv = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
for (let k in core.OBF_KEYS)
c.delete(core.CONFIG, srv.id, k);
for (let k, v in o)
c.set(core.CONFIG, srv.id, k, v);
c.set(core.CONFIG, srv.id, 'preset', preset);
return srv;
});
let r = apply.apply();
admin_log('awg', 'changed', 'server', srv.name, `disguise: ${preset}`);
return r;
}
/** Remove a server with its people, their devices and its circles (a backup is made first). */
function server_delete(a) {
if (!core.load().servers[a.id])
die('Unknown server.');
backup.backup_create('pre-delete');
let res = store.transact((c, m) => {
let srv = m.servers[a.id];
if (!srv)
die('Unknown server.');
let gone = 0;
for (let pid, p in m.people)
if (p.server == srv.id) {
core.delete_person(c, m, pid);
gone++;
}
for (let cid, ci in m.circles)
if (ci.server == srv.id)
c.delete(core.CONFIG, cid);
c.delete(core.CONFIG, srv.id);
return { name: srv.name, gone };
});
let r = apply.apply();
admin_log('awg', 'removed', 'server', res.name, res.gone ? `with ${res.gone} ${res.gone == 1 ? 'person' : 'people'}` : null);
return r;
}
export const methods = {
setup_defaults: { call: wrap(setup_defaults) },
server_create: {
args: { id: '', name: '', ifname: '', port: 0, subnet: '', endpoint: '', mtu: 0, preset: '', lan_zone: '', wan_zone: '',
lan_like: true, portal_enabled: false, portal_port: 0 },
call: wrap(server_create),
},
server_ports: { args: { id: '' }, call: wrap(server_ports) },
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
server_interfaces: {
args: { id: '', auto_wan: false, wan_device: '', auto_lan: false, lan_devices: [], lan_like: false, device_mesh: true, mesh: '' },
call: wrap(server_interfaces),
},
server_delete: { args: { id: '' }, call: wrap(server_delete) },
};
@@ -0,0 +1,154 @@
// Dawnline rpcd methods: the Settings page (the portal, defaults, logs and
// 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 * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as apply from 'dawnline.apply';
import * as geo from 'dawnline.geo';
import * as store from 'dawnline.store';
import * as schema from 'dawnline.schema';
import * as health from 'dawnline.health';
import * as pc from 'dawnline.portalcert';
import { wrap, check_portal, tcp_taken } from 'dawnline.rpc.common';
/** The portal's own checks from Health, shown next to its settings. */
const PORTAL_CHECKS = [ 'portal', 'portal_dns', 'portal_reply', 'portal_http', 'cert' ];
function file_size(path) {
return stat(path)?.size ?? 0;
}
/** What the log and traffic history hold right now (Settings → Logs & history). */
function logs_info(m) {
let ev = live.load_events();
let by = {};
for (let cat in live.CATEGORIES)
by[cat] = 0;
for (let e in ev)
by[live.category_of(e.type)]++;
let usage = core.load_usage();
let days = {};
for (let grp in [ usage?.devices ?? {}, usage?.people ?? {} ])
for (let id, rec in grp)
for (let k in keys(rec.days ?? {}))
days[k] = true;
let dk = sort(keys(days));
return {
policy: live.policy(m.settings.retention),
events: length(ev),
oldest: length(ev) ? ev[0].ts : 0,
by_category: by,
log_ram: file_size(`${RUN_DIR}/events.json`),
log_flash: file_size(`${DATA_DIR}/events.json`),
usage_flash: file_size(`${DATA_DIR}/usage.json`),
usage_since: length(dk) ? dk[0] : '',
usage_days: length(dk),
geo_flash: file_size(`${DATA_DIR}/geo.json`),
};
}
function settings_get(a) {
let c = core.open_cursor();
let raw = c.get_all(core.CONFIG, 'settings') ?? {};
let m = core.load(c);
let out = {};
for (let k in keys(schema.SETTINGS))
out[k] = raw[k] ?? '';
out.log_category = live.policy(m.settings.retention).categories;
let cert = m.settings.portal_enabled ? pc.portal_cert(m.settings) : null;
return {
settings: out,
needs: health.needs(),
effective: m.settings,
services: values(m.services),
cert: cert ? { path: cert.cert, self_signed: cert.self_signed,
expires: sh_out(`openssl x509 -enddate -noout -in ${q(cert.cert)} 2>/dev/null | cut -d= -f2`) } : null,
tcp_taken: tcp_taken(m),
portal_public_port: core.portal_public_port(m),
geo_cached: length(keys(geo.load().ips)),
logs: logs_info(m),
};
}
/*
* The slow part of the portal settings (DNS lookups and the Health checks),
* fetched after the page shows.
*/
function portal_info(a) {
let m = core.load();
return {
candidates: pc.portal_candidates(m),
checks: filter(health.health(m), (x) => index(PORTAL_CHECKS, x.id) >= 0),
};
}
function same(a, b) {
return (type(a) == 'array' ? join('\n', a) : a ?? '') == (type(b) == 'array' ? join('\n', b) : b ?? '');
}
/** Save settings (`values`: key → value, '' back to the default); the portal is checked as it will be. */
function settings_update(a) {
let v = a.values ?? {};
if (type(v) != 'object')
die('Nothing to save.');
let res = store.transact((c, m) => {
let restart = false;
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);
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);
if (schema.SETTINGS[k].restart && !same(nv, c.get(core.CONFIG, 'settings', k)))
restart = true;
if (nv == null)
c.delete(core.CONFIG, 'settings', k);
else
c.set(core.CONFIG, 'settings', k, nv);
}
check_portal(core.load(c), m);
return { restart, was: m.settings };
});
let s = null;
if (res.restart)
system('/etc/init.d/dawnline reload >/dev/null 2>&1');
else
s = apply.sync();
// The changes worth a line: the portal and the watchdog (other settings are housekeeping).
let now = core.load().settings, was = res.was;
if (now.portal_enabled != was.portal_enabled)
admin_log('portal', now.portal_enabled ? 'turned on' : 'turned off', null, 'the personal portal', now.portal_enabled ? `port ${now.portal_port}` : null);
else if (now.portal_enabled) {
let what = [];
if (now.portal_port != was.portal_port)
push(what, `port ${now.portal_port}`);
if (now.portal_host != was.portal_host)
push(what, `address ${now.portal_host}`);
if (join(' ', now.portal_alt) != join(' ', was.portal_alt))
push(what, 'other addresses');
if (now.portal_cert != was.portal_cert || now.portal_key != was.portal_key)
push(what, 'certificate');
if (now.portal_redirect != was.portal_redirect)
push(what, 'redirect');
if (length(what))
admin_log('portal', 'changed', null, 'the personal portal', join(', ', what));
}
if (now.watchdog != was.watchdog)
admin_log('dawnline', now.watchdog ? 'turned on' : 'turned off', null, 'the watchdog', now.watchdog ? null : 'problems are only logged, nothing is repaired');
let out = settings_get({});
if (s?.warning)
out.warning = s.warning;
return out;
}
export const methods = {
settings_get: { call: wrap(settings_get) },
portal_info: { call: wrap(portal_info) },
settings_update: { args: { values: {} }, call: wrap(settings_update) },
};
@@ -0,0 +1,290 @@
// Dawnline rpcd methods: the live revision, the Overview status (servers,
// people, totals, map, recent activity), the activity log and traffic history.
import { readfile } from 'fs';
import { read_json, write_json, ensure_dir, lock, unlock, admin_log, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as live from 'dawnline.live';
import * as view from 'dawnline.view';
import * as geo from 'dawnline.geo';
import * as net from 'dawnline.net';
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 { wrap, str, clamp_days } from 'dawnline.rpc.common';
/** The router's public IPv4 (null when none or private). */
function wan_public(m) {
let w = lookup.router_wan(m);
return w && health.wan_kind(w) == 'public' ? w : null;
}
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
function own_addresses(m) {
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
return own;
}
/** Router location plus one point per (device, recent client address). */
function geo_view(m, usage, dmp) {
if (!m.settings.geo_enabled)
return { enabled: false, home: null, points: [] };
let cache = geo.load();
let points = [];
let now = time();
// The router's own public addresses: a device at home that reaches the server through the
// WAN address (NAT loopback) shows up from there. Home is not a place people connect from.
let own = {};
for (let id, srv in m.servers) {
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
if (a)
own[a] = true;
}
let wan = lookup.wan_ipv4('wan');
if (wan)
own[wan] = true;
for (let id, d in m.devices) {
let rec = usage.devices?.[id];
let peer = dmp.peers[d.public_key];
let cur = live.endpoint_ip(peer?.endpoint);
let online = live.online(dmp, id, peer);
for (let ip, ts in rec?.ips ?? {}) {
// Local (LAN / CGNAT) client addresses and the router's own are not shown on the map.
let pl = geo.is_public(ip) && !own[ip] ? geo.place(cache, ip) : null;
if (!pl)
continue;
push(points, {
person: d.person, device: id, ip, ts,
online: online && ip == cur,
lat: pl.lat, lon: pl.lon, city: pl.city, country: pl.country, cc: pl.cc,
asn: pl.asn ?? 0, org: pl.org ?? '',
});
}
}
let h = cache.home;
return {
enabled: true,
provider: m.settings.geo_provider,
cached: length(keys(cache.ips)),
home: (h && h.lat != null) ? { lat: h.lat, lon: h.lon, city: h.city, country: h.country, cc: h.cc, asn: h.asn ?? 0, org: h.org ?? '' } : null,
points,
};
}
/** Older connections from home get the DHCP name their address has now. */
function with_hosts(ev) {
let names = null;
for (let e in ev)
if ((e.type == 'connect' || e.type == 'roam') && !e.hosts) {
let h = net.event_hosts(e, names ??= net.lan_names());
if (h)
e.hosts = h;
}
return ev;
}
function server_view(m, srv, usage, dmp, rates, days) {
let online = 0, peers = 0;
let links = map(core.tunnels(srv), (t) => t.ifname);
let ids = {};
for (let id, d in m.devices)
ids[d.public_key] = id;
for (let k, p in dmp.peers)
if (index(links, p.ifname) >= 0) {
peers++;
if (live.online(dmp, ids[k], p))
online++;
}
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
// The newest handshake from a public address that is not the router's own:
// proof that the port is reachable from the internet.
let own = own_addresses(m);
let reached = 0;
for (let id, d in m.devices)
if (m.people[d.person]?.server == srv.id)
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
if (geo.is_public(ip) && !own[ip] && ts > reached)
reached = ts;
return {
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
// What devices get now, by kind (mtu 0 = automatic).
mtus: { computer: core.device_mtu(srv, { kind: 'computer' }), phone: core.device_mtu(srv, { kind: 'phone' }) },
address: core.server_address(srv), up: !!st.up, uptime: st.uptime ?? 0,
// Why the tunnel cannot run (its interface name belongs to another network section), or null.
blocked: srv.blocked ?? null,
// 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,
// 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).
series: live.series(map(filter(keys(m.people), (pid) => m.people[pid].server == srv.id), (pid) => usage.people?.[pid]), days),
};
}
/*
* Everything the pages show at once. Readable by read-only users: no personal
* codes or links here (person_links has them).
*/
function status(a) {
let m = core.load();
let usage = core.load_usage();
let dmp = live.dump(m);
let states = view.states(m, usage);
let days = clamp_days(a.days);
let servers = [];
let rates = read_json(`${RUN_DIR}/rate.json`, {});
let prates = read_json(`${RUN_DIR}/rate_people.json`, {});
for (let id, srv in m.servers)
push(servers, server_view(m, srv, usage, dmp, rates, days));
let people = [];
for (let id, p in m.people) {
let pv = view.person_view(m, p, usage, dmp, states, { admin: true });
pv.rate = type(prates[p.id]?.[0]) == 'array' ? prates[p.id] : [];
push(people, pv);
}
people = sort(people, (a, b) => (b.online - a.online) || (b.last_seen - a.last_seen) || (a.name < b.name ? -1 : 1));
let totals = { people: length(people), devices: 0, online: 0, active: 0 };
for (let p in people) {
totals.devices += length(p.devices);
totals.online += p.online;
if (p.state == 'active')
totals.active++;
}
let recs = values(usage.people ?? {});
let day = live.series(recs, 1)[0];
totals.today = [ day.rx, day.tx ];
let mon = [ 0, 0 ];
for (let r in recs) {
let v = live.month(r);
mon[0] += v[0];
mon[1] += v[1];
}
totals.month = mon;
let events = live.load_events();
let s = m.settings;
return {
geo: geo_view(m, usage, dmp),
version: VERSION,
now: time(),
hostname: trim(readfile('/proc/sys/kernel/hostname') ?? ''),
settings: {
portal_enabled: s.portal_enabled, portal_port: s.portal_port, portal_host: s.portal_host,
portal_public_port: core.portal_public_port(m),
default_device_limit: s.default_device_limit, domain: s.domain,
hostnames: s.hostnames, geo_enabled: s.geo_enabled, home_dns_fallback: s.home_dns_fallback,
},
servers,
people,
services: values(m.services),
circles: values(m.circles),
totals,
series: live.series(recs, days),
events: with_hosts(slice(events, length(events) > 60 ? length(events) - 60 : 0)),
like_home: loop.status(),
awg: awg.caps(),
awg_state: awg.state(),
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
wan: wan_public(m),
};
}
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
function events_list(a) {
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
let person = str(a.person), since = +a.since || 0;
let ev = filter(live.load_events(), (e) => e.type != 'server_down' && e.type != 'server_up' &&
(!person || e.person == person) && (!since || (e.ts ?? 0) > since));
let n = +a.limit || 300;
return { events: with_hosts(slice(ev, length(ev) > n ? length(ev) - n : 0)), total: length(ev), policy: live.policy() };
}
/** Remove activity by person, device, category and/or age; nothing given clears it all. */
function logs_clear(a) {
let m = core.load();
let f = {};
if (a.person) {
if (!m.people[a.person])
die('Unknown person.');
f.person = a.person;
}
if (a.device)
f.device = a.device;
if (a.category) {
if (index(live.CATEGORIES, a.category) < 0)
die('Unknown category.');
f.category = a.category;
}
if (a.older_days) {
if (!match(a.older_days, /^[1-9][0-9]{0,3}$/))
die('Older than must be a number of days.');
f.before = time() - +a.older_days * 86400;
}
let removed = live.clear_events(f);
if (removed)
admin_log('dawnline', 'cleared', null, 'the activity log',
join(' · ', filter([ `${removed} event${removed == 1 ? '' : 's'}`, f.category, f.person ? m.people[f.person].name : null,
a.older_days ? `older than ${a.older_days} days` : null ], (x) => x)));
return { ok: true, removed };
}
/**
* Reset traffic history (all | person | device). The agent owns the live
* counters, so it gets a marker; the tmpfs copy is edited too so the UI
* shows the result straight away.
*/
function usage_clear(a) {
let m = core.load();
if (index([ 'all', 'person', 'device' ], a.scope) < 0)
die('Unknown scope.');
if (a.scope == 'person' && !m.people[a.id])
die('Unknown person.');
if (a.scope == 'device' && !m.devices[a.id])
die('Unknown device.');
let req = { scope: a.scope, id: a.id, ts: time() };
ensure_dir(RUN_DIR);
let l = lock('usage-reset');
let pending = read_json(`${RUN_DIR}/usage.reset`, []);
push(pending, req);
write_json(`${RUN_DIR}/usage.reset`, pending, 0o600);
unlock(l);
let usage = core.load_usage();
if (usage) {
live.reset_usage(usage, m, a.scope, a.id);
write_json(`${RUN_DIR}/usage.json`, usage, 0o600);
}
admin_log('dawnline', 'reset traffic history', null,
a.scope == 'all' ? 'for everyone' : a.scope == 'person' ? `for ${m.people[a.id].name}` : `for ${m.devices[a.id].name} (${m.people[m.devices[a.id].person]?.name})`);
return { ok: true };
}
/** The live revision (dawnline.live.PRESENCE): pages refresh when it moves; 0 without the agent. */
/** The live revision, and the version answering (a page notices an update under it). */
function rev() {
return { rev: +(live.presence()?.rev ?? 0), version: VERSION };
}
export const methods = {
rev: { call: wrap(rev) },
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) },
usage_clear: { args: { scope: '', id: '' }, call: wrap(usage_clear) },
geo_clear: { call: wrap((a) => { geo.clear(); return { ok: true }; }) },
};
@@ -0,0 +1,139 @@
// Dawnline rpcd methods for the Components tab: status, starting update jobs
// (the updater does the work in the background), releases, release notes
// and the changes between two releases. luci.dawnline merges `methods`.
import { readfile } from 'fs';
import { cursor } from 'uci';
import { read_json, ensure_dir, VERSION, REPO, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as health from 'dawnline.health';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as builds from 'dawnline.awg_builds';
import { NAMES as PKG_NAMES } from 'dawnline.upd_pkgs';
const TAG = /^v?[0-9][0-9A-Za-z.+~-]{0,40}$/;
// check[:app|amneziawg|packages] | app[@tag|:reinstall|:rollback]
// | amneziawg[:auto|slava|grey[:ru]|:rollback] | pkgs:<name,…> (only packages Dawnline manages)
const TARGET = /^(check(:(app|amneziawg|packages))?|app(@v?[0-9][0-9A-Za-z.+~-]{0,40}|:reinstall|:rollback)?|amneziawg(:rollback|:(auto|slava|grey)(:ru)?)?|pkgs:[a-z0-9][a-z0-9.+,-]*)$/;
function wrap(fn) {
return function(req) {
try {
let r = fn(req.args ?? {});
return type(r) == 'object' ? r : { result: r };
}
catch (e) {
return { error: e.message ?? `${e}` };
}
};
}
/** AmneziaWG interfaces by name: switching builds restarts them. */
function awg_tunnels() {
let out = [];
let c = cursor();
c.load('network');
c.foreach('network', 'interface', (s) => {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(out, s._dawnline_name ?? s['.name']);
});
return out;
}
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)='([^']*)'/);
if (x)
rel[lc(x[1])] = x[2];
}
return {
version: VERSION,
firmware: { version: rel.release ?? '', target: rel.target ?? '', arch: rel.arch ?? '' },
portal: m.settings.portal_enabled,
home: length(filter(values(m.servers), (x) => x.lan_like)) > 0,
needs: health.needs(),
check: read_json(upd.CHECK_FILE, null),
job: upd.job(),
now: time(),
repo: REPO,
policy: m.settings.updates,
auto: upd.auto_state(),
kept: upd.kept_all(builds.firmware()?.postfix),
history: slice(upd.history(), 0, 12),
tunnels: awg_tunnels(),
};
}
/** Releases for the Versions list (Dawnline), five per page. */
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 };
}
/** Release notes for What's new: Dawnline by tag, or an AmneziaWG build's release. */
function notes(a) {
let rp = a.component == 'amneziawg' ? builds.SOURCES[a.build || 'slava']?.repo : REPO;
let tag = a.tag ?? '';
if (!rp || !match(tag, TAG))
die('Unknown release.');
let r = gh.release(rp, tag);
if (!r && a.component != 'amneziawg' && substr(tag, 0, 1) != 'v')
r = gh.release(rp, `v${tag}`);
if (!r)
die(`No release ${tag} in ${rp}.`);
return { ...r, digests: null, repo: rp };
}
/** What changed between the installed Dawnline and a release (points for the Components tab). */
function changes(a) {
let to = a.to ?? '', from = a.from ?? '';
if (!match(to, TAG) || (from != '' && !match(from, TAG)))
die('Unknown release.');
// The installed version as a tag when it was released (a build ahead of the releases has none).
let base = null;
for (let t in (from != '' ? [ `v${replace(from, /^v/, '')}`, replace(from, /^v/, '') ] : []))
if (!base && gh.release(REPO, t))
base = t;
return { items: gh.changes(REPO, base, to) };
}
/**
* 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.
*/
function run(a) {
let what = a.what ?? 'check';
if (length(what) > 400 || !match(what, TARGET))
die('Unknown update target.');
// Checked here too, so a wrong name never becomes a failed job in the history.
if (substr(what, 0, 5) == 'pkgs:')
for (let n in split(substr(what, 5), ','))
if (index(PKG_NAMES, n) < 0)
die(n == '' ? 'Unknown update target.' : `${n} is not a package Dawnline manages.`);
if (upd.busy())
die('Another component action is already running.');
ensure_dir(RUN_DIR);
let t0 = time();
let args = substr(what, 0, 5) == 'check' ? `check ${substr(what, 6)}` : `install ${what}`;
system(`start-stop-daemon -S -b -x /usr/libexec/dawnline/updater -- ${args}`);
for (let i = 0; i < 20; i++) {
let j = read_json(upd.JOB_FILE, null);
if (j?.state == 'running' && j.started >= t0)
return { started: true, job: j };
system('usleep 100000 2>/dev/null || sleep 1');
}
return { started: true, job: null };
}
export const methods = {
updates_status: { call: wrap(status) },
updates_run: { args: { what: '' }, call: wrap(run) },
updates_releases: { args: { page: 1 }, call: wrap(releases) },
updates_notes: { args: { component: '', tag: '', build: '' }, call: wrap(notes) },
updates_changes: { args: { from: '', to: '' }, call: wrap(changes) },
};
@@ -0,0 +1,259 @@
// Dawnline — what the settings section may hold: one entry per option with
// its type, default and range, used to validate what the admin saves and to
// parse what is stored. Also the address checks the rest of the code shares.
//
// Booleans are stored as '1' / '0' only, and parsed the way the init script's
// config_get_bool does, so the service and the code never disagree.
import { stat } from 'fs';
import { ip2int, valid_host, ulength } from 'dawnline.util';
import { INTERVALS, TARGETS } from 'dawnline.updates';
/* ---------- addresses ---------- */
/** An IPv4 address in dotted form. */
export function ipv4(s) {
return type(s) == 'string' && ip2int(s) != null;
};
/**
* An IPv6 address → its eight 16-bit groups, or null. Accepts '::' and an
* embedded IPv4 at the end (::ffff:192.0.2.1); no zone ids or prefixes.
*/
export function ipv6_groups(s) {
if (type(s) != 'string' || length(s) < 2 || length(s) > 45 || !match(s, /^[0-9A-Fa-f:.]+$/))
return null;
let tail = [];
let v4 = match(s, /^(.*:)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/);
if (v4) {
let n = ip2int(v4[2]);
if (n == null)
return null;
tail = [ (n >> 16) & 0xffff, n & 0xffff ];
s = substr(v4[1], -2) == '::' ? v4[1] : substr(v4[1], 0, length(v4[1]) - 1);
}
else if (index(s, '.') >= 0)
return null;
let halves = split(s, '::');
if (length(halves) > 2)
return null;
let groups = (part) => {
let out = [];
if (part == '')
return out;
for (let g in split(part, ':')) {
if (!match(g, /^[0-9A-Fa-f]{1,4}$/))
return null;
push(out, hex(g));
}
return out;
};
let head = groups(halves[0]);
let rest = length(halves) == 2 ? groups(halves[1]) : [];
if (head == null || rest == null)
return null;
if (length(halves) == 1) {
push(head, ...tail);
return length(head) == 8 ? head : null;
}
push(rest, ...tail);
let gap = 8 - length(head) - length(rest);
if (gap < 1)
return null;
let out = [ ...head ];
for (let i = 0; i < gap; i++)
push(out, 0);
push(out, ...rest);
return out;
};
/** An IPv6 address (any valid notation). */
export function ipv6(s) {
return ipv6_groups(s) != null;
};
/** An IPv4 or IPv6 address. */
export function ip(s) {
return ipv4(s) || ipv6(s);
};
/** A TCP/UDP port as typed: 1-5 digits, 1-65535. */
export function valid_port(v) {
let s = trim(`${v ?? ''}`);
return match(s, /^[0-9]{1,5}$/) != null && +s >= 1 && +s <= 65535;
};
/* ---------- parsing stored values ---------- */
/** A stored boolean, as the init script's config_get_bool reads it. */
export function bool(v, dflt) {
v = lc(trim(`${v ?? ''}`));
if (index([ '1', 'on', 'true', 'yes', 'enabled' ], v) >= 0)
return true;
if (index([ '0', 'off', 'false', 'no', 'disabled' ], v) >= 0)
return false;
return dflt;
};
/** A stored whole number within [min, max], else the default. */
export function to_int(v, dflt, lo, hi) {
let s = trim(`${v ?? ''}`);
if (!match(s, /^-?[0-9]{1,9}$/))
return dflt;
let n = +s;
return (lo != null && n < lo) || (hi != null && n > hi) ? dflt : n;
};
/* ---------- the settings section ---------- */
/*
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
* min/max: ints and text length; values: enums; msg: the error for a bad value.
*/
export const SETTINGS = {
portal_enabled: { type: 'bool', dflt: false, restart: true },
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
portal_alt: { type: 'hosts', dflt: [], restart: true, msg: 'Other addresses must be hostnames or IP addresses.' },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
portal_cert: { type: 'file', dflt: '', restart: true },
portal_key: { type: 'file', dflt: '', restart: true },
default_device_limit: { type: 'int', dflt: 3, min: 1, max: 32, msg: 'Default device limit must be 1-32.' },
hostnames: { type: 'bool', dflt: true },
domain: { type: 'domain', dflt: 'lan', msg: 'Domain may use lowercase letters, digits, dashes and dots.' },
// Off until the admin turns it on: lookups send people's addresses to a third party.
geo_enabled: { type: 'bool', dflt: false },
geo_provider: { type: 'enum', dflt: 'ipwho.is', values: [ 'ipwho.is', 'ipapi.co' ], msg: 'Unknown location service.' },
log_connections: { type: 'bool', dflt: true },
watchdog: { type: 'bool', dflt: true },
log_keep_days: { type: 'int', dflt: 30, min: 0, max: 9999, msg: 'Keep activity for 0 (no age limit) to 9999 days.' },
log_max: { type: 'int', dflt: 2000, min: 100, max: 20000, msg: 'Log size must be 100-20000 events.' },
log_persist: { type: 'enum', dflt: 'hourly', values: [ '10min', 'hourly', 'off' ], msg: 'Save the log every 10min, hourly or off.' },
usage_keep_days: { type: 'int', dflt: 62, min: 7, max: 1830, msg: 'Daily traffic history must be 7-1830 days.' },
usage_keep_months: { type: 'int', dflt: 24, min: 1, max: 120, msg: 'Monthly traffic history must be 1-120 months.' },
// Empty means "no fallback" (stored as 'none'); unset means the default.
home_dns_fallback: { type: 'ipv4', dflt: '1.1.1.1', msg: 'Fallback DNS must be an IPv4 address (or empty for none).' },
update_check: { type: 'bool', dflt: true },
update_interval: { type: 'enum', dflt: '1d', values: keys(INTERVALS), msg: 'Check every 6h, 12h, 1d or 7d.' },
update_auto: { type: 'bool', dflt: true },
update_mode: { type: 'enum', dflt: 'scheduled', values: [ 'immediate', 'scheduled' ], msg: 'Install updates immediately or scheduled.' },
update_time: { type: 'time', dflt: '04:00', msg: 'Enter a time as HH:MM, 00:00 to 23:59.' },
update_targets: { type: 'targets', dflt: [ 'app', 'packages' ] },
update_keep: { type: 'bool', dflt: false },
update_mirrors: { type: 'bool', dflt: true },
};
/** Ports the portal never takes: SSH, DNS and the LuCI web server. */
export const RESERVED_PORTS = [ 22, 53, 80, 443 ];
function bad(spec, key) {
die(spec.msg ?? `Invalid value for ${key}.`);
}
/**
* Check a value the admin saves for setting `key`. Returns what to store: a
* string, a list, or null to remove the option (back to the default). Dies
* with a message for the admin when the value is not acceptable.
*/
export function validate(key, val) {
let spec = SETTINGS[key];
if (!spec)
die(`Unknown setting ${key}.`);
let t = spec.type;
if (t == 'hosts') {
let lst = [];
for (let x in (type(val) == 'array' ? val : [])) {
// A typo must not vanish on Save: refused, like the main address.
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
bad(spec, key);
if (trim(x) != '' && index(lst, trim(x)) < 0)
push(lst, trim(x));
}
return length(lst) ? lst : null;
}
if (t == 'targets') {
let lst = [];
for (let x in (type(val) == 'array' ? val : []))
if (index(TARGETS, x) >= 0 && index(lst, x) < 0)
push(lst, x);
// An empty list is a choice too ("none"), unlike a missing option (the default).
return length(lst) ? lst : [ 'none' ];
}
if (type(val) == 'bool')
val = val ? '1' : '0';
val = trim(`${val ?? ''}`);
if (t == 'ipv4' && val == '')
return 'none';
if (val == '')
return null;
if (t == 'bool') {
if (val != '0' && val != '1')
die(`${key} is 0 or 1.`);
}
else if (t == 'int') {
if (!match(val, /^[0-9]{1,9}$/) || +val < spec.min || +val > spec.max)
bad(spec, key);
val = `${+val}`;
}
else if (t == 'enum') {
if (index(spec.values, val) < 0)
bad(spec, key);
}
else if (t == 'host') {
if (!valid_host(val))
bad(spec, key);
}
else if (t == 'url') {
if (length(val) > 300 || !match(val, /^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^[:space:]"'<>]*)?$/))
bad(spec, key);
}
else if (t == 'file') {
if (substr(val, 0, 1) != '/' || !stat(val))
die(`${val} does not exist.`);
}
else if (t == 'domain') {
if (!match(val, /^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/))
bad(spec, key);
}
else if (t == 'ipv4') {
if (!ipv4(val))
bad(spec, key);
}
else if (t == 'time') {
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
bad(spec, key);
}
else if (t == 'text') {
if (ulength(val) > spec.max || match(val, /[[:cntrl:]]/))
bad(spec, key);
}
return val;
};
/**
* A stored setting parsed by its schema entry: the typed value, or the default
* when it is missing or invalid. For dawnline.core's load().
*/
export function get(raw, key) {
let spec = SETTINGS[key];
let v = raw?.[key];
if (!spec)
return v;
let t = spec.type;
if (t == 'bool')
return bool(v, spec.dflt);
if (t == 'int')
return to_int(v, spec.dflt, spec.min, spec.max);
if (t == 'hosts' || t == 'targets')
return v == null ? spec.dflt : filter(type(v) == 'array' ? v : [ v ], (x) => x != '');
if (v == null || v == '')
return spec.dflt;
if (t == 'enum')
return index(spec.values, v) >= 0 ? v : spec.dflt;
if (t == 'ipv4')
return v == 'none' ? '' : (ipv4(v) ? v : spec.dflt);
return v;
};
@@ -0,0 +1,48 @@
// Dawnline — changes to /etc/config/dawnline, the one way: under the config
// lock, against a model loaded inside that lock, committed with the file kept
// private. rpcd, the portal, the CLI and the agent all go through here, so
// no change is made on a stale model and none is lost to another writer.
import { lock, unlock } from 'dawnline.util';
import * as core from 'dawnline.core';
/** Section names that are never ids of people, devices, servers, services or circles. */
export const RESERVED_IDS = [ 'settings', 'main', 'global', 'defaults' ];
/**
* Commit the dawnline config and keep it readable by root only. A commit
* that did not reach flash (full or read-only overlay) is an error: the
* caller's change never happened, and nothing downstream may act on it.
*/
export function commit(c) {
if (!c.commit(core.CONFIG))
die(`Couldn't save /etc/config/dawnline: ${c.error() ?? 'the write failed'}. Is the flash full?`);
system('chmod 600 /etc/config/dawnline');
};
/**
* Run fn(c, m) with the config lock held, on a fresh cursor and model; commit
* when fn returns (the return value is passed on). Anything fn throws aborts
* without committing and is rethrown with the same message.
*/
export function transact(fn) {
let l = lock('config');
try {
let c = core.open_cursor();
let m = core.load(c);
let r = fn(c, m);
commit(c);
unlock(l);
return r;
}
catch (e) {
unlock(l);
die(e.message ?? `${e}`);
}
};
/** Is `id` used by anything in the model (any kind of section), or reserved? */
export function id_taken(m, id) {
return index(RESERVED_IDS, id) >= 0 || m.servers?.[id] != null || m.people?.[id] != null || m.devices?.[id] != null ||
m.services?.[id] != null || m.circles?.[id] != null;
};
@@ -0,0 +1,138 @@
// Dawnline updater: Dawnline itself — check the latest release, install a
// release (latest, a tag, the same one again) or the kept previous version.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { readfile } from 'fs';
import { VERSION, REPO } from 'dawnline.util';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg';
function status(installed, latest) {
let c = upd.version_cmp(installed, latest);
return c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
}
export function check(ctx) {
let r = gh.latest(REPO);
if (!r)
return { installed: VERSION, latest: null, update: false, repo: REPO, status: '', note: `Cannot reach github.com/${REPO}` };
let latest = replace(r.tag, /^v/, '');
let st = status(VERSION, latest);
ctx.log(st == 'outdated' ? `Dawnline update is available: ${VERSION} → ${latest}`
: st == 'dev' ? `Installed Dawnline ${VERSION} is newer than the release ${latest}`
: `Dawnline is up to date (${VERSION})`);
return { installed: VERSION, latest, tag: r.tag, repo: REPO, url: r.url, published: r.published, update: st == 'outdated', status: st };
};
/**
* 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).
*/
function want_sha(ctx, tag, asset, dir) {
let want = gh.asset_sha256(REPO, tag, asset);
if (want)
return want;
let sums = `${dir}/sha256sums-${replace(tag, /[^A-Za-z0-9.-]/g, '_')}.txt`;
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/sha256sums.txt`, sums, { mirrors: false, log: ctx.log }))
return null;
for (let line in split(readfile(sums) ?? '', '\n')) {
let m = match(trim(line), /^([0-9a-f]{64})[ \t]+\*?(\S+)$/);
if (m && m[2] == asset)
return m[1];
}
return null;
}
/** Download a release's package, verified against its sha256. */
function fetch(ctx, tag, dir) {
let ver = replace(tag, /^v/, '');
let asset = `luci-app-dawnline-${ver}.${pkg.ext()}`;
ctx.phase(`Downloading ${asset}`);
let want = want_sha(ctx, tag, asset, dir);
if (!want)
die(`Release ${tag} publishes no checksum for ${asset}: not installing an unverified package`);
let f = `${dir}/${asset}`;
if (!gh.download(`https://github.com/${REPO}/releases/download/${tag}/${asset}`, f, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }))
die(`Download failed: ${asset}`);
ctx.log(`sha256 matches the release (${substr(want, 0, 12)}…)`);
return f;
}
/** The release tag of a version: tags may or may not carry the v. */
function tag_of(ver) {
for (let t in [ `v${ver}`, ver ]) {
try {
if (gh.release(REPO, t))
return t;
}
catch (e) {}
}
return `v${ver}`;
}
function backup(ctx) {
ctx.phase('Backing up configuration');
system('/usr/bin/dawnline backup --reason pre-update >/dev/null 2>&1');
}
/** arg: null (latest) | @<tag> | reinstall | rollback */
export function install(ctx, arg) {
let out = { from: VERSION, to: null };
if (arg == 'rollback') {
let k = upd.kept('app');
if (!k)
die('No previous Dawnline version is kept on the router');
out.to = k.version;
ctx.versions(VERSION, k.version);
backup(ctx);
ctx.phase(`Rolling back to ${k.version}`);
if (!pkg.install_files(k.files, true, ctx.log))
die('Installation failed');
upd.forget('app');
ctx.after('app');
return out;
}
let tag, force = false;
if (arg == 'reinstall') {
tag = tag_of(VERSION);
force = true;
}
else if (arg && substr(arg, 0, 1) == '@') {
tag = substr(arg, 1);
force = upd.version_cmp(replace(tag, /^v/, ''), VERSION) <= 0;
}
else {
let c = check(ctx);
if (!c.latest)
die(c.note);
if (!c.update) {
out.to = VERSION;
return out;
}
tag = c.tag;
}
out.to = replace(tag, /^v/, '');
ctx.versions(VERSION, out.to);
let f = fetch(ctx, tag, ctx.work);
// The version being replaced, for Roll back (downloaded again: opkg keeps
// no package files). Always for an automatic run: nobody is there to
// recover a router whose new version does not come up (postupdate rolls
// back to it on its own).
if ((ctx.pol.keep || ctx.auto?.()) && out.to != VERSION && upd.kept('app')?.version != VERSION) {
ctx.phase(`Keeping Dawnline ${VERSION} for rollback`);
try {
system(`mkdir -p '${ctx.work}/keep'`);
upd.keep('app', VERSION, [ fetch(ctx, tag_of(VERSION), `${ctx.work}/keep`) ]);
}
catch (e) {
ctx.log(`Warning: could not keep ${VERSION}: ${e.message}`);
}
}
backup(ctx);
ctx.phase('Installing package');
if (!pkg.install_files([ f ], force, ctx.log))
die('Installation failed');
ctx.after('app');
return out;
};
@@ -0,0 +1,241 @@
// 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.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import { stat } from 'fs';
import { cursor } from 'uci';
import { iface_intent } from 'dawnline.util';
import * as upd from 'dawnline.updates';
import * as gh from 'dawnline.github';
import * as pkg from 'dawnline.pkg';
import * as builds from 'dawnline.awg_builds';
function sh(cmd) {
return system(`${cmd} >/dev/null 2>&1`);
}
/**
* Download one package of a build to dir, verified when GitHub publishes its
* sha256 (then mirrors may serve it); without a sha256 only github.com itself.
* Returns the path or null.
*/
function fetch(ctx, fw, name, src, dir) {
let file = builds.asset(fw, name);
let dest = `${dir}/${src}_${file}`;
let want = gh.asset_sha256(builds.SOURCES[src].repo, fw.tag, file);
let url = `https://github.com/${builds.SOURCES[src].repo}/releases/download/${fw.tag}/${file}`;
return gh.download(url, dest, { sha256: want, mirrors: ctx.pol.mirrors, log: ctx.log }) ? dest : null;
}
/** The newest tag of the same OpenWrt series (24.10.x) in a repository, if newer than ours. */
function newer_series_tag(rp, tag) {
let series = match(tag, /^v([0-9]+\.[0-9]+)\./)?.[1];
let best = null;
try {
for (let x in gh.releases(rp, 1)) {
let t = x.tag;
if (series && match(t, regexp(`^v${replace(series, '.', '\\.')}\\.`)) && pkg.cmp(substr(t, 1), substr(tag, 1)) > 0 &&
(!best || pkg.cmp(substr(t, 1), substr(best, 1)) > 0))
best = t;
}
}
catch (e) {}
return best;
}
export function check(ctx) {
let installed = builds.installed();
let ru = pkg.version(builds.RU) != null;
let cur = installed['amneziawg-tools'];
let fw = builds.firmware();
if (!fw)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'Cannot detect the firmware target' };
if (fw.snapshot)
return { installed: cur, gen: builds.gen(cur), packages: installed, current: null, ru, sources: {}, update: false, status: '',
note: 'This is a SNAPSHOT firmware: the AmneziaWG projects publish builds for releases only' };
let dir = `${ctx.work}/check`;
system(`mkdir -p '${dir}'`);
let sources = {};
for (let id in builds.ORDER) {
let src = builds.SOURCES[id];
ctx.log(`Looking for the ${src.label} build for OpenWrt ${substr(fw.tag, 1)}`);
let f = fetch(ctx, fw, 'amneziawg-tools', id, dir);
let v = f ? pkg.file_version(f) : null;
let date = null;
try {
date = f ? gh.release(src.repo, fw.tag)?.published : null;
}
catch (e) {}
let s = { label: src.label, repo: src.repo, tag: fw.tag, version: v, gen: builds.gen(v), date };
// A newer firmware may already get 3.1 from this source.
if (s.gen != '3.1') {
let nt = newer_series_tag(src.repo, fw.tag);
if (nt) {
let nf = fetch(ctx, builds.for_tag(fw, nt), 'amneziawg-tools', id, dir);
if (builds.gen(nf ? pkg.file_version(nf) : null) == '3.1')
s.newer = { tag: nt, gen: '3.1' };
}
}
sources[id] = s;
}
// The installed build: the source whose package matches. Unknown stays unknown
// (an automatic update never switches a build it could not identify).
let current = null;
for (let id, x in sources)
if (!current && cur && x.version == cur)
current = id;
let mine = current ? sources[current] : null;
let c = cur && mine?.version ? pkg.cmp(cur, mine.version) : null;
let st = c == null ? '' : c < 0 ? 'outdated' : c > 0 ? 'dev' : 'latest';
ctx.log(cur == null ? 'AmneziaWG is not installed'
: !current ? `AmneziaWG ${cur}: no source publishes this build for this firmware any more`
: st == 'outdated' ? `AmneziaWG update is available: ${cur} → ${mine.version}`
: `AmneziaWG is up to date (${cur})`);
return { installed: cur, gen: builds.gen(cur), packages: installed, current, ru, release: fw.tag, sources,
latest: mine?.version ?? null, status: st,
update: cur == null || st == 'outdated',
// An update that changes the generation (2.0 → 3.1) breaks older apps: never automatic.
gen_change: cur != null && mine?.version != null && builds.gen(cur) != builds.gen(mine.version),
note: !length(filter(values(sources), (x) => x.version)) ? `No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} yet` : null };
};
/** 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;
let ifaces = [];
let c = cursor();
c.load('network');
c.foreach('network', 'interface', (s) => {
if (s.proto == 'amneziawg' && s.disabled != '1')
push(ifaces, s['.name']);
});
ctx.phase(`Reloading the kernel module (${length(ifaces)} tunnel(s) restart)`);
for (let i in ifaces) {
iface_intent(i, 'update', c.get('network', i, '_dawnline_name') ?? i);
sh(`ifdown '${i}'`);
}
// Both steps must really happen: the new tools against the old module (or
// no module at all) leave every tunnel down while the job says "done".
ctx.run('rmmod amneziawg');
if (stat('/sys/module/amneziawg'))
die('The old AmneziaWG kernel module is still loaded (another AmneziaWG interface may use it): reboot the router to finish the update');
ctx.run('modprobe amneziawg');
if (!stat('/sys/module/amneziawg'))
die("The new AmneziaWG kernel module doesn't load on this firmware: the tunnels stay down until it does (see the log above)");
for (let i in ifaces)
sh(`ifup '${i}'`);
}
/** After packages changed: the module loaded, netifd knowing the protocol, Dawnline set up again. */
function settle(ctx, before, after) {
if (!before['kmod-amneziawg'] && after['kmod-amneziawg']) {
ctx.phase('Loading the kernel module');
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');
}
/** The first source that publishes every package for this firmware. */
function pick(fw) {
for (let id in builds.ORDER) {
let r = null;
try {
r = gh.release(builds.SOURCES[id].repo, fw.tag);
}
catch (e) {}
if (r && length(filter(builds.PKGS, (p) => index(r.assets, builds.asset(fw, p)) >= 0)) == length(builds.PKGS))
return id;
}
return null;
}
/** arg: [auto|slava|grey][:ru] | rollback */
export function install(ctx, arg) {
let before = builds.installed();
let out = { from: before['amneziawg-tools'], to: null, before };
let fw = builds.firmware();
if (!fw)
die('Cannot detect the firmware target');
if (arg == 'rollback') {
let k = upd.kept('amneziawg');
if (!k)
die('No previous AmneziaWG build is kept on the router');
if (k.firmware && k.firmware != fw.postfix)
die('The kept AmneziaWG build was made for another firmware: it would not load on this one');
out.to = k.version;
out.build = k.build;
ctx.versions(out.from, out.to);
ctx.phase(`Rolling back to ${k.version}`);
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;
}
let parts = split(arg ?? '', ':');
let id = parts[0] || 'auto';
let want_ru = parts[1] == 'ru';
if (id == 'auto') {
id = pick(fw);
if (!id)
die(`No AmneziaWG build for OpenWrt ${substr(fw.tag, 1)} (${fw.postfix}) yet`);
}
let src = builds.SOURCES[id];
if (!src)
die(`Unknown AmneziaWG build ${id}`);
out.build = id;
let files = [];
for (let p in [ ...builds.PKGS, ...(want_ru ? [ builds.RU ] : []) ]) {
ctx.phase(`Downloading ${p} from ${src.repo}`);
let f = fetch(ctx, fw, p, id, ctx.work);
if (!f)
die(`No ${p} build for OpenWrt ${substr(fw.tag, 1)} in ${src.repo}, or it could not be verified`);
push(files, f);
}
out.to = pkg.file_version(files[1]);
ctx.versions(out.from, out.to);
// The build being replaced, for Roll back: from another source that still publishes it.
if (ctx.pol.keep && out.from && out.to != out.from) {
let dir = `${ctx.work}/keep`;
system(`mkdir -p '${dir}'`);
let kept = null;
for (let sid in builds.ORDER) {
if (sid == id || kept)
continue;
let f = fetch(ctx, fw, 'amneziawg-tools', sid, dir);
if (f && pkg.file_version(f) == out.from)
kept = sid;
}
if (kept) {
ctx.phase(`Keeping AmneziaWG ${out.from} for rollback`);
let keepf = filter(map(builds.PKGS, (p) => fetch(ctx, fw, p, kept, dir)), (x) => x);
if (length(keepf) == length(builds.PKGS))
upd.keep('amneziawg', out.from, keepf, kept, fw.postfix);
}
else
ctx.log('Warning: the installed build is no longer published, nothing to keep for rollback');
}
ctx.phase('Refreshing package lists');
pkg.refresh(ctx.log);
ctx.phase(`Installing the ${src.label} build`);
if (!pkg.install_files(files, true, ctx.log))
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;
};
@@ -0,0 +1,92 @@
// Dawnline updater: the OpenWrt packages Dawnline adds — the home-like link
// (ip-full, kmod-veth) and HTTPS plus certificates for the personal portal —
// checked against and updated from the OpenWrt feeds.
// ctx is the updater's job context (see usr/libexec/dawnline/updater).
import * as pkg from 'dawnline.pkg';
/** What Dawnline itself adds to OpenWrt (the rest of LuCI, ucode, rpcd and uhttpd is the stock system). */
export const NAMES = [ 'ip-full', 'kmod-veth', 'libustream-openssl', 'openssl-util', 'acme', 'acme-acmesh-dnsapi', 'luci-app-acme' ];
// Packages released together with each of the above, updated as a set so OpenSSL never ends up
// half old and half new.
const FAMILY = [
[ /^ip-full$/, /^ip-/ ],
[ /^(libustream-openssl|openssl-util)$/, /^(libustream-openssl|libopenssl|openssl-util$)/ ],
[ /^(acme|luci-app-acme$)/, /^acme/ ],
];
function family(p) {
for (let f in FAMILY)
if (match(p, f[0]))
return f[1];
return null;
}
/** The packages to update for these names: each one plus its upgradable family. */
function with_family(names, up) {
let set = {};
for (let n in names) {
if (up[n])
set[n] = true;
let f = family(n);
if (f)
for (let u in keys(up))
if (match(u, f))
set[u] = true;
}
return sort(keys(set));
}
/** refresh: update the package lists first (a check by hand or on schedule). */
export function check(ctx, refresh) {
if (refresh ?? true) {
ctx.phase('Refreshing package lists');
pkg.refresh();
}
let up = pkg.upgradable();
let res = {}, all = {};
for (let p in NAMES) {
let v = pkg.version(p);
let set = v ? with_family([ p ], up) : [];
res[p] = { installed: v, latest: v && up[p] ? up[p] : null, with: filter(set, (x) => x != p) };
for (let x in set)
all[x] = true;
}
let n = length(keys(all));
ctx.log(n ? `${n} package update${n == 1 ? '' : 's'} in the feeds: ${join(', ', sort(keys(all)))}` : 'System packages are up to date');
return { pkgs: res, updates: n, status: n ? 'outdated' : 'latest' };
};
/** arg: name,name,… (only names Dawnline manages): missing ones are installed, present ones updated with their family. */
export function install(ctx, arg) {
let names = filter(split(arg ?? '', ','), (x) => x != '');
for (let n in names)
if (index(NAMES, n) < 0)
die(`${n} is not a package Dawnline manages`);
if (!length(names))
die('Nothing to install');
ctx.phase('Refreshing package lists');
pkg.refresh(ctx.log);
let missing = filter(names, (n) => pkg.version(n) == null);
let have = with_family(filter(names, (n) => pkg.version(n) != null), pkg.upgradable());
if (length(have)) {
ctx.phase(`Updating ${join(', ', have)}`);
if (!pkg.upgrade(have, ctx.log))
die('Update failed');
}
if (length(missing)) {
ctx.phase(`Installing ${join(', ', missing)}`);
if (!pkg.add(missing, ctx.log))
die('Installation failed');
}
// The portal's HTTPS runs in uhttpd; a piece that just arrived lets the portal or the home-like link start.
let touched = [ ...missing, ...have ];
if (length(filter(missing, (n) => match(n, /^(openssl-util|libustream|ip-full|kmod-veth)/)))) {
ctx.after('apply');
ctx.after('uhttpd');
}
else if (length(filter(touched, (n) => match(n, /^(libustream|libopenssl)/))))
ctx.after('uhttpd');
return { updated: have, installed: missing, check: check(ctx, false) };
};
@@ -0,0 +1,228 @@
// Dawnline — what the Components tab, the updater and the agent share: the
// update policy (Settings → Updates), when an automatic run is due, the one
// update job at a time (a kernel lock), the history for Activity, and the
// versions kept for rollback. GitHub and the package manager live in
// dawnline.github and dawnline.pkg.
import { open, stat } from 'fs';
import { q, read_json, write_json, ensure_dir, RUN_DIR, DATA_DIR } from 'dawnline.util';
export const JOB_FILE = `${RUN_DIR}/update-job.json`;
export const CHECK_FILE = `${RUN_DIR}/update-check.json`;
/** Held (flock) by the updater for the whole job: busy() and stale jobs come from it, not from pids. */
export const LOCK_FILE = `${RUN_DIR}/update.lock`;
/** Automatic runs: when the last check and the last scheduled install happened. */
export const AUTO_FILE = `${DATA_DIR}/update-auto.json`;
/** What happened: updates (by hand or automatic), failures, checks that found something. */
export const HISTORY_FILE = `${DATA_DIR}/update-history.json`;
/** The version each component had before its last update (Keep the previous version). */
export const KEEP_DIR = `${DATA_DIR}/keep`;
export const INTERVALS = { '6h': 6 * 3600, '12h': 12 * 3600, '1d': 86400, '7d': 7 * 86400 };
export const TARGETS = [ 'app', 'amneziawg', 'packages' ];
function on(v, dflt) {
if (v == null || v == '')
return dflt;
return v == '1' || v == 'true' || v == 'on' || v == 'yes';
}
/** The update policy from raw UCI settings (core.load puts it in m.settings.updates). */
export function policy(s) {
s ??= {};
let t = type(s.update_targets) == 'array' ? s.update_targets : s.update_targets ? [ s.update_targets ] : null;
let time_ok = match(s.update_time ?? '', /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/);
return {
check: on(s.update_check, true),
interval: INTERVALS[s.update_interval] ? s.update_interval : '1d',
auto: on(s.update_auto, true),
mode: s.update_mode == 'immediate' ? 'immediate' : 'scheduled',
time: time_ok ? s.update_time : '04:00',
// AmneziaWG is left out by default: a new kernel module restarts every tunnel.
targets: t ? filter(t, (x) => index(TARGETS, x) >= 0) : [ 'app', 'packages' ],
keep: on(s.update_keep, false),
mirrors: on(s.update_mirrors, true),
};
};
/* ---------- schedule ---------- */
/** The scheduled time on the day of `ts` (router local time), in seconds since the epoch. */
function scheduled_on(pol, ts) {
let t = localtime(ts);
let hm = split(pol.time, ':');
return ts - (t.hour * 3600 + t.min * 60 + t.sec) + int(hm[0]) * 3600 + int(hm[1]) * 60;
}
function day_of(ts) {
let t = localtime(ts);
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
}
/** The scheduled slot `now` is in (up to an hour after the set time, also across midnight), or null. */
function slot(pol, now) {
for (let at in [ scheduled_on(pol, now), scheduled_on(pol, now - 86400) ])
if (now >= at && now - at < 3600)
return at;
return null;
}
/**
* What an automatic run should do now: 'install' (the scheduled window, at
* most an hour after the set time, once per slot), 'check' (the interval has
* passed), or null.
*/
export function due(pol, st, now) {
now ??= time();
st ??= {};
if (pol.auto && pol.mode == 'scheduled' && length(pol.targets)) {
let at = slot(pol, now);
if (at != null && st.install_day != day_of(at))
return 'install';
}
if (pol.check && now - (st.check ?? 0) >= INTERVALS[pol.interval])
return 'check';
return null;
};
export function auto_state() {
return read_json(AUTO_FILE, {});
};
export function auto_save(st) {
ensure_dir(DATA_DIR);
write_json(AUTO_FILE, st, 0o600);
};
/** Record that the scheduled slot `now` is in has run (the slot's own day, not today's after midnight). */
export function mark_day(pol, st, now) {
now ??= time();
st.install_day = day_of(slot(pol, now) ?? now);
return st;
};
/* ---------- one job at a time ---------- */
/**
* Take the update lock without waiting: the open file (keep it for the whole
* job; the kernel releases it when the process ends), or null when another
* job holds it.
*/
export function try_lock() {
ensure_dir(RUN_DIR);
let f = open(LOCK_FILE, 'a');
if (f && f.lock('xn'))
return f;
f?.close();
return null;
};
/** A job is running: someone holds the update lock. */
export function busy() {
let f = try_lock();
if (!f)
return true;
f.close();
return false;
};
/** The last job; a "running" one whose worker is gone (the lock is free) reads as failed. */
export function job() {
let j = read_json(JOB_FILE, null);
if (j?.state == 'running' && !busy()) {
j.state = 'failed';
j.error = 'The update stopped unexpectedly.';
j.finished = j.finished ?? time();
}
return j;
};
/* ---------- history (Components → Activity) ---------- */
export function history() {
let h = read_json(HISTORY_FILE, []);
return type(h) == 'array' ? h : [];
};
/** Newest first, the last 30 kept on flash. */
export function history_add(e) {
let h = history();
unshift(h, { ts: time(), ...e });
ensure_dir(DATA_DIR);
write_json(HISTORY_FILE, slice(h, 0, 30), 0o600);
};
/* ---------- Dawnline versions ---------- */
/**
* Compare Dawnline release versions (0.3.2, v0.4.0-rc1): -1, 0 or 1. Numbers
* compare as numbers; a pre-release (-rc1, -beta) comes before its release.
*/
export function version_cmp(a, b) {
let parse = (v) => {
let m = match(replace(`${v}`, /^v/, ''), /^([0-9.]+)([-~]([0-9A-Za-z.]+))?/);
return m ? { nums: map(split(m[1], '.'), (x) => int(x)), pre: m[3] } : { nums: [ 0 ], pre: `${v}` };
};
let x = parse(a), y = parse(b);
for (let i = 0; i < length(x.nums) || i < length(y.nums); i++) {
let p = x.nums[i] ?? 0, r = y.nums[i] ?? 0;
if (p != r)
return p < r ? -1 : 1;
}
if (x.pre == y.pre)
return 0;
if (x.pre == null)
return 1;
if (y.pre == null)
return -1;
// rc1 < rc2 < rc10: compare the number runs as numbers.
let px = match(x.pre, /^([^0-9]*)([0-9]*)/), py = match(y.pre, /^([^0-9]*)([0-9]*)/);
if (px[1] != py[1])
return px[1] < py[1] ? -1 : 1;
return int(px[2] || 0) < int(py[2] || 0) ? -1 : int(px[2] || 0) > int(py[2] || 0) ? 1 : 0;
};
/* ---------- kept previous versions ---------- */
/** { version, build?, firmware?, files: [paths], saved } of the kept version, or null. */
export function kept(component) {
let k = read_json(`${KEEP_DIR}/${component}/meta.json`, null);
if (!k?.version || !length(k.files ?? []))
return null;
for (let f in k.files)
if (!stat(f))
return null;
return k;
};
/** What the Components tab shows; firmware: the current one (a kept AmneziaWG build is for one firmware only). */
export function kept_all(firmware) {
let out = {};
for (let c in [ 'app', 'amneziawg' ]) {
let k = kept(c);
if (k && c == 'amneziawg' && k.firmware && firmware && k.firmware != firmware)
k = null;
out[c] = k ? { version: k.version, build: k.build ?? null, saved: k.saved ?? null } : null;
}
return out;
};
/** Replace the kept version of a component with these files (copied in). */
export function keep(component, version, files, build, firmware) {
let dir = `${KEEP_DIR}/${component}`;
system(`rm -rf ${q(dir)}; mkdir -p ${q(dir)}; chmod 700 ${q(KEEP_DIR)} ${q(dir)}`);
let saved = [];
for (let f in files) {
let to = `${dir}/${replace(f, /^.*\//, '')}`;
if (system(`cp ${q(f)} ${q(to)}`) == 0)
push(saved, to);
}
if (length(saved) == length(files))
write_json(`${dir}/meta.json`, { version, build, firmware, files: saved, saved: time() }, 0o600);
else
system(`rm -rf ${q(dir)}`);
};
export function forget(component) {
system(`rm -rf ${q(KEEP_DIR + '/' + component)}`);
};
@@ -1,9 +1,10 @@
// Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and // Dawnline — small helpers shared by the rpcd plugin, the CLI, the agent and
// the portal CGI. Nothing in here touches configuration. // the portal CGI. Nothing in here loads or commits configuration (the uci
// helpers work on a cursor the caller owns).
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs'; import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
export const VERSION = '0.1.1'; export const VERSION = '0.8.0';
/** GitHub repository with Dawnline releases (updates and the installer). */ /** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline'; export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline'; export const RUN_DIR = '/var/run/dawnline';
@@ -91,15 +92,27 @@ export function read_json(path, fallback) {
} }
}; };
/** Atomic write (temp file + rename). `mode` defaults to 0600. */ /**
* Atomic write (temp file + rename). `mode` defaults to 0600. A short write
* (flash full) leaves the old file in place and returns false.
*/
export function write_file(path, data, mode) { export function write_file(path, data, mode) {
let tmp = `${path}.tmp${rand_hex(3)}`; let tmp = `${path}.tmp${rand_hex(3)}`;
let f = open(tmp, 'w', mode ?? 0o600); let f = open(tmp, 'w', mode ?? 0o600);
if (!f) if (!f)
return false; return false;
f.write(data); data = `${data ?? ''}`;
f.close(); let n = length(data) ? f.write(data) : 0;
return rename(tmp, path); let closed = f.close();
if (n != length(data) || !closed) {
unlink(tmp);
return false;
}
if (!rename(tmp, path)) {
unlink(tmp);
return false;
}
return true;
}; };
export function write_json(path, data, mode) { export function write_json(path, data, mode) {
@@ -126,6 +139,229 @@ export function unlock(f) {
} }
}; };
// Locks this process holds through with_lock (flock does not nest: a second
// open of the same lock file in one process would wait for itself).
let held = {};
/**
* Run fn() holding the named lock and return what it returns. Nested calls
* for the same name in one process run fn() directly. Anything fn throws
* releases the lock and is rethrown with the same message.
*/
export function with_lock(name, fn) {
if (held[name])
return fn();
let l = lock(name);
held[name] = true;
try {
let r = fn();
delete held[name];
unlock(l);
return r;
}
catch (e) {
delete held[name];
unlock(l);
die(e.message ?? `${e}`);
}
};
/* ---------- uci (on the caller's cursor) ---------- */
/** Set an option only when it differs (null, '' or [] delete it); true if something changed. */
export function uci_put(c, conf, sec, opt, val) {
let cur = c.get(conf, sec, opt);
if (val == null || val == '' || (type(val) == 'array' && !length(val))) {
if (cur != null) {
c.delete(conf, sec, opt);
return true;
}
return false;
}
if (type(val) == 'array') {
if (type(cur) == 'array' && join('\n', cur) == join('\n', val))
return false;
}
else if (cur == `${val}`)
return false;
c.set(conf, sec, opt, type(val) == 'array' ? val : `${val}`);
return true;
};
/** Make `sec` a section of type `stype` (recreated when its type differs); true if it changed. */
export function uci_section(c, conf, sec, stype) {
if (c.get(conf, sec) == stype)
return false;
if (c.get(conf, sec) != null)
c.delete(conf, sec);
c.set(conf, sec, stype);
return true;
};
/**
* After committing a config ourselves (and applying it), record its new
* checksum so a later `reload_config` does not treat it as changed and
* restart unrelated services that reload on any network change.
*/
export function ack_config(confs) {
let md5f = '/var/run/config.md5';
if (!stat(md5f))
return;
let lines = split(trim(readfile(md5f) ?? ''), '\n');
for (let conf in confs) {
let path = `/var/run/config.check/${conf}`;
let sum = sh_out(`uci show ${q(conf)} | md5sum | cut -d' ' -f1`);
if (!sum)
continue;
let found = false;
for (let i = 0; i < length(lines); i++)
if (substr(lines[i], -length(path) - 2) == ` ${path}`) {
lines[i] = `${sum} ${path}`;
found = true;
}
if (!found)
push(lines, `${sum} ${path}`);
}
writefile(md5f, join('\n', lines) + '\n');
};
/* ---------- service log ---------- */
/*
* Tunnel and service starts and stops, watchdog repairs and errors: one JSON
* object per line in tmpfs (appends from several processes stay whole), a
* copy on flash that the agent refreshes hourly, and a line in syslog.
* src: awg | dawnline | portal; level: info | up | down | repair | error.
*/
export const SLOG = `${RUN_DIR}/service.log`;
export const SLOG_SAVED = `${DATA_DIR}/service.log`;
const SLOG_KEEP = 300;
export function slog(src, level, msg, detail, who, extra) {
let e = { ts: time(), src, level, msg };
// The subject, shown first and bold: a server's name, "Personal portal", "Dawnline".
if (who)
e.who = `${who}`;
// The admin's own changes: { by: 'admin', kind: 'server', note: 'port 50115' }
// read "You <msg> <kind> <who> · <note>".
for (let k in [ 'by', 'kind', 'note' ])
if (extra?.[k])
e[k] = `${extra[k]}`;
if (detail)
e.detail = substr(trim(`${detail}`), 0, 2000);
ensure_dir(RUN_DIR);
let f = open(SLOG, 'a', 0o600);
if (f) {
f.write(sprintf('%J\n', e));
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)}`);
};
/** A change the admin made in LuCI, for the service log. */
export function admin_log(src, msg, kind, who, note, detail) {
slog(src, 'info', msg, detail, who, { by: 'admin', kind, note });
};
/*
* Why Dawnline itself is about to take a tunnel down, so the hotplug log can
* tell that from a tunnel that stopped on its own. reason: settings | off |
* removed | update. Kept for two minutes.
*/
const INTENT = `${RUN_DIR}/iface-intent.json`;
export function iface_intent(ifname, reason, name) {
let all = read_json(INTENT, {});
let now = time();
for (let k, v in all)
if (now - v.ts >= 120)
delete all[k];
all[ifname] = { reason, name, ts: now };
ensure_dir(RUN_DIR);
write_json(INTENT, all, 0o600);
};
/**
* The note for a stop of `ifname`, or null. netifd may report one stop more
* than once (the interface, then its device): the note covers every report
* within 15 s of the first, then it is spent.
*/
export function take_iface_intent(ifname) {
let all = read_json(INTENT, {});
let it = all[ifname];
let now = time();
if (!it || now - it.ts >= 120 || (it.used && now - it.used >= 15))
return null;
if (!it.used) {
it.used = now;
write_json(INTENT, all, 0o600);
}
return it;
};
/** Newest first. */
export function slog_read(limit) {
let lines = split(readfile(SLOG) ?? readfile(SLOG_SAVED) ?? '', '\n');
let out = [];
for (let i = length(lines) - 1; i >= 0 && length(out) < (limit ?? SLOG_KEEP); i--) {
if (lines[i] == '')
continue;
try {
let e = json(lines[i]);
if (type(e) == 'object' && e.ts)
push(out, e);
}
catch (err) {}
}
return out;
};
/** Keep the last entries only, and save them to flash when asked. */
export function slog_trim(save) {
let lines = filter(split(readfile(SLOG) ?? '', '\n'), (l) => l != '');
if (length(lines) > SLOG_KEEP + 50) {
lines = slice(lines, -SLOG_KEEP);
write_file(SLOG, join('\n', lines) + '\n');
}
if (save && length(lines) && stat(SLOG)?.mtime > (stat(SLOG_SAVED)?.mtime ?? 0)) {
ensure_dir(DATA_DIR, 0o700);
write_file(SLOG_SAVED, join('\n', lines) + '\n');
}
};
/** Remove entries (all, or older than `days`); returns how many went. */
export function slog_clear(days) {
let keep = [], removed = 0, cut = days > 0 ? time() - days * 86400 : null;
for (let l in split(readfile(SLOG) ?? readfile(SLOG_SAVED) ?? '', '\n')) {
if (l == '')
continue;
let e = null;
try {
e = json(l);
}
catch (err) {}
if (cut != null && e?.ts >= cut)
push(keep, l);
else
removed++;
}
let data = length(keep) ? join('\n', keep) + '\n' : '';
ensure_dir(RUN_DIR);
write_file(SLOG, data);
if (stat(SLOG_SAVED))
write_file(SLOG_SAVED, data);
return removed;
};
/** After a reboot tmpfs is empty: continue the log saved on flash. */
export function slog_restore() {
if (!stat(SLOG) && stat(SLOG_SAVED)) {
ensure_dir(RUN_DIR);
write_file(SLOG, readfile(SLOG_SAVED) ?? '');
}
};
/* ---------- IPv4 ---------- */ /* ---------- IPv4 ---------- */
export function ip2int(ip) { export function ip2int(ip) {
@@ -146,6 +382,35 @@ export function int2ip(n) {
return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255); return sprintf('%d.%d.%d.%d', (n >> 24) & 255, (n >> 16) & 255, (n >> 8) & 255, n & 255);
}; };
/**
* "a.b.c.d[/len]" with any prefix 0-32 (a bare address is a /32) →
* { net, prefix, size, ip }; null for anything else. Routes, rules and
* 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]+))?$/);
if (!m)
return null;
let ip = ip2int(m[1]), prefix = m[3] != null ? +m[3] : 32;
if (ip == null || prefix > 32)
return null;
let size = 1 << (32 - prefix);
return { net: ip - ip % size, prefix, size, ip };
};
/** The first of `nets` (CIDR strings, any prefix) that holds `ip` (a string or an int), or null. */
export function in_nets(ip, nets) {
let n = type(ip) == 'int' ? ip : ip2int(ip);
if (n == null)
return null;
for (let s in nets) {
let c = cidr_any(s);
if (c && n >= c.net && n < c.net + c.size)
return s;
}
return null;
};
// Cloudflare's published ranges (https://www.cloudflare.com/ips/). // Cloudflare's published ranges (https://www.cloudflare.com/ips/).
const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', const CF_V4 = [ '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18',
'108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17',
@@ -161,13 +426,7 @@ export function cloudflare_ip(a) {
return true; return true;
return false; return false;
} }
for (let c in CF_V4) { return in_nets(n, CF_V4) != null;
let m = match(c, /^([0-9.]+)\/([0-9]+)$/);
let size = 1 << (32 - +m[2]), net = ip2int(m[1]);
if (n >= net && n < net + size)
return true;
}
return false;
}; };
/** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */ /** Parse "a.b.c.d/len" → { net, prefix, first, last, size } (net is the masked base). */
@@ -196,38 +455,139 @@ export function in_cidr(ip, c) {
return n != null && n >= c.net && n < c.net + c.size; return n != null && n >= c.net && n < c.net + c.size;
}; };
/* ---------- text ---------- */
/** Characters in a UTF-8 string (length() counts bytes: "Мама" is 8 of them). */
export function ulength(s) {
let n = 0;
for (let i = 0; i < length(s); i++)
if ((ord(s, i) & 0xc0) != 0x80)
n++;
return n;
};
/** The first `n` characters of a UTF-8 string, never cut inside one. */
export function ucut(s, n) {
let i = 0, c = 0;
while (i < length(s)) {
if ((ord(s, i) & 0xc0) != 0x80) {
if (c == n)
break;
c++;
}
i++;
}
return substr(s, 0, i);
};
// Cyrillic (Russian, Ukrainian) to Latin: а-я by code point from U+0430, then
// ё, і, ї, є, ґ; the rest of a string passes as it is.
const CYR_A = 0x430;
const CYRILLIC = [ 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u',
'f', 'kh', 'ts', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya' ];
const CYRILLIC_MORE = { '1105': 'yo', '1110': 'i', '1111': 'yi', '1108': 'ye', '1169': 'g' };
/**
* Cyrillic letters written in Latin ("Мама" → "mama", "Юля" → "yulya"):
* ids, hostnames and file names are ASCII, and a person should recognise
* their own in them. Other characters are left alone.
*/
export function translit(s) {
let out = '', i = 0, n = length(s);
while (i < n) {
let b = ord(s, i);
if (b < 0x80) {
out += substr(s, i, 1);
i++;
continue;
}
let cp = 0, len = 1;
if ((b & 0xe0) == 0xc0 && i + 1 < n) {
cp = ((b & 0x1f) << 6) | (ord(s, i + 1) & 0x3f);
len = 2;
}
else if ((b & 0xf0) == 0xe0 && i + 2 < n) {
cp = ((b & 0x0f) << 12) | ((ord(s, i + 1) & 0x3f) << 6) | (ord(s, i + 2) & 0x3f);
len = 3;
}
else if ((b & 0xf8) == 0xf0 && i + 3 < n)
len = 4;
// Upper case to lower: А-Я, Ё, І, Ї, Є, Ґ.
if (cp >= 0x410 && cp <= 0x42f)
cp += 0x20;
else if (cp == 0x401)
cp = 0x451;
else if (cp == 0x406)
cp = 0x456;
else if (cp == 0x407)
cp = 0x457;
else if (cp == 0x404)
cp = 0x454;
else if (cp == 0x490)
cp = 0x491;
let t = cp >= CYR_A && cp < CYR_A + length(CYRILLIC) ? CYRILLIC[cp - CYR_A] : CYRILLIC_MORE[`${cp}`];
out += t != null ? t : substr(s, i, len);
i += len;
}
return out;
};
/* ---------- validation ---------- */ /* ---------- validation ---------- */
export function valid_slug(s) { export function valid_slug(s) {
return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null; return type(s) == 'string' && match(s, /^[a-z0-9][a-z0-9-]{0,30}[a-z0-9]$|^[a-z0-9]$/) != null;
}; };
/** A name people see: 1-48 characters (not bytes), none of < > " \ or control characters. */
export function valid_name(s) { export function valid_name(s) {
return type(s) == 'string' && length(trim(s)) > 0 && length(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null; return type(s) == 'string' && ulength(trim(s)) > 0 && ulength(s) <= 48 && match(s, /[<>"\\[:cntrl:]]/) == null;
}; };
/** What valid_name wants, for the admin. */
export const NAME_RULE = 'Enter a name: up to 48 characters, without < > " or \\.';
export function valid_key(s) { export function valid_key(s) {
return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null; return type(s) == 'string' && match(s, /^[A-Za-z0-9+\/]{42}[AEIMQUYcgkosw048]=$/) != null;
}; };
/** An IPv6 address in its usual spelling (no zone, no brackets). */
export function is_ip6(s) {
return type(s) == 'string' && match(s, /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/) != null && match(s, /:::/) == null;
};
export function valid_host(s) { export function valid_host(s) {
return type(s) == 'string' && length(s) <= 253 && return type(s) == 'string' && length(s) <= 253 &&
(match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null || (match(s, /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/) != null ||
ip2int(s) != null || match(s, /^[0-9a-fA-F:]+$/) != null); ip2int(s) != null || is_ip6(s));
}; };
/** YYYY-MM-DD, and a day that exists (2026-02-30 does not). */
export function valid_date(s) { export function valid_date(s) {
return type(s) == 'string' && match(s, /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/) != null; let m = type(s) == 'string' ? match(s, /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) : null;
if (!m)
return false;
let l = localtime(timelocal({ year: +m[1], mon: +m[2], mday: +m[3], hour: 12, min: 0, sec: 0 }));
return l.year == +m[1] && l.mon == +m[2] && l.mday == +m[3];
}; };
/** Turn a display name into a portal slug candidate. */ /** Turn a display name into a portal slug candidate ("Мама Таня" → "mama-tanya"). */
export function slugify(s) { export function slugify(s) {
let out = lc(trim(`${s ?? ''}`)); let out = lc(translit(trim(`${s ?? ''}`)));
out = replace(out, /[^a-z0-9]+/g, '-'); out = replace(out, /[^a-z0-9]+/g, '-');
out = replace(out, /^-+|-+$/g, ''); out = replace(out, /^-+|-+$/g, '');
return substr(out, 0, 32) || 'user'; return substr(out, 0, 32) || 'user';
}; };
/**
* A device's name as a DNS label ("Galaxy S24" → "galaxy-s24", "Телефон" →
* "telefon"): at most 40 characters, "device" when nothing is left.
*/
export function host_label(s) {
let l = replace(lc(translit(`${s ?? ''}`)), /[^a-z0-9]+/g, '-');
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 40), /-+$/g, '');
return l || 'device';
};
/* ---------- time ---------- */ /* ---------- time ---------- */
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */ /** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
@@ -253,6 +613,16 @@ export function day_key(ts) {
return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday); return sprintf('%04d-%02d-%02d', t.year, t.mon, t.mday);
}; };
/**
* The day key `days` days before `ts` (default now). Counted from local noon,
* so a 23- or 25-hour day around a DST change neither skips nor repeats a day.
*/
export function day_key_ago(days, ts) {
let t = localtime(ts ?? time());
let noon = timelocal({ year: t.year, mon: t.mon, mday: t.mday, hour: 12, min: 0, sec: 0 });
return day_key(noon - (days ?? 0) * 86400);
};
export function uniq(arr) { export function uniq(arr) {
let seen = {}, out = []; let seen = {}, out = [];
for (let v in arr) for (let v in arr)
@@ -274,3 +644,18 @@ export function remove(path) {
export function now() { export function now() {
return time(); return time();
}; };
/** 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}$/))
return null;
let s = sh_out(`ubus call network.interface.${ifname} status 2>/dev/null`);
if (!s)
return null;
try {
return json(s);
}
catch (e) {
return null;
}
};
@@ -3,22 +3,24 @@
import * as core from 'dawnline.core'; import * as core from 'dawnline.core';
import * as live from 'dawnline.live'; import * as live from 'dawnline.live';
import { day_key, month_key } from 'dawnline.util'; import * as awg from 'dawnline.awg';
import { day_key_ago, month_key } from 'dawnline.util';
/** Daily totals (rx+tx) for the last `n` days, oldest first. */ /** Daily totals (rx+tx) for the last `n` days, oldest first. */
export function spark(rec, n) { export function spark(rec, n) {
let out = [], ts = time(); let out = [];
for (let i = n - 1; i >= 0; i--) { for (let i = n - 1; i >= 0; i--) {
let v = rec?.days?.[day_key(ts - i * 86400)]; let v = rec?.days?.[day_key_ago(i)];
push(out, v ? v[0] + v[1] : 0); push(out, v ? v[0] + v[1] : 0);
} }
return out; return out;
}; };
/** The device holds an older configuration than the one it would get now. */
function config_stale(m, d) { function config_stale(m, d) {
m._issued ??= core.issued(); m._issued ??= awg.issued();
let was = m._issued[d.id]; let was = m._issued[d.id];
return was != null && was != core.config_fingerprint(m, d); return was != null && was != awg.config_fingerprint(m, d);
} }
export function device_view(m, d, usage, dmp) { export function device_view(m, d, usage, dmp) {
@@ -27,7 +29,14 @@ export function device_view(m, d, usage, dmp) {
let ts = time(); let ts = time();
let hs = peer?.handshake || u?.handshake || 0; let hs = peer?.handshake || u?.handshake || 0;
let p = m.people[d.person]; let p = m.people[d.person];
return { // The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
let label = '';
if (m.settings.hostnames && p) {
m._labels ??= {};
m._labels[p.id] ??= core.device_labels(m, p);
label = m._labels[p.id][d.id] ?? 'device';
}
let v = {
id: d.id, id: d.id,
name: d.name, name: d.name,
kind: d.kind, kind: d.kind,
@@ -35,18 +44,19 @@ export function device_view(m, d, usage, dmp) {
disabled: d.disabled, disabled: d.disabled,
created: d.created, created: d.created,
created_by: d.created_by, created_by: d.created_by,
online: !!(peer && peer.handshake > 0 && ts - peer.handshake < live.ONLINE_WINDOW), online: live.online(dmp, d.id, peer),
handshake: hs, handshake: hs,
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '', endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
active: !!peer, active: !!peer,
month: live.month(u), month: live.month(u),
total: u?.total ?? [ 0, 0 ], total: u?.total ?? [ 0, 0 ],
spark: spark(u, 7), spark: spark(u, 7),
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '', hostname: label ? `${label}.${p.id}.${m.settings.domain}` : '',
browser_key: d.private_key == '', browser_key: d.private_key == '',
// Its configuration changed since it was last shown or downloaded. // Its configuration changed since it was last shown or downloaded.
config_stale: config_stale(m, d), config_stale: config_stale(m, d),
}; };
return v;
}; };
export function person_view(m, p, usage, dmp, states, opts) { export function person_view(m, p, usage, dmp, states, opts) {
@@ -85,12 +95,15 @@ export function person_view(m, p, usage, dmp, states, opts) {
if (d.handshake > v.last_seen) if (d.handshake > v.last_seen)
v.last_seen = d.handshake; v.last_seen = d.handshake;
if (opts.admin) { if (opts.admin) {
v.code = p.code; // The code and links themselves are person_links' (admins only): the
v.link = core.portal_url(m, p); // code opens the person's portal and their devices' configurations.
v.links = core.portal_urls(m, p); v.has_link = core.portal_url(m, p) != null;
v.note = p.note; v.note = p.note;
v.services = p.services; v.services = p.services;
v.home_nets = p.home_nets;
v.circle = p.circle;
v.created = p.created; v.created = p.created;
v.code_set = p.code_set;
} }
return v; return v;
}; };
@@ -0,0 +1,186 @@
// Dawnline — watchdog. The agent runs it every minute: it checks what keeps
// people connected and repairs what it can, waiting longer after each repair
// that did not help. What it finds goes to the service log; its state to
// RUN_DIR for the Health page. A cron job (libexec/dawnline/heartbeat) looks
// after the agent itself.
import { stat } from 'fs';
import { sh_out, q, read_json, write_json, slog, slog_read, RUN_DIR } from 'dawnline.util';
import * as apply from 'dawnline.apply';
import * as loop from 'dawnline.loop';
import * as health from 'dawnline.health';
import * as awg from 'dawnline.awg';
import * as nft from 'dawnline.nft';
import * as netifd from 'dawnline.netifd';
import * as upd from 'dawnline.updates';
export const STATE = `${RUN_DIR}/watchdog.json`;
/** The agent writes the time here on every tick. */
export const BEAT = `${RUN_DIR}/agent.beat`;
// Seconds before the next repair, by the number of repairs so far.
const WAIT = [ 0, 120, 600, 1800, 3600 ];
// Good minutes in a row before a repaired target's count of repairs is
// forgotten: one good minute between two failures is still flapping.
const SETTLED = 10;
/** Why a tunnel is down (AmneziaWG; kept here for older callers). */
export function iface_errors(ifname) {
return awg.iface_errors(ifname);
};
function restart_services() {
// procd keeps unchanged instances (the agent running this) and starts missing ones.
system('/etc/init.d/dawnline start >/dev/null 2>&1');
}
/**
* What to look at: { id (= the Health check id), src, name (chip), who (the log's subject), ok,
* problem, back, detail?, repair: { what, run }? }. The log reads "<who> <problem> — <what>".
*/
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) }));
if (length(m.servers))
push(out, {
id: 'nft', src: 'dawnline', name: 'Access rules', who: 'Access rules', ok: nft.present(),
problem: 'are missing', back: 'are loaded again',
repair: { what: 'loading them again', run: () => apply.apply() },
});
if (length(filter(values(m.servers), (x) => x.private_key))) {
let fw = apply.firewall_drift(m);
push(out, {
id: 'fw', src: 'dawnline', name: 'Firewall', who: 'Firewall', ok: fw == null,
problem: fw == 'off' ? "isn't running on this router (fw4): tunnels and the portal are closed"
: fw == 'changed' ? "rules for Dawnline were changed or removed" : "rules for Dawnline aren't loaded",
back: 'rules for Dawnline are in place again',
// fw4 stopped on purpose is the admin's call: report it, do not start it.
repair: fw == 'off' ? null : { what: 'restoring them', run: () => { apply.apply(); system('fw4 -q reload'); } },
});
}
let s = m.settings;
if (s.portal_enabled && !length(health.needs().https) && !length(health.tcp_port_owners(s.portal_port)))
push(out, {
id: 'portal', src: 'portal', name: 'Portal', who: 'Personal portal', ok: health.tcp_listening(s.portal_port),
problem: `isn't answering on port ${s.portal_port}`, back: 'answers again',
detail: () => sh_out("logread -l 400 2>/dev/null | grep 'uhttpd' | grep -iE 'error|fail|cert|key|bind|address' | tail -n 4"),
repair: { what: 'restarting it', run: restart_services },
});
// Only while a server is on: with all of them off it idles on loopback.
if (stat(loop.RESOLVER.conf) && length(filter(values(m.servers), (x) => x.enabled && x.private_key)))
push(out, {
id: 'resolver', src: 'dawnline', name: 'Resolver', who: 'DNS for Home-only devices', ok: loop.resolver_running(),
problem: "isn't running", back: 'runs again',
repair: { what: 'restarting it', run: restart_services },
});
push(out, {
id: 'rpc', src: 'dawnline', name: 'LuCI link', who: 'LuCI', ok: system('ubus list luci.dawnline >/dev/null 2>&1') == 0,
problem: "can't reach Dawnline (luci.dawnline is missing in rpcd)", back: 'reaches Dawnline again',
detail: () => sh_out('logread -l 400 2>/dev/null | grep rpcd | tail -n 4'),
// A reload keeps LuCI logins; a restart (second try) signs everyone out —
// and after three it stops: restarting rpcd every hour for good would
// sign every admin out for good.
repair: { what: 'reloading rpcd', max: 3, run: (n) => system(n > 1 ? '/etc/init.d/rpcd restart >/dev/null 2>&1' : '/etc/init.d/rpcd reload >/dev/null 2>&1') },
});
return out;
}
/** One pass. With repairs off it only reports. */
export function run(m) {
let now = time();
let fix = m.settings.watchdog;
// An update is replacing packages or restarting tunnels: what looks broken
// meanwhile is being worked on; repairs would only get in its way.
let busy = upd.busy();
let st = read_json(STATE, {});
let t = type(st.targets) == 'object' ? st.targets : {};
let repairs = filter(st.repairs ?? [], (r) => now - r.ts < 86400);
let seen = {};
for (let p in probes(m)) {
seen[p.id] = true;
let x = t[p.id] ??= { bad: 0, tries: 0, next: 0 };
x.name = p.name;
x.ok = p.ok;
if (p.ok) {
if (x.reported)
slog(p.src, 'up', p.back + (x.stuck ? ' · restored' : x.tries ? ` (after ${x.tries} repair${x.tries > 1 ? 's' : ''})` : ''), null, p.who);
x.bad = 0;
x.next = 0;
x.reported = false;
x.stuck = false;
// The repairs so far are forgotten only once it has stayed up a while:
// a target that fails every other minute keeps its back-off.
x.good = (x.good ?? 0) + 1;
if (x.good >= SETTLED) {
x.tries = 0;
x.good = 0;
}
continue;
}
x.good = 0;
// One bad minute can be a restart in progress.
if (++x.bad < 2)
continue;
if (busy)
continue;
if (p.repair?.max && x.tries >= p.repair.max && !x.reported) {
slog(p.src, 'error', `${p.problem} — not repaired again (${p.repair.max} repairs didn't help)`, p.detail?.(), p.who);
x.reported = true;
continue;
}
if (!fix || !p.repair || (p.repair.max && x.tries >= p.repair.max)) {
if (!x.reported)
slog(p.src, 'error', p.problem, p.detail?.(), p.who);
x.reported = true;
continue;
}
// Three repairs did not help: say so once, in red, and from then on keep
// trying quietly until it works again (that is logged).
if (x.tries >= 3 && !x.stuck && now - (x.last ?? 0) >= 50) {
x.stuck = true;
slog(p.src, 'error', `${p.problem} — ${x.tries} repairs didn't help`, p.detail?.(), p.who);
}
if (now < x.next)
continue;
x.tries++;
x.last = now;
x.next = now + WAIT[min(x.tries, length(WAIT) - 1)];
x.reported = true;
if (!x.stuck)
slog(p.src, 'repair', `${p.problem} — ${p.repair.what}`, p.detail?.(), p.who);
try {
p.repair.run(x.tries);
}
catch (e) {
if (!x.stuck)
slog(p.src, 'error', `couldn't be repaired: ${e.message}`, null, p.who);
}
if (!x.stuck)
push(repairs, { ts: now, id: p.id, name: p.name });
}
for (let id in keys(t))
if (!seen[id])
delete t[id];
write_json(STATE, { last: now, targets: t, repairs }, 0o644);
};
/** For the Health page: the watchdog's state and the newest log entries. */
export function view(m) {
let st = read_json(STATE, {});
let beat = +(read_json(BEAT, 0) ?? 0);
// The agent itself: fine while it ticks (cron restarts it after 5 minutes without).
let targets = [ { id: 'agent', name: 'Agent', ok: beat > 0 && time() - beat < 180, tries: 0 } ];
for (let id, x in (type(st.targets) == 'object' ? st.targets : {}))
push(targets, { id, name: x.name, ok: !!x.ok, tries: x.tries ?? 0 });
return {
watchdog: {
enabled: m.settings.watchdog, last: st.last ?? null, beat: beat || null, now: time(),
targets, repairs: st.repairs ?? [],
},
log: slog_read(200),
};
};
+31
View File
@@ -0,0 +1,31 @@
# Backend (ucode on the router)
Read with `code-standards.md`. Everything here runs on a small router (2 × Cortex-A53 on the reference Cudy WR3000P): cost is part of correctness.
## Layers
- `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.
## ucode
- `'use strict'` in entry points; modules `import { … } from 'fs'` / `'dawnline.x'`. Subdirectories map to dots (`dawnline.rpc.status` → `dawnline/rpc/status.uc`).
- Exported functions end with `};` (the compiler requires it). No destructuring. Regexes are POSIX (no `(?:)`, `\s\S` classes, lazy quantifiers); anchor them.
- Modules with `export` cannot be loaded with `require()`: imports are static and compiled on every start of the script.
- Doc comments (`/** … */`) on every export: what it returns, including the null/empty case.
- Shell out through one small helper per module (`run()`/`sh()`), with `2>&1` captured and the exit code checked.
- nft changes load as one script (`nft.load()`, a transaction); tables Dawnline owns are named `dawnline*` and rebuilt whole (`table X` + `delete table X` + the table).
## Cost on the router
- **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.
- **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.
- 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
- `scripts/lint-ucode.py` and `scripts/ucode-container.sh` (compiles and runs `tests/ucode` in the OpenWrt rootfs containers; `scripts/check-ucode.sh` compiles on the router instead) pass before any deploy; new directories and entry points are added to `lint-ucode.py` and `scripts/compile-ucode.sh`, and executables to the mode check in `.github/workflows/ci.yml`.
- Pure functions get a case in `tests/ucode/<module>.test.uc`; what reads the clock takes an optional `ts` so a test can pass one.
+36
View File
@@ -0,0 +1,36 @@
# Code standards
How code in our own projects (Dawnline first, the same spirit for Tachyon, liminal and the rest) is written. This file holds what applies everywhere; per area:
- `backend.md` — ucode on the router: layers, conventions, what things cost there.
- `frontend.md` — TypeScript admin UI and portal: layout, live data.
- `shell.md` — install, uninstall, init and CI scripts.
- `ui-design.md` — how anything visible looks and how it gets approved.
Match the code around you: its naming, comment density and idiom win over personal taste.
## Decomposition
- **One module, one job, named after it.** A file you cannot describe in one sentence is two files. Starting points: ~300–400 lines for a ucode/TS module, ~60 lines for a function. Past that, split by responsibility, not by line count.
- **Every module opens with a header comment**: what it owns, what it deliberately does not (and where that lives), and any invariant callers rely on (locks, files it writes, who may call it).
- **Layers point one way.** Pure helpers and the data model know nothing about the router or the UI; orchestration calls them, never the reverse. Dawnline's layers are in `backend.md`.
- **No god files, no grab-bag `ops`/`misc`/`kit` modules.** When a helper is used by one module, it stays private in that module.
- **Delete, don't deprecate.** When something is replaced, move every caller and remove the old code in the same change; no shims, no commented-out blocks.
## Logic and state
- **Validate at the boundary, trust inside.** RPC, portal, CLI and file input are checked once (types, ranges, ids, regexes anchored with `^…$`, length caps); inner code assumes valid data. Never build a shell command from unchecked input — quote with `q()` and prefer argument whitelists.
- **One writer per resource, under a lock.** Config changes go through `store.transact()` (load the model inside the lock, change, commit, chmod 600). Router state changes go through `apply` under the `apply` lock. Long jobs (updates) hold a `flock`; "is it running" comes from the lock, never from a pid file. Do not nest locks.
- **Reconcile, don't patch.** Derive router state from config and converge (idempotent: running twice changes nothing). Touch only objects you own (tagged/named `dawnline`), never foreign interfaces, zones or rules.
- **Fail closed.** If a filter or nft load fails, access stays blocked, not open. A missing dependency (no AmneziaWG, no curl, no openssl) is a reported state with a fix, never a crash: check capabilities (`awg.state()`, `health.needs()`) and gate the feature in the backend *and* the UI.
- **Atomic files.** Write JSON/state to a temp file and rename; keep runtime counters in tmpfs (`RUN_DIR`) and flush to flash (`DATA_DIR`) rarely.
- **Trust and downloads.** APIs only directly over TLS; files may come from mirrors only when their sha256 is known from the API, and every attempt is verified. No hash → direct only, or refuse.
- **Side effects at the end.** Collect restarts (network, uhttpd, re-apply) and run them once after the job, so a failure halfway never leaves half-restarted services.
- **Errors say what to do.** `die()` / thrown messages are shown to the admin: a full sentence with the cause and, where possible, the fix. Never swallow an error silently; a `catch` either handles it or logs why it is ignored.
- **Time and dates come from the router** (`localtime`, `util.today()`), not from the browser.
## Comments, names, commits
- Comments explain why and the contract, not what the next line does. English in code and UI copy.
- Names say what the thing is in the product's words (people, devices, servers, circles), not implementation words.
- Commits are reviewable pieces (one area or concern each), message says what changed and why; no push without the user's go-ahead.
+19
View File
@@ -0,0 +1,19 @@
# Frontend (TypeScript: admin UI and portal)
Read with `code-standards.md` and, for anything visible, `ui-design.md`.
## Code
- Strict TS, no `any` without a comment; types for RPC answers live in `shared/types.ts` / `admin/api.ts` and mirror the backend's shapes.
- Layout of `web/src/admin`: `ui/` generic components (button, menu, modal, drawer, tooltip, toast, controls), `widgets/` composite house widgets, `state/` polling and scoping, `events/` the activity vocabulary (model without DOM, render separate), `updater/` the Components data layer, `cores/` per-protocol bits, `pages/<page>/` one folder per page split by section, `styles/*.css` one file per feature joined in `styles/index.ts`. Shared with the portal: `src/shared/`.
- Pages build from `ui/` and `widgets/`; a page never defines a generic component. Logic that does not touch the DOM (formatting, models, CSV, sorting) lives outside the render code and gets tests.
## Live data
- Admin pages use `createPoller` (`state/poller.ts`): newest answer wins, no repaint of a region that holds focus, every RPC failure shows a toast or an inline error, never a blank section.
- Changes reach open pages through the revision (`state/live.ts`): one small `rev` call every 2 s while the page is visible; pollers that opt in (`live: true`) refresh when it moves. Their own `every` stays as a slow fallback.
- The portal does not poll (each request is a CGI process on the router, see `backend.md`): it loads once, after the visitor's own changes, and while it waits for a new device's first connection.
## Checks
- In `web/`: `npm run format:check`, `npm run typecheck`, `npm test`, `npm run build`; the rebuilt bundles under `package/` are committed (CI fails otherwise).
+7
View File
@@ -0,0 +1,7 @@
# Shell (install, uninstall, init, CI)
Read with `code-standards.md`. Anything run on the router by hand follows the workspace's `../rules/router-shell.md` (a literal stdin heredoc over SSH).
- POSIX `sh` (BusyBox ash), `set -eu` where the script allows; quote every expansion; `shellcheck -S warning` clean (CI runs it).
- Every mutating script has a `--dry-run` that prints what it would do; uninstall removes everything install created (cron, nft, firewall, routing, packages it added, files) and nothing else — including what older versions created (e.g. the priority-90 reply rules up to 0.4.0).
- BusyBox lacks GNU options (`ls -e`, `pkill`, `time` on shell functions): check on the router before relying on a flag.
+32
View File
@@ -0,0 +1,32 @@
# UI design (Dawnline admin, portal and other panels)
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.
## 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.
- **Think past the obvious.** When an option is rejected as "not it", propose new concepts, not variations of the same layout.
- **Structure over text.** Tiles, segmented controls, pills, round icon buttons, inline status, folded "Advanced" sections. Summaries first ("All 6 checks passed"), details on demand.
- **No duplication.** One place per fact (usage, device count, links). Remove what is repeated elsewhere on the page.
- **Reuse the house patterns** before inventing new ones: `dl-params` folded details with a rotating chevron, `dl-tile2` tiles, round icon buttons with tooltips, `⋯` menus (destructive and Pause inside, Pause in warn colour, "Delete" without an ellipsis), bottom toasts instead of LuCI banners, the same tiles on server and person pages.
- **Alignment and spacing are part of the design.** Shared margins and edges, equal heights in a row, controls pinned consistently (top, not centred, when the user says so), nothing clipped or overflowing, single-line labels where they fit.
- **No ellipsis on buttons or menu items** ("Remove", not "Remove…"), even when they open a dialog. "…" only for progress ("Loading…") and truncated values.
- **Colour means something:** ok = green, warn/pause = orange, danger = red, accent = blue. Icons for states instead of words where obvious.
- **Honest warnings** belong in the UI (e.g. plain HTTP, Cloudflare throttling), shown where the choice is made.
## Mocks look like the real product
A mock is judged against the page it will live on, so it must already look like it. Hand-drawn look-alikes with invented styles get rejected ("выбивается из дизайна").
- **Study the existing pages first** (the section being changed and its neighbours) and build only from their components: `dl-setsec` cards with `dl-setsec-foot`, `dl-setrow` rows with a `dl-need-ic` icon tile and `dl-switch`, `dl-seg` (`sm`, `wide`), `dl-chip` / `dl-chipbtn`, `dl-list` + `dl-row`, `dl-table`, `dl-checks` (the Health check list), `dl-tile2` tiles, `dl-panel`. A new class only when nothing fits, and then in the same tokens (`--dl-*`).
- **Buttons are `cbi-button`**: actions like Edit, Change, Rescan are `neutral` pills (as "Edit in Settings", "+ Add device"); Save and Install are `positive`. No blue text links for actions.
- **Show only what changes.** Do not add existing, unrelated controls (e.g. Devices or Access ends tiles) to a mock; say in the caption that the rest of the page stays.
- **Build it from the real code and CSS**, not from a copy:
- theme: `scp root@outline.lan:/www/luci-static/outline/{main.css,geist-*.woff2}` into the mock folder, strip `/luci-static/outline/` from the font URLs, `<html data-darkmode="true">`;
- Dawnline CSS: the files in `web/src/admin/styles/*.css` concatenated in the order of `styles/index.ts` into `dl.css`;
- markup: a small `mock.ts` that imports the real `admin/e`, `shared/icons`, `admin/ui/*` and `admin/widgets/*` (stub the LuCI globals `window.E`, `dom.content`, `L.url`), bundled with `web/node_modules/.bin/esbuild --bundle --format=iife`.
- Keep mocks outside the product repo, serve them with `python3 -m http.server` started from Bash (the preview server cannot read `~/Documents` on macOS), open them in the built-in browser, and delete the folder when the feature ships.
## Done means seen
Deploy, then look at it in the browser (desktop width, and narrow when layout changes) before reporting. Check modals and drawers stack correctly and long values do not overflow.
+2 -2
View File
@@ -19,9 +19,9 @@ grep -q "\"version\": \"$VERSION\"" "$ROOT/web/package.json" || { echo "web/pack
mkdir -p "$STAGE/www" "$OUT" mkdir -p "$STAGE/www" "$OUT"
cp -R "$APP/root/." "$STAGE/" cp -R "$APP/root/." "$STAGE/"
cp -R "$APP/htdocs/." "$STAGE/www/" cp -R "$APP/htdocs/." "$STAGE/www/"
chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" \ chmod 755 "$STAGE/usr/bin/dawnline" "$STAGE/usr/libexec/dawnline/agent" "$STAGE/usr/libexec/dawnline/updater" "$STAGE/usr/libexec/dawnline/resolver" "$STAGE/usr/libexec/dawnline/postupdate" \
"$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \ "$STAGE/etc/init.d/dawnline" "$STAGE/etc/uci-defaults/90_dawnline" "$STAGE/etc/hotplug.d/iface/95-dawnline" \
"$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/www/cgi-bin/portal" "$STAGE/usr/share/dawnline/portal/cgi.uc"
find "$STAGE" -name '.DS_Store' -delete find "$STAGE" -name '.DS_Store' -delete
TAR="$OUT/luci-app-dawnline-$VERSION.tar.gz" TAR="$OUT/luci-app-dawnline-$VERSION.tar.gz"
+342
View File
@@ -0,0 +1,342 @@
#!/usr/bin/env node
// Capture the raw README screenshots 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.
//
// 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
// 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]
//
// --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).
import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
const SCALE = 2;
const args = { router: 'https://outline.lan', person: '', mask: [], names: [], only: [] };
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
const v = () => process.argv[++i] ?? die(`${a} needs a value`);
if (a === '--router') args.router = v().replace(/\/+$/, '');
else if (a === '--person') args.person = v();
else if (a === '--mask') args.mask.push(v().split('=', 2));
else if (a === '--name') args.names.push(v().split('=', 2));
else if (a === '--only') args.only = v().split(',');
else die(`unknown argument ${a}`);
}
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. */
const initials = (name) => {
const p = name.trim().split(/\s+/);
return (p[0][0] + (p.length > 1 ? p[p.length - 1][0] : (p[0][1] ?? ''))).toUpperCase();
};
for (const [real, shown] of args.names)
args.mask.push([real, shown], [real.toLowerCase(), shown.toLowerCase()], [real.toUpperCase(), shown.toUpperCase()]);
const INITIALS = args.names.map(([real, shown]) => [initials(real), initials(shown)]);
function die(msg) {
console.error(msg);
process.exit(1);
}
const LUCI = `${args.router}/cgi-bin/luci/admin/network/dawnline`;
const USER = process.env.LUCI_USER || 'root';
/*
* Each shot: the page, what must be on it before the capture, what to do
* first (in the page), and the area to keep (in the page, CSS pixels).
* Admin pages keep the theme's header and the content column, 48px either side.
*/
const column = `(() => {
const r = document.querySelector('.dl-root').getBoundingClientRect();
return { x: r.left - 48, w: r.width + 96 };
})()`;
// From the top down to an element; whatever follows it is hidden, not cut through.
const below = (sel) => `(() => {
const c = ${column}, el = document.querySelector(${JSON.stringify(sel)});
for (let e = el; e && !e.classList.contains('dl-root'); e = e.parentElement)
for (let n = e.nextElementSibling; n; n = n.nextElementSibling) n.style.visibility = 'hidden';
return { x: c.x, y: 0, width: c.w, height: el.getBoundingClientRect().bottom + 40 };
})()`;
const SHOTS = [
{
name: 'overview',
url: () => `${LUCI}/server`,
width: 1400,
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');
b?.click();
})()`,
settle: 6000,
clip: below('.dl-srvov .dl-panel.flush'),
},
{
name: 'people',
url: () => `${LUCI}/server?section=people`,
width: 1400,
ready: '.dl-srvbody a[href*="dawnline/person"]',
clip: below('.dl-srvbody'),
},
{
name: 'person',
url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`,
width: 1400,
ready: '.dl-grid-person .dl-row',
// Down to the end of Access & limits; activity rows that would be cut are hidden.
clip: `(() => {
const c = ${column}, cut = document.querySelector('.dl-grid-person > .dl-col:last-child').getBoundingClientRect().bottom + 40;
document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => {
if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden';
});
return { x: c.x, y: 0, width: c.w, height: cut };
})()`,
},
{
name: 'access',
url: () => `${LUCI}/server?section=access`,
width: 1400,
ready: 'section.dl-ifcard details',
// The home network card alone, its folded lists closed.
prep: `(() => {
const card = [...document.querySelectorAll('section.dl-ifcard')].find((s) => s.querySelector('details'));
card.querySelectorAll('details[open]').forEach((d) => (d.open = false));
card.setAttribute('data-shot', '');
})()`,
clip: `(() => {
const r = document.querySelector('[data-shot]').getBoundingClientRect();
return { x: r.left - 12, y: r.top - 12, width: r.width + 24, height: r.height + 24 };
})()`,
},
{
name: 'portal',
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) => {
const doc = new Map();
const isPrivate = (a) => a[0] === 10 || a[0] === 127 || (a[0] === 172 && a[1] >= 16 && a[1] < 32) ||
(a[0] === 192 && a[1] === 168) || (a[0] === 100 && a[1] >= 64 && a[1] < 128) || a[0] === 0 || a[0] >= 224;
const ip = (m) => {
const a = m.split('.').map(Number);
if (a.some((x) => x > 255) || isPrivate(a)) return m;
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
return doc.get(m);
};
const swap = (s) => pairs.reduce((t, [a, b]) => t.split(a).join(b), s).replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip);
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
for (let n; (n = w.nextNode()); ) {
const ini = inits.find(([a]) => n.nodeValue.trim() === a);
const v = ini ? n.nodeValue.replace(ini[0], ini[1]) : swap(n.nodeValue);
if (v !== n.nodeValue) n.nodeValue = v;
}
document.querySelectorAll('input').forEach((i) => { const v = swap(i.value); if (v !== i.value) i.value = v; });
})(${JSON.stringify(args.mask)}, ${JSON.stringify(INITIALS)})`;
async function password() {
if (process.env.LUCI_PASSWORD) return process.env.LUCI_PASSWORD;
if (!process.stdin.isTTY) die('Set LUCI_PASSWORD or run on a terminal');
process.stdout.write(`LuCI password for ${USER}: `);
execFileSync('stty', ['-echo'], { stdio: 'inherit' });
try {
const rl = createInterface({ input: process.stdin });
const line = await new Promise((ok) => rl.once('line', ok));
rl.close();
return line.replace(/\r$/, '');
} finally {
execFileSync('stty', ['echo'], { stdio: 'inherit' });
process.stdout.write('\n');
}
}
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 = [];
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 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 }));
return { send, waitFor, 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' },
);
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');
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
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', { width, height, deviceScaleFactor: SCALE, mobile: false });
await viewport(1400);
await go(`${args.router}/cgi-bin/luci/`);
if (await evaluate(`!!document.querySelector('input[name=luci_password]')`)) {
await evaluate(`(() => {
document.querySelector('input[name=luci_username]').value = ${JSON.stringify(USER)};
document.querySelector('input[name=luci_password]').value = ${JSON.stringify(pass)};
})()`);
const loaded = page.waitFor('Page.loadEventFired');
await evaluate(`document.querySelector('form.login-form, form').submit()`);
await loaded;
if (await evaluate(`!!document.querySelector('input[name=luci_password]')`))
die(
(await evaluate(`!!document.querySelector('.login-error')`))
? `LuCI login failed: wrong password for ${USER} (LUCI_USER sets the user)`
: `LuCI login failed: still on the login page (${await evaluate('location.href')})`,
);
}
// The person to show (the first one on People unless --person) and their personal link.
const s = { person: args.person, portal: '' };
await go(`${LUCI}/server?section=people`);
await 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 waitSel(shot.ready);
await sleep(2000);
if (shot.prep) await evaluate(shot.prep);
await sleep(shot.settle ?? 1500);
await evaluate(MASK);
const clip = await evaluate(shot.clip);
const { data } = await page.send('Page.captureScreenshot', {
format: 'png',
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})`);
}
page.close();
} finally {
chrome.kill();
await sleep(300);
rmSync(profile, { recursive: true, force: true });
}
}
main().catch((e) => die(e.message));
+5 -17
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Compile-check every ucode file on a router without installing anything: # Compile-check every ucode file on a router without installing anything:
# the tree is unpacked under /tmp/dlc and modules are resolved from there. # the tree is unpacked under /tmp/dlc and scripts/compile-ucode.sh runs there
# (the same check CI runs in an OpenWrt rootfs container, scripts/ucode-container.sh).
# scripts/check-ucode.sh [root@host] # scripts/check-ucode.sh [root@host]
set -euo pipefail set -euo pipefail
HOST="${1:-root@outline.lan}" HOST="${1:-root@outline.lan}"
@@ -12,19 +13,6 @@ TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
python3 "$(dirname "$0")/lint-ucode.py" "$ROOT" python3 "$(dirname "$0")/lint-ucode.py" "$ROOT"
( cd "$ROOT" && COPYFILE_DISABLE=1 tar -czf "$TMP/t.tgz" usr etc ) ( cd "$ROOT" && COPYFILE_DISABLE=1 tar -czf "$TMP/t.tgz" usr etc )
scp -q "$TMP/t.tgz" "$HOST:/tmp/dl-check.tgz" scp -q "$TMP/t.tgz" "$HOST:/tmp/dl-check.tgz"
ssh "$HOST" sh <<'REMOTE' ssh "$HOST" 'rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz'
rm -rf /tmp/dlc && mkdir -p /tmp/dlc && tar -xzf /tmp/dl-check.tgz -C /tmp/dlc && rm /tmp/dl-check.tgz # The script goes over stdin (`sh -s`), nothing of it stays on the router.
cd /tmp/dlc ssh "$HOST" 'sh -s /tmp/dlc; rc=$?; rm -rf /tmp/dlc; exit $rc' < "$(dirname "$0")/compile-ucode.sh"
rc=0
for f in usr/share/ucode/dawnline/*.uc; do
n=$(basename "$f" .uc)
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -e "import * as x from 'dawnline.$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline usr/share/dawnline/portal/www/cgi-bin/portal; do
[ -f "$f" ] || continue
out=$(ucode -L '/tmp/dlc/usr/share/ucode/*.uc' -c -o /dev/null "$f" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
rm -rf /tmp/dlc
[ $rc = 0 ] && echo "all ucode files compile"
exit $rc
REMOTE
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Compile-check every ucode file of a Dawnline tree without installing it:
# modules are imported by name (dawnline/x.uc is dawnline.x, dawnline/rpc/x.uc
# dawnline.rpc.x) and entry points compiled with `ucode -c`. Needs ucode with
# its fs, uci, ubus and uloop modules, which is any OpenWrt box or an
# openwrt/rootfs container (scripts/ucode-container.sh); check-ucode.sh pipes
# this script to a router.
# scripts/compile-ucode.sh [ROOT] ROOT holds usr/ and etc/ (default: .)
#
# ucode resolves names at compile time and imports are static, so this catches
# a syntax error, a missing module and a named import that nothing exports.
set -eu
ROOT="$(cd "${1:-.}" && pwd)"
cd "$ROOT"
LIB="$ROOT/usr/share/ucode/*.uc"
rc=0
for f in usr/share/ucode/dawnline/*.uc usr/share/ucode/dawnline/rpc/*.uc; do
[ -f "$f" ] || continue
n=$(echo "${f#usr/share/ucode/}" | sed 's/\.uc$//; s#/#.#g')
out=$(ucode -L "$LIB" -e "import * as x from '$n';" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
# Entry points (ucode scripts outside the module tree); the shell ones live in
# the ShellCheck list of .github/workflows/ci.yml instead.
for f in usr/share/rpcd/ucode/luci.dawnline usr/libexec/dawnline/agent usr/libexec/dawnline/updater usr/bin/dawnline \
usr/share/dawnline/portal/cgi.uc; do
[ -f "$f" ] || { echo "FAIL $f: missing"; rc=1; continue; }
out=$(ucode -L "$LIB" -c -o /dev/null "$f" 2>&1) || { echo "FAIL $f"; echo "$out" | head -8; rc=1; }
done
[ $rc = 0 ] && echo "all ucode files compile"
exit $rc
+9 -6
View File
@@ -1,9 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Put the README screenshots into a browser window on a dawn gradient. """Put the README screenshots into a browser window on a dawn gradient.
Raw captures live in docs/screenshots/raw/<name>.png; the framed images are Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
written to docs/screenshots/<name>.png. Needs a Chromium-based browser for the per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
headless render (BROWSER=/path/to/chrome, default: Brave or Chrome on macOS). are written to docs/screenshots/<name>.png at the same scale. Needs a
Chromium-based browser for the headless render (BROWSER=/path/to/chrome,
default: Brave or Chrome on macOS).
Run: scripts/frame-screenshots.py Run: scripts/frame-screenshots.py
""" """
import os import os
@@ -23,9 +25,10 @@ SHOTS = {
'people': 'router.lan · Dawnline · People', 'people': 'router.lan · Dawnline · People',
'person': 'router.lan · Dawnline · Myata', 'person': 'router.lan · Dawnline · Myata',
'portal': 'vpn.example.com/kamiro-telosu-bavine', 'portal': 'vpn.example.com/kamiro-telosu-bavine',
'map': 'router.lan · Dawnline · Overview', 'access': 'router.lan · Dawnline · Home · Access',
} }
PAD_X, PAD_Y, BAR = 120, 96, 40 PAD_X, PAD_Y, BAR = 120, 96, 40
SCALE = 2
CANDIDATES = [ CANDIDATES = [
os.environ.get('BROWSER', ''), os.environ.get('BROWSER', ''),
@@ -74,7 +77,7 @@ def main():
if not os.path.exists(src): if not os.path.exists(src):
print(f'skip {name}: no raw capture') print(f'skip {name}: no raw capture')
continue continue
iw, ih = png_size(src) iw, ih = (v // SCALE for v in png_size(src))
w, h = iw + 2 * PAD_X, ih + BAR + 2 * PAD_Y w, h = iw + 2 * PAD_X, ih + BAR + 2 * PAD_Y
html = os.path.join(tmp, f'{name}.html') html = os.path.join(tmp, f'{name}.html')
with open(html, 'w', encoding='utf-8') as f: with open(html, 'w', encoding='utf-8') as f:
@@ -82,7 +85,7 @@ def main():
gw=int(w * .8), gh=int(h * .5), gw2=int(w * .6), gh2=int(h * .45))) gw=int(w * .8), gh=int(h * .5), gw2=int(w * .6), gh2=int(h * .45)))
out = os.path.join(OUT, f'{name}.png') out = os.path.join(OUT, f'{name}.png')
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files', subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
'--force-device-scale-factor=1', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'], f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f'{name}: {w}x{h}') print(f'{name}: {w}x{h}')
shutil.rmtree(tmp) shutil.rmtree(tmp)
+133 -15
View File
@@ -3,46 +3,164 @@
ucode resolves names where they are used: calling a function that is declared ucode resolves names where they are used: calling a function that is declared
further down the same file fails at runtime ("access to undeclared variable"). further down the same file fails at runtime ("access to undeclared variable").
Also: calls and named imports must match what a Dawnline module exports, the
rpcd methods (dawnline.rpc.*) must match the plugin and its ACL, and regexes
stay POSIX (rules/backend.md). Imports against the module layering are
reported as notes, not failures.
Run: scripts/lint-ucode.py [package root] Run: scripts/lint-ucode.py [package root]
""" """
import glob import glob
import json
import os import os
import re import re
import sys import sys
root = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '..', 'package', 'luci-app-dawnline', 'root') root = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '..', 'package', 'luci-app-dawnline', 'root')
files = glob.glob(f"{root}/usr/share/ucode/dawnline/*.uc") + [ MODDIR = f"{root}/usr/share/ucode/dawnline"
f"{root}/usr/share/rpcd/ucode/luci.dawnline", PLUGIN = f"{root}/usr/share/rpcd/ucode/luci.dawnline"
ACL = f"{root}/usr/share/rpcd/acl.d/luci-app-dawnline.json"
modules = sorted(glob.glob(f"{MODDIR}/*.uc") + glob.glob(f"{MODDIR}/rpc/*.uc"))
files = modules + [
PLUGIN,
f"{root}/usr/libexec/dawnline/agent", f"{root}/usr/libexec/dawnline/agent",
f"{root}/usr/libexec/dawnline/updater", f"{root}/usr/libexec/dawnline/updater",
f"{root}/usr/libexec/dawnline/resolver",
f"{root}/usr/bin/dawnline", f"{root}/usr/bin/dawnline",
f"{root}/usr/share/dawnline/portal/www/cgi-bin/portal", f"{root}/usr/share/dawnline/portal/cgi.uc",
] ]
files = [f for f in files if os.path.exists(f)]
bad = 0 bad = 0
checked = 0
def problem(msg):
global bad
print(msg)
bad = 1
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)
# A regex literal on one line: `/…/` with no slash inside, followed by flags or
# a delimiter (so a division keeps out). Good enough for how Dawnline writes them.
REGEX_LITERAL = re.compile(r'(?<![\w)\]])/((?:\\.|[^/\\\n])+)/[gis]*(?=[,);\s])')
def modname(path):
"""dawnline/rpc/people.uc → 'rpc.people' (as in import … from 'dawnline.rpc.people')."""
rel = os.path.relpath(path, MODDIR)[:-3]
return rel.replace(os.sep, '.')
for f in files: for f in files:
if not os.path.exists(f): code = strip_comments(open(f, encoding='utf-8').read())
continue
checked += 1
code = re.sub(r'//[^\n]*|/\*.*?\*/', '', open(f, encoding='utf-8').read(), flags=re.S)
defs = {m.group(1): m.start() for m in re.finditer(r'^(?:export )?function (\w+)\(', code, re.M)} defs = {m.group(1): m.start() for m in re.finditer(r'^(?:export )?function (\w+)\(', code, re.M)}
for name, pos in defs.items(): for name, pos in defs.items():
for m in re.finditer(r'(?<![\w.\'"`])' + name + r'\(', code[:pos]): for m in re.finditer(r'(?<![\w.\'"`])' + name + r'\(', code[:pos]):
line = code[: m.start()].count('\n') + 1 line = code[: m.start()].count('\n') + 1
print(f"{f}:{line}: {name}() is used before its definition") problem(f"{f}:{line}: {name}() is used before its definition")
bad = 1
# In a module an exported function is an expression statement: its closing # In a module an exported function is an expression statement: its closing
# brace needs a semicolon ("Expecting ';'" breaks the whole module). # brace needs a semicolon ("Expecting ';'" breaks the whole module).
lines = open(f, encoding='utf-8').read().split('\n') lines = blank_comments(open(f, encoding='utf-8').read()).split('\n')
inside = None inside = None
for n, text in enumerate(lines, 1): for n, text in enumerate(lines, 1):
if inside is None and re.match(r'^export function \w+\(', text): if inside is None and re.match(r'^export function \w+\(', text):
inside = n inside = n
elif inside is not None and re.match(r'^}', text): elif inside is not None and re.match(r'^}', text):
if not text.startswith('};'): if not text.startswith('};'):
print(f"{f}:{n}: exported function from line {inside} must end with '}};'") problem(f"{f}:{n}: exported function from line {inside} must end with '}};'")
bad = 1
inside = None inside = None
print(f"lint-ucode: {checked} files checked" + (", problems found" if bad else ", ok")) # ucode regexes are POSIX: a (?: group fails when the line runs ("Repetition
# not preceded by valid expression"), and let [a, b] = … does not compile.
if re.search(r'/[^/\n]*\(\?[:=!][^/\n]*/', text):
problem(f"{f}:{n}: ucode regexes are POSIX: no (?: (?= (?! groups")
# Lazy quantifiers (*? +? }?) and the [\s\S] class are PCRE: the C
# library's regcomp does something else with them or rejects them.
for m in REGEX_LITERAL.finditer(text):
body = m.group(1)
if re.search(r'(?<!\\)[*+}]\?', body):
problem(f"{f}:{n}: ucode regexes are POSIX: no lazy quantifiers (*? +? }}?) in /{body}/")
if re.search(r'\[\\[sS]\\[sS]\]', body):
problem(f"{f}:{n}: ucode regexes are POSIX: no [\\s\\S] class in /{body}/ (use (.|\\n) or a negated class)")
if re.match(r'\s*(let|const)\s*[\[{]', text):
problem(f"{f}:{n}: ucode has no destructuring")
# Calls into another Dawnline module (alias.fn(...)) and named imports must name
# something it exports: one removed from a module but still used elsewhere only
# fails at runtime.
exports = {}
for f in modules:
text = open(f, encoding='utf-8').read()
exports[modname(f)] = set(re.findall(r'^export (?:function|const|let) (\w+)', text, re.M))
for f in files:
code = strip_comments(open(f, encoding='utf-8').read())
for alias, mod in re.findall(r"import \* as (\w+) from 'dawnline\.([\w.]+)'", code):
if mod not in exports:
problem(f"{f}: imports dawnline.{mod}, which does not exist")
continue
# Calls, and constants (upper case: a lower-case "geo.json" in a string is no access).
for m in re.finditer(r'(?<![\w.])' + alias + r'\.(\w+\(|[A-Z][A-Z0-9_]*\b)', code):
name = m.group(1).rstrip('(')
if name not in exports[mod]:
line = code[: m.start()].count('\n') + 1
problem(f"{f}:{line}: {alias}.{name} is not exported by dawnline.{mod}")
for names, mod in re.findall(r"import \{([^}]*)\} from 'dawnline\.([\w.]+)'", code):
if mod not in exports:
problem(f"{f}: imports dawnline.{mod}, which does not exist")
continue
for name in re.split(r'\s*,\s*', names.strip()):
name = re.split(r'\s+as\s+', name)[0].strip()
if name and name not in exports[mod]:
problem(f"{f}: {name} is not exported by dawnline.{mod}")
# rpcd methods: every rpc module's `methods` is merged by the plugin, no name is
# defined twice (the later one would silently win), and the ACL's read list
# names methods that exist.
methods = {}
for f in glob.glob(f"{MODDIR}/rpc/*.uc"):
text = strip_comments(open(f, encoding='utf-8').read())
m = re.search(r'^export const methods = \{\n(.*?)^\};', text, re.M | re.S)
if not m:
continue
mod = modname(f)
if os.path.exists(PLUGIN) and f"from 'dawnline.{mod}'" not in open(PLUGIN, encoding='utf-8').read():
problem(f"{PLUGIN}: does not import dawnline.{mod}, whose methods would be missing")
for name in re.findall(r"^\t'?(\w+)'?: \{", m.group(1), re.M):
if name in methods:
problem(f"{f}: method {name} is also defined in dawnline.{methods[name]}")
methods[name] = mod
if methods and os.path.exists(ACL):
acl = json.load(open(ACL, encoding='utf-8'))['luci-app-dawnline']
for kind in ('read', 'write'):
for name in acl.get(kind, {}).get('ubus', {}).get('luci.dawnline', []):
if name != '*' and name not in methods:
problem(f"{ACL}: {kind} lists {name}, which no dawnline.rpc module defines")
if 'uci' in acl.get(kind, {}) and 'dawnline' in acl[kind]['uci']:
problem(f"{ACL}: {kind} grants uci 'dawnline' (private keys, no validation): use the rpc methods")
# Layering (rules/backend.md): util, schema → core → store → domain modules →
# apply → entry points. A module importing one from a layer above it is
# reported, not failed, until the existing edges are untangled.
LAYER = {'util': 0, 'schema': 1, 'core': 2, 'store': 3, 'apply': 5}
LAYER_NAME = {0: 'util', 1: 'schema', 2: 'core', 3: 'store', 4: 'domain', 5: 'apply'}
notes = 0
for f in modules:
mod = modname(f)
if mod.startswith('rpc.'):
continue # an entry point: may import anything
mine = LAYER.get(mod, 4)
for dep in re.findall(r"from 'dawnline\.([\w.]+)'", strip_comments(open(f, encoding='utf-8').read())):
theirs = LAYER.get(dep, 4)
if theirs > mine or (theirs == mine and mine < 4 and dep != mod):
print(f"note: {f}: {mod} ({LAYER_NAME[mine]}) imports dawnline.{dep} ({LAYER_NAME[theirs]}), a layer above it")
notes += 1
if notes:
print(f"lint-ucode: {notes} layering notes (not failures)")
print(f"lint-ucode: {len(files)} files checked" + (", problems found" if bad else ", ok"))
sys.exit(bad) sys.exit(bad)
+72
View File
@@ -0,0 +1,72 @@
#!/bin/sh
# shellcheck shell=dash
#
# Release notes for a tag, from the commits since the previous tag:
# scripts/release-notes.sh v0.3.1 [repository]
# PREV_TAG=v0.1.1 scripts/release-notes.sh v0.3.0 (compare with another tag)
#
# Release commits ("Dawnline 0.3.1") list their changes as "- " lines in the
# body: those become the points. Other commits add their title; merges are
# skipped. Wrapped points are joined into one line, so the Components tab
# (and anything else reading the release) gets one change per line.
set -eu
TAG="${1:?usage: release-notes.sh <tag> [owner/repo]}"
REPO="${2:-tickcount/luci-app-dawnline}"
git rev-parse -q --verify "$TAG^{commit}" >/dev/null || {
echo "release-notes: no tag $TAG" >&2
exit 1
}
# The previous release: the nearest older tag, or PREV_TAG when a tag was never published.
PREV="${PREV_TAG:-$(git describe --tags --abbrev=0 --match 'v[0-9]*' "$TAG^" 2>/dev/null || true)}"
if [ -n "$PREV" ] && ! git rev-parse -q --verify "$PREV^{commit}" >/dev/null; then
echo "release-notes: no tag $PREV" >&2
exit 1
fi
RANGE="$TAG"
[ -n "$PREV" ] && RANGE="$PREV..$TAG"
# git log runs alone first: a failure must stop the script, not vanish into the pipe.
git log --no-merges --format='%s' "$RANGE" >/dev/null
# One record per commit, newest first: the subject, then the body; records end with RS (\036).
points="$(git log --no-merges --format='%s%n%b%x1e' "$RANGE" | awk '
BEGIN { RS = "\036" }
{
n = split($0, line, "\n")
title = ""
for (i = 1; i <= n; i++) if (line[i] != "") { title = line[i]; start = i + 1; break }
if (title == "") next
got = 0; cur = ""
for (i = start; i <= n; i++) {
if (line[i] ~ /^[ \t]*[-*][ \t]+/) {
if (cur != "") { print "- " cur; got = 1 }
cur = line[i]; sub(/^[ \t]*[-*][ \t]+/, "", cur)
} else if (cur != "" && line[i] ~ /^[ \t]+[^ \t]/) {
l = line[i]; sub(/^[ \t]+/, "", l); cur = cur " " l
} else if (cur != "") { print "- " cur; got = 1; cur = "" }
}
if (cur != "") { print "- " cur; got = 1 }
# A release commit without a list says nothing new; any other commit is its title.
if (!got && title !~ /^(Dawnline )?v?[0-9]+\.[0-9]+(\.[0-9]+)?$/) print "- " title
}')"
if [ -n "$points" ]; then
printf "## What’s new\n\n%s\n\n" "$points"
fi
cat <<EOF
## Install
Install or upgrade on the router (OpenWrt 24.10 with opkg, or 25.12 with apk):
\`\`\`sh
sh -c "\$(wget -qO- https://raw.githubusercontent.com/$REPO/main/install.sh)"
\`\`\`
Or update from LuCI → Network → Dawnline → Components.
EOF
if [ -n "$PREV" ]; then
printf '\n**Full Changelog**: https://github.com/%s/compare/%s...%s\n' "$REPO" "$PREV" "$TAG"
else
printf '\n**Full Changelog**: https://github.com/%s/commits/%s\n' "$REPO" "$TAG"
fi
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Run the ucode checks the way CI does: in an OpenWrt rootfs container with the
# release's own ucode and libuci — compile every file (compile-ucode.sh), then
# the unit tests (tests/ucode/run.sh). Needs docker; the repository is mounted
# read-only at /src, the container is thrown away.
# scripts/ucode-container.sh [24.10|25.12|all] [test name filter]
#
# Images are the x86-64 rootfs of the OpenWrt releases the packages are built
# for (build/Dockerfile, scripts/build-packages.sh), pinned by digest so a
# retagged image cannot change what CI runs. To move to a new release change
# the tag and the digest together (docker buildx imagetools inspect <image>).
set -euo pipefail
REPO="$(cd "$(dirname "$0")/.." && pwd)"
image_for() {
case "$1" in
24.10) echo 'openwrt/rootfs:x86-64-24.10.6@sha256:fd76f3afb9c390ef2915618b6e3d7187698c03ecc6c23d3a13f12b62d9c6209e' ;;
25.12) echo 'openwrt/rootfs:x86-64-25.12.3@sha256:af882e0583954fc2ceac6b081a9d214fc739cfea36a29b48795a5f15563aa3b5' ;;
*) echo "unknown release $1 (24.10 or 25.12)" >&2; exit 2 ;;
esac
}
releases="${1:-all}"
[ "$releases" = all ] && releases='24.10 25.12'
rc=0
for rel in $releases; do
image="$(image_for "$rel")"
echo "== OpenWrt $rel ($image)"
# The checks run from this stdin script (`sh -s`): ucode-mod-uloop is not in
# the 24.10 rootfs, so what is missing is installed from the release's feeds.
docker run --rm -i --platform linux/amd64 -v "$REPO:/src:ro" -e "FILTER=${2:-}" "$image" sh -s <<-'INNER' || rc=1
set -eu
missing=''
command -v ucode >/dev/null || missing='ucode'
for m in fs uci ubus uloop; do
[ -e "/usr/lib/ucode/$m.so" ] || missing="$missing ucode-mod-$m"
done
if [ -n "$missing" ]; then
echo "installing:$missing"
if command -v apk >/dev/null; then
# shellcheck disable=SC2086
apk add --quiet $missing
else
mkdir -p /var/lock
# shellcheck disable=SC2086
opkg update >/dev/null && opkg install $missing >/dev/null
fi
fi
sh /src/scripts/compile-ucode.sh /src/package/luci-app-dawnline/root
sh /src/tests/ucode/run.sh /src "$FILTER"
INNER
done
exit $rc
+96
View File
@@ -0,0 +1,96 @@
// dawnline.awg: disguise presets against their own validation, and 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).
import { readfile, writefile, unlink } from 'fs';
import * as awg from 'dawnline.awg';
const AWG_DUMP = '/tmp/dawnline-tests/awg-dump';
let fixtures = sourcepath(0, true) + '/fixtures';
test('obf_preset off', () => {
let o = awg.obf_preset('off');
eq(o, { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' }, 'plain WireGuard headers');
eq(awg.obf_errors(o), [], 'valid');
});
test('obf_preset balanced', () => {
for (let i = 0; i < 25; i++) {
let o = awg.obf_preset('balanced');
eq(awg.obf_errors(o), [], 'balanced is valid');
ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`);
let jmin = +o.jmin, jmax = +o.jmax;
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `junk sizes ${o.jmin}-${o.jmax}`);
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
ok(+o[k] >= 5, `${k} above the reserved values`);
ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`);
ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets');
eq(o.header_protection_key, null, 'no 3.1 values');
}
});
test('obf_preset max', () => {
let o = awg.obf_preset('max');
eq(o.header_protection_key, 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=', 'key from 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');
ok(substr(o.i2, 0, 3) == '<r ', 'DNS-answer second packet');
// The template varies by name length and top-level domain (the letters
// themselves are random at run time): over many servers, more than one shape.
let shapes = {};
for (let i = 0; i < 20; i++)
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');
});
test('obf_errors', () => {
eq(awg.obf_errors({}), [], 'nothing set');
eq(awg.obf_errors({ jc: '11' }), [ 'jc=11 (0-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_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');
});
function dump_of(name) {
writefile(AWG_DUMP, readfile(`${fixtures}/awg-dump-${name}.txt`));
return awg.dump();
}
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');
});
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');
});
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(length(d.peers), 2, 'two peers');
});
test('dump: the tool fails', () => {
unlink(AWG_DUMP);
let d = awg.dump();
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
});
+166
View File
@@ -0,0 +1,166 @@
// 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.
import * as core from 'dawnline.core';
// A local time that no time zone turns into another day.
function at(y, mo, d, h, mi) {
return timelocal({ year: y, mon: mo, mday: d, hour: h, min: mi, sec: 0 });
}
let m = core.load();
test('load reads the fixture', () => {
eq(keys(m.servers), [ 'main' ], 'servers');
eq(sort(keys(m.people)), [ 'alice', 'bob' ], 'people');
eq(m.servers.main.subnet, '10.9.0.0/29', 'subnet');
eq(m.servers.main.mtu, 1380, 'stored MTU');
eq(m.servers.main.obf, { jc: '4', jmin: '64', jmax: '128', s4: '12' }, 'disguise values as strings');
eq(m.servers.main.mesh, 'all', 'mesh default');
eq(m.people.alice.devices, [ 'alice_phone' ], 'devices attached to their person');
eq(m.people.alice.access, 'both', 'access');
eq(m.people.bob.access, 'internet', 'access default');
eq(m.people.bob.quota_gb, 2, 'quota as a number');
eq(m.people.bob.device_limit, 3, 'device limit from the settings default');
eq(m.devices.alice_phone.kind, 'phone', 'kind');
eq(m.settings.portal_enabled, true, 'bool setting');
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');
});
test('parse_hours', () => {
eq(core.parse_hours('07:00-23:00'), [ 420, 1380 ], 'day window');
eq(core.parse_hours('23:00-07:00'), [ 1380, 420 ], 'overnight window');
eq(core.parse_hours('7:00-23:00'), [ 420, 1380 ], 'one-digit hour');
eq(core.parse_hours('00:00-24:00'), [ 0, 1440 ], 'whole day');
eq(core.parse_hours('24:00-01:00'), null, 'start at 24:00');
eq(core.parse_hours('10:00-10:00'), null, 'empty window');
eq(core.parse_hours('always'), null, 'words');
eq(core.parse_hours(''), null, 'empty');
eq(core.parse_hours(null), null, 'null');
});
test('person_quota', () => {
let march = at(2026, 3, 10, 12, 0);
eq(core.person_quota({ quota_gb: 0 }, march), 0, 'unlimited');
eq(core.person_quota({ quota_gb: 2 }, march), 2147483648, '2 GiB');
eq(core.person_quota({ quota_gb: 2, bonus_gb: 1, bonus_month: '2026-03' }, march), 3221225472, 'bonus this month');
eq(core.person_quota({ quota_gb: 2, bonus_gb: 1, bonus_month: '2026-02' }, march), 2147483648, 'bonus of another month');
eq(core.person_quota({ quota_gb: -1 }, march), 0, 'negative is unlimited');
});
test('person_usage', () => {
let march = at(2026, 3, 10, 12, 0);
let usage = { people: { bob: { total: [ 100, 50 ], months: { '2026-03': [ 10, 5 ], '2026-02': [ 1000, 1000 ] } } } };
eq(core.person_usage({ id: 'bob', quota_period: 'month' }, usage, march), 15, 'this month');
eq(core.person_usage({ id: 'bob', quota_period: 'month' }, usage, at(2026, 4, 1, 0, 0)), 0, 'a month without traffic');
eq(core.person_usage({ id: 'bob', quota_period: 'total' }, usage, march), 150, 'total');
eq(core.person_usage({ id: 'nobody', quota_period: 'month' }, usage, march), 0, 'unknown person');
eq(core.person_usage({ id: 'bob' }, null, march), 0, 'no usage data');
});
test('own_state', () => {
let base = { id: 'p', paused: false, expires: '', expire_action: 'pause', quota_gb: 0, hours: '' };
let noon = at(2026, 3, 10, 12, 0);
eq(core.own_state(m, base, null, noon), 'active', 'nothing set');
eq(core.own_state(m, { ...base, paused: true }, null, noon), 'paused', 'paused');
eq(core.own_state(m, { ...base, expires: '2026-03-09' }, null, noon), 'expired', 'expired yesterday');
eq(core.own_state(m, { ...base, expires: '2026-03-10' }, null, noon), 'active', 'expires at the end of today');
eq(core.own_state(m, { ...base, expires: '2026-03-09', expire_action: 'notify' }, null, noon), 'active', 'notify keeps access');
let usage = { people: { p: { months: { '2026-03': [ 600000000, 600000000 ] } } } };
eq(core.own_state(m, { ...base, quota_gb: 1 }, usage, noon), 'quota', 'over quota');
eq(core.own_state(m, { ...base, quota_gb: 1, bonus_gb: 1, bonus_month: '2026-03' }, usage, noon), 'active', 'bonus lifts the quota');
eq(core.own_state(m, { ...base, quota_gb: 1 }, usage, at(2026, 4, 1, 0, 0)), 'active', 'a new month resets the usage');
eq(core.own_state(m, { ...base, hours: '09:00-17:00' }, null, noon), 'active', 'inside the hours');
eq(core.own_state(m, { ...base, hours: '09:00-17:00' }, null, at(2026, 3, 10, 20, 0)), 'hours', 'outside the hours');
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, at(2026, 3, 10, 23, 0)), 'active', 'overnight, before midnight');
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, at(2026, 3, 10, 5, 59)), 'active', 'overnight, after midnight');
eq(core.own_state(m, { ...base, hours: '22:00-06:00' }, null, noon), 'hours', 'overnight, daytime');
eq(core.own_state(m, { ...base, paused: true, expires: '2000-01-01' }, null, noon), 'paused', 'paused wins over expired');
eq(core.own_state(m, { ...base, expires: '2000-01-01', quota_gb: 1 }, usage, noon), 'expired', 'expired wins over quota');
});
test('person_state', () => {
let noon = at(2026, 3, 10, 12, 0);
let p = { id: 'p', server: 'main', paused: false, expires: '', expire_action: 'pause', quota_gb: 0, hours: '' };
eq(core.person_state(m, p, null, noon), 'active', 'server on');
eq(core.person_state(m, { ...p, server: 'gone' }, null, noon), 'no_server', 'no server');
let off = { servers: { main: { ...m.servers.main, enabled: false } } };
eq(core.person_state(off, p, null, noon), 'server_off', 'server off');
eq(core.person_state(off, { ...p, paused: true }, null, noon), 'server_off', 'server off is about the server');
ok(core.person_expired({ expires: '2000-01-01' }, noon), 'person_expired');
ok(!core.person_expired({ expires: '' }, noon), 'no end date');
ok(!core.person_expired({ expires: 'garbage' }, noon), 'bad date is not expired');
});
test('alloc_address', () => {
let srv = { id: 'main', subnet: '10.9.0.0/29' };
let other = { id: 'other', subnet: '10.9.1.0/29' };
let model = (addrs) => {
let mm = { servers: { main: srv, other }, people: { a: { server: 'main' }, o: { server: 'other' } }, devices: {} };
for (let i, a in addrs)
mm.devices[`d${i}`] = { person: 'a', address: a };
return mm;
};
eq(core.alloc_address(model([]), srv), '10.9.0.2', 'router has the first host');
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.3' ]), srv), '10.9.0.4', 'next free');
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.4' ]), srv), '10.9.0.3', 'lowest gap');
eq(core.alloc_address(model([ '10.9.0.2', '10.9.0.3', '10.9.0.4', '10.9.0.5', '10.9.0.6' ]), srv), null, 'exhausted (.7 is broadcast)');
eq(core.alloc_address(model([ '10.9.0.2', 'garbage' ]), srv), '10.9.0.3', 'a broken address is ignored');
let mm = model([]);
mm.devices.x = { person: 'o', address: '10.9.0.2' };
eq(core.alloc_address(mm, srv), '10.9.0.2', 'another server\'s devices do not count');
eq(core.alloc_address(model([]), { id: 'main', subnet: 'nonsense' }), null, 'no subnet');
eq(core.server_address(srv), '10.9.0.1', 'server_address');
eq(core.tunnels({ ...srv, ifname: 'awgmain', private_key: 'k' }), [ { ifname: 'awgmain', subnet: '10.9.0.0/29', address: '10.9.0.1' } ], 'tunnels');
eq(core.tunnels({ ...srv, ifname: 'awgmain' }), [], 'no key, no tunnel');
eq(core.tunnels({ ...srv, ifname: 'awgmain', private_key: 'k', blocked: 'taken' }), [], 'blocked interface');
eq(core.tunnels({ ...srv, ifname: 'awg-main', private_key: 'k' }), [], 'bad interface name');
});
test('tunnel_mtu / device_mtu', () => {
eq(core.tunnel_mtu({ mtu: 1420 }), 1420, 'set by hand');
eq(core.tunnel_mtu({ mtu: 0, obf: {} }), 1380, 'automatic');
eq(core.tunnel_mtu({ mtu: 0 }), 1380, 'automatic without disguise');
eq(core.tunnel_mtu({ mtu: 0, obf: { s4: '12' } }), 1368, 'S4 taken off');
eq(core.tunnel_mtu({ mtu: 0, obf: { s4: '100' } }), 1280, 'never below 1280');
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');
});
test('names and codes', () => {
ok(core.valid_ifname('awgmain') && core.valid_ifname('a') && core.valid_ifname('awg_1'), 'interface names');
ok(!core.valid_ifname('Awg') && !core.valid_ifname('1awg') && !core.valid_ifname('awg-main') && !core.valid_ifname('awgmain123456'), 'bad interface names');
for (let i = 0; i < 20; i++)
ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code');
});
test('renumber_server', () => {
let srv = { id: 'main', name: 'Main', subnet: '10.9.0.0/29' };
let mm = {
servers: { main: srv, other: { id: 'other', subnet: '10.9.1.0/29' } },
people: { a: { server: 'main', devices: [ 'a1', 'a2' ] }, o: { server: 'other', devices: [ 'o1' ] } },
devices: { a1: { person: 'a', address: '10.9.0.5' }, a2: { person: 'a', address: '10.9.0.3' }, o1: { person: 'o', address: '10.9.1.2' } },
};
let set = {};
let c = { set: (cfg, s, k, v) => { set[`${s}.${k}`] = v; }, delete: () => {} };
core.renumber_server(c, mm, srv, '10.77.0.0/24');
eq(srv.subnet, '10.77.0.0/24', 'the server moves');
eq([ mm.devices.a1.address, mm.devices.a2.address ], [ '10.77.0.2', '10.77.0.3' ], 'devices renumbered lowest first');
eq(mm.devices.o1.address, '10.9.1.2', 'another server untouched');
eq(set, { 'a1.address': '10.77.0.2', 'a2.address': '10.77.0.3', 'main.subnet': '10.77.0.0/24' }, 'written to uci');
let err = null;
try { core.renumber_server(c, mm, srv, '10.9.2.0/30'); } catch (e) { err = e; }
ok(err != null, 'refuses a subnet too small for the devices');
});
test('device_labels', () => {
let mm = { devices: {
a: { id: 'a', name: 'iPhone', created: 1 }, b: { id: 'b', name: 'iPhone!', created: 2 },
c: { id: 'c', name: 'Телефон', created: 3 }, d: { id: 'd', name: 'телефон', created: 4 },
} };
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
});
+3
View File
@@ -0,0 +1,3 @@
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 1234567 2345678 3456789 4567890
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
awgmain TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= (none) (none) 10.9.0.3/32 0 0 0 off
+2
View File
@@ -0,0 +1,2 @@
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 12 12 1234567 2345678 3456789 4567890 <b 0xdead>
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
+3
View File
@@ -0,0 +1,3 @@
awgmain yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg= 51820 off 4 64 128 20 40 12 12 1234567 2345678 3456789 4567890 <r 2><b 0x858000010001> yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= 10-100 on on
awgmain HIgo9xNzJMWLKASShiTqIybxZ0U3wGLiUeJ1PKf8ykw= (none) 203.0.113.7:41821 10.9.0.2/32 1760000000 123456 654321 off
awgmain TrMvSoP4jYQlY6RIzBgbssQqY3vxI2Pi+y71lOWWXX0= (none) (none) 10.9.0.3/32 0 0 0 off
+10
View File
@@ -0,0 +1,10 @@
#!/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.
case "$1 ${2:-} ${3:-}" in
'genkey ') echo 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=' ;;
'show all dump') cat /tmp/dawnline-tests/awg-dump ;;
*) echo "awg stand-in: unsupported arguments: $*" >&2; exit 1 ;;
esac
+43
View File
@@ -0,0 +1,43 @@
# Test fixture: a small installation (one server, two people, one device).
# migrate.test.uc expects bob's random code, the server's stored MTU 1380 and
# uhttpd's error_page: the one-time steps remove them.
config settings 'settings'
option portal_enabled '1'
option portal_port '8443'
option portal_host 'vpn.example.com'
option log_connections '0'
option update_interval '7d'
list update_targets 'app'
config server 'main'
option name 'Main'
option ifname 'awgmain'
option port '51820'
option subnet '10.9.0.0/29'
option private_key 'yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk='
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
option mtu '1380'
option jc '4'
option jmin '64'
option jmax '128'
option s4 '12'
config person 'alice'
option server 'main'
option name 'Alice'
option code 'abcdef-ghijkl-mnopqr'
option access 'both'
config person 'bob'
option server 'main'
option name 'Bob'
option code 'XyZ12345'
option quota_gb '2'
config device 'alice_phone'
option person 'alice'
option name 'Phone'
option kind 'phone'
option address '10.9.0.2'
option public_key 'xTIBA5rboUvnH4htodjb6e697QjLERt1NAB4mZqp8Dg='
+8
View File
@@ -0,0 +1,8 @@
# Test fixture: LuCI's web server as versions before 0.4 left it, with the
# portal as its error page (migrate.uhttpd removes that).
config uhttpd 'main'
list listen_http '0.0.0.0:80'
list listen_https '0.0.0.0:443'
option home '/www'
option error_page '/cgi-bin/dawnline-portal'
+50
View File
@@ -0,0 +1,50 @@
// dawnline.live: event categories and the retention policy, from a settings
// object and from the fixture config (real libuci).
import * as live from 'dawnline.live';
test('category_of', () => {
eq(live.category_of('connect'), 'connections', 'connect');
eq(live.category_of('roam'), 'connections', 'roam');
eq(live.category_of('device_added'), 'people', 'device events are people events');
eq(live.category_of('person_changed'), 'people', 'person');
eq(live.category_of('server_down'), 'problems', 'server');
eq(live.category_of('something_new'), 'problems', 'unknown types are problems');
});
test('policy defaults', () => {
eq(live.policy({}), { keep_days: 30, max: 2000, categories: [ 'connections', 'people', 'problems' ],
persist: 'hourly', usage_days: 62, usage_months: 24 }, 'empty settings');
});
test('policy categories', () => {
eq(live.policy({ log_connections: '0' }).categories, [ 'people', 'problems' ], 'old switch');
eq(live.policy({ log_category: 'devices, problems' }).categories, [ 'people', 'problems' ], 'string list, devices renamed');
eq(live.policy({ log_category: [ 'connections', 'bogus', 'connections' ] }).categories, [ 'connections' ], 'list, unknown and repeats dropped');
eq(live.policy({ log_category: [], log_connections: '0' }).categories, [], 'explicit empty list wins');
});
// Ranges come from dawnline.schema: a stored value outside them (an older
// version, a hand edit) reads as the default, as settings_update would have refused it.
test('policy ranges', () => {
eq(live.policy({ log_max: '50' }).max, 2000, 'max below the floor: default');
eq(live.policy({ log_max: '99999' }).max, 2000, 'max above the ceiling: default');
eq(live.policy({ log_max: '150' }).max, 150, 'max in range');
eq(live.policy({ log_max: 'abc' }).max, 2000, 'bad max');
eq(live.policy({ log_keep_days: '0' }).keep_days, 0, 'keep forever');
eq(live.policy({ log_keep_days: '-3' }).keep_days, 30, 'negative days');
eq(live.policy({ log_persist: '10min' }).persist, '10min', 'persist');
eq(live.policy({ log_persist: 'daily' }).persist, 'hourly', 'bad persist');
eq(live.policy({ usage_keep_days: '1' }).usage_days, 62, 'usage days below the floor: default');
eq(live.policy({ usage_keep_months: '500' }).usage_months, 24, 'usage months above the ceiling: default');
});
test('policy from the config', () => {
eq(live.policy(null).categories, [ 'people', 'problems' ], 'fixture turns connections off');
eq(live.policy(null).max, 2000, 'default where the fixture says nothing');
});
test('endpoint_ip', () => {
eq(live.endpoint_ip('203.0.113.7:41821'), '203.0.113.7', 'v4');
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
eq(live.endpoint_ip(''), '', 'none');
});
+44
View File
@@ -0,0 +1,44 @@
// dawnline.migrate: the one-time steps on the fixture config (real libuci):
// each changes what it must the first time and nothing the second time.
// This test rewrites /etc/config/dawnline and /etc/config/uhttpd.
import { cursor } from 'uci';
import { stat } from 'fs';
import * as core from 'dawnline.core';
import * as migrate from 'dawnline.migrate';
function conf(name) {
let c = cursor();
c.load(name);
return c;
}
test('before: the fixture holds the old state', () => {
let c = conf('dawnline');
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
});
test('run: the steps change what they must', () => {
migrate.run();
let c = conf('dawnline');
ok(match(c.get('dawnline', 'bob', 'code'), core.WORD_CODE), 'bob has a word code');
eq(c.get('dawnline', 'alice', 'code'), 'abcdef-ghijkl-mnopqr', 'alice keeps hers');
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
user_read: true, user_write: true, user_exec: false,
group_read: false, group_write: false, group_exec: false,
other_read: false, other_write: false, other_exec: false }, 'config stays private');
});
test('run again: a step runs once', () => {
let before = conf('dawnline').get('dawnline', 'bob', 'code');
let mtime = stat('/etc/config/dawnline').mtime;
migrate.run();
eq(conf('dawnline').get('dawnline', 'bob', 'code'), before, 'the code is not drawn again');
eq(stat('/etc/config/dawnline').mtime, mtime, 'nothing written');
});
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
# Run the ucode unit tests against the real libuci: the fixture configs are
# copied into /etc/config (replacing what is there), the stand-in `awg` goes on
# PATH and tests/ucode/run.uc runs every *.test.uc. For a throw-away OpenWrt
# rootfs container (scripts/ucode-container.sh); on anything else it refuses
# unless DAWNLINE_TEST_FORCE=1, because it overwrites /etc/config/dawnline.
# tests/ucode/run.sh [REPO] [test name filter]
set -eu
REPO="$(cd "${1:-$(dirname "$0")/../..}" && pwd)"
T="$REPO/tests/ucode"
if [ ! -e /.dockerenv ] && [ "${DAWNLINE_TEST_FORCE:-}" != 1 ]; then
echo "run.sh replaces /etc/config/dawnline and /etc/config/uhttpd: run it in a container (scripts/ucode-container.sh)" >&2
exit 2
fi
cp "$T"/fixtures/config/* /etc/config/
mkdir -p /tmp/dawnline-tests /var/run/dawnline
PATH="$T/fixtures/bin:$PATH" ucode -L "$REPO/package/luci-app-dawnline/root/usr/share/ucode/*.uc" "$T/run.uc" "${2:-}"
Loaded 100 of 226 files, more files were not shown because too many files have changed in this diff. Show more