Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f12ca19e7 | ||
|
|
edeb1506fd | ||
|
|
7a6370aa9e | ||
|
|
466ca6c7b0 |
No files matched your search
@@ -1,88 +1,182 @@
|
|||||||
# Dawnline
|
<div align="center">
|
||||||
|
|
||||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml)
|
<picture>
|
||||||
[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml)
|
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
|
||||||
|
<img alt="Dawnline" src="docs/assets/logo-light.svg" width="88" height="88">
|
||||||
|
</picture>
|
||||||
|
|
||||||
Your OpenWrt router as a private VPN for the people you choose.
|
<h1>Dawnline</h1>
|
||||||
|
|
||||||
Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router
|
**Your OpenWrt router as a private VPN for the people you choose.**
|
||||||
and gives every person a personal link. They open it, add their own devices
|
|
||||||
(up to the limit you set) and connect with AmneziaVPN or AmneziaWG. You decide
|
|
||||||
what each person may reach: the home network, the internet, or both.
|
|
||||||
|
|
||||||
Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-liminal):
|
<a href="https://github.com/tickcount/luci-app-dawnline/releases/latest"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Latest release" src="https://shieldcn.dev/github/release/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
the same idea rebuilt around people instead of peers, with a personal portal,
|
<a href="https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="CI" src="https://shieldcn.dev/github/ci/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
limits, live traffic and a LuCI admin that follows a modern design.
|
<a href="https://github.com/tickcount/luci-app-dawnline/releases"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="Downloads" src="https://shieldcn.dev/github/downloads/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
|
<a href="LICENSE"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=dark"><img alt="License" src="https://shieldcn.dev/github/license/tickcount/luci-app-dawnline.svg?variant=secondary&font=geist&mode=light"></picture></a>
|
||||||
|
<br>
|
||||||
|
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 24.10" src="https://shieldcn.dev/badge/OpenWrt-24.10%20%C2%B7%20opkg.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||||
|
<a href="https://openwrt.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=dark"><img alt="OpenWrt 25.12" src="https://shieldcn.dev/badge/OpenWrt-25.12%20%C2%B7%20apk.svg?variant=secondary&font=geist&logo=openwrt&mode=light"></picture></a>
|
||||||
|
<a href="https://docs.amnezia.org/"><picture><source media="(prefers-color-scheme: dark)" srcset="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=dark"><img alt="AmneziaWG 2.0 and 3.1" src="https://shieldcn.dev/badge/AmneziaWG-2.0%20%C2%B7%203.1.svg?variant=secondary&font=geist&logo=wireguard&mode=light"></picture></a>
|
||||||
|
|
||||||

|
[**Quick start**](#-quick-start) · [Features](#-features) · [How it works](#-how-it-works) · [Screenshots](#-a-closer-look) · [FAQ](#-faq) · [Development](#-development)
|
||||||
|
|
||||||
| People | A person |
|
</div>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
Dawnline runs an [AmneziaWG] server on your OpenWrt router and gives every
|
||||||
|
person you invite **a personal link**. They open it, **add their own phones and
|
||||||
|
computers** and connect with AmneziaVPN, AmneziaWG or WireGuard. You decide
|
||||||
|
**what each of them may reach** (the home network, the internet, or both) and
|
||||||
|
**for how long, how much and when**.
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/screenshots/portal.png" alt="The personal portal: devices and access, and adding a phone in three steps" width="860">
|
||||||
|
<br>
|
||||||
|
<sub>A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect.</sub>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## 💡 Why Dawnline?
|
||||||
|
|
||||||
|
Sharing a home VPN usually means making a config file by hand, sending it over
|
||||||
|
a messenger and hoping nobody shares it further. Dawnline turns that around:
|
||||||
|
|
||||||
|
| | A VPN by hand | With Dawnline |
|
||||||
|
|---|---|---|
|
||||||
|
| **Setting up a device** | You make a config and send it | They add it themselves from their link |
|
||||||
|
| **Who can do what** | Everyone gets the same | Home, internet or both, per person |
|
||||||
|
| **Ending access** | Find and delete their peers | A date, a data limit, or one click |
|
||||||
|
| **Knowing what goes on** | Read `wg show` | Who is online, traffic, places, a log |
|
||||||
|
| **When something breaks** | You find out from them | A watchdog notices and repairs it |
|
||||||
|
|
||||||
|
It is the successor of [Liminal]: the same idea rebuilt around people instead
|
||||||
|
of peers, with a personal portal, limits, live traffic and a LuCI admin that
|
||||||
|
follows a modern design.
|
||||||
|
|
||||||
|
## 🚀 Quick start
|
||||||
|
|
||||||
|
1. **Install** on the router (it asks before it changes anything):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Set up** in LuCI: <kbd>Network</kbd> › <kbd>Dawnline</kbd>, and follow the
|
||||||
|
wizard. It suggests the port, the public address and the networks.
|
||||||
|
3. **Invite** someone: <kbd>Add person</kbd>, then send them the link or the
|
||||||
|
invite card with its QR code. They do the rest.
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> Behind Cloudflare, give the portal a port Cloudflare proxies: 2053, 2083,
|
||||||
|
> 2087, 2096 or 8443.
|
||||||
|
|
||||||
|
## ✨ Features
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<h3>🔗 A link, not an account</h3>
|
||||||
|
<p>Three words, like <code>vpn.example.com/kamiro-telosu-bavine</code>. The link is the key: no sign-up, no password, and a new link locks the old one out at once.</p>
|
||||||
|
</td>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<h3>📱 Their own devices</h3>
|
||||||
|
<p>People add, rename and remove devices up to their limit. Adding one walks them through it: the right app, then a QR code, a link, a key or a file.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>👥 People, not peers</h3>
|
||||||
|
<p>One card per person with their devices, who is online, traffic, end date and data limit. Filter by who needs attention or is paused.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🧭 Who reaches what</h3>
|
||||||
|
<p>The home network, the internet or both; only some networks or devices at home (a NAS, Home Assistant). Family sees family, guests see guests.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>⏳ Limits</h3>
|
||||||
|
<p>End dates, monthly or total data limits, allowed hours, a pause button. Changes apply at once, without dropping anyone else's connection.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🕶️ Disguise</h3>
|
||||||
|
<p>Presets that make the VPN traffic harder to spot and block, with what each one needs from the apps.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🏠 Internet like a home device</h3>
|
||||||
|
<p>People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🗺️ Overview and places</h3>
|
||||||
|
<p>Who is online with what, speed now, the last 30 days, and a map of where people connect from, at city level.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>🩺 Repairs itself</h3>
|
||||||
|
<p>Health checks with one-click fixes, and a watchdog that checks the tunnels, access rules and portal every minute and mends them.</p>
|
||||||
|
</td>
|
||||||
|
<td valign="top">
|
||||||
|
<h3>📦 Updates and backups</h3>
|
||||||
|
<p>Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
## 🧩 How it works
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
you(["🛠️ You, in LuCI"]) -- "add a person" --> link["🔗 Their link"]
|
||||||
|
link -- "they open it" --> portal["📱 Their portal"]
|
||||||
|
portal -- "add a device" --> app["App and connection"]
|
||||||
|
app == "AmneziaWG tunnel" ==> router["🌅 Dawnline<br>on your router"]
|
||||||
|
router -- "if allowed" --> home["🏠 Home network"]
|
||||||
|
router -- "if allowed" --> net["🌍 Internet"]
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **You add a person** in LuCI and choose what they may reach, their device
|
||||||
|
limit, an end date or a data limit.
|
||||||
|
2. **They open their link** on any device. The portal is theirs alone: it shows
|
||||||
|
their devices and their access; access and limits stay yours to change.
|
||||||
|
3. **They add a device.** The portal points them to the app for that system and
|
||||||
|
hands over the connection; the router gives each device its own keys.
|
||||||
|
4. **The device connects** through the router's AmneziaWG server, and Dawnline
|
||||||
|
lets through what that person may reach, counts their traffic and keeps to
|
||||||
|
their limits.
|
||||||
|
|
||||||
|
## 📸 A closer look
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="docs/screenshots/overview.png" alt="Overview: who is online, speed, the last 30 days and where people connect from" width="720">
|
||||||
|
<br>
|
||||||
|
<sub><b>Overview</b>: who is online, speed now, the last 30 days and a map of where people connect from.</sub>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<img alt="People: everyone on the server, with their devices, data and state" src="docs/screenshots/people.png">
|
||||||
|
<p align="center"><sub><b>People</b>: online, ending soon, over the limit, outside their hours, paused.</sub></p>
|
||||||
|
</td>
|
||||||
|
<td width="50%" valign="top">
|
||||||
|
<img alt="A person: their devices, traffic, places and limits" src="docs/screenshots/person.png">
|
||||||
|
<p align="center"><sub><b>A person</b>: their devices, traffic, places and limits.</sub></p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
## 📋 Requirements
|
||||||
|
|
||||||
|
| | What Dawnline needs |
|
||||||
|---|---|
|
|---|---|
|
||||||
|  |  |
|
| **OpenWrt** | 24.10 (opkg, `.ipk`) or 25.12 (apk, `.apk`) |
|
||||||
|
| **AmneziaWG** | `kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`: the installer adds a build made for your firmware when they are missing |
|
||||||
|
| **Free flash** | about 2 MB |
|
||||||
|
|
||||||
| Personal portal | Home network access |
|
## 📥 Install
|
||||||
|---|---|
|
|
||||||
|  |  |
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
- **People, not peers.** One card per person with device chips, live status,
|
|
||||||
traffic, end date and data limit. Add a person, send them the link or the
|
|
||||||
invite card (QR code), and they do the rest.
|
|
||||||
- **Personal portal.** Every person gets a link made of three words
|
|
||||||
(`https://vpn.example.com/kamiro-telosu-bavine`). The link is the key: no
|
|
||||||
accounts, no sessions, and a new link locks the old one out at once. People
|
|
||||||
add, rename and remove their devices and get each one as a QR code,
|
|
||||||
"Open in AmneziaVPN" (`vpn://`), a key or a `.conf` file. They cannot change
|
|
||||||
access or limits. Links work on the portal's own port with a Let's Encrypt
|
|
||||||
certificate (via ACME), several addresses at once (a Cloudflare-proxied name,
|
|
||||||
a plain IP), the same link at home, and wrong links can redirect to your
|
|
||||||
website. Behind Cloudflare, pick a port it proxies (2053, 2083, 2087, 2096 or
|
|
||||||
8443).
|
|
||||||
- **Access per person**, enforced in an `inet dawnline` nftables table on the
|
|
||||||
tunnel interface: home network only, internet only, or both, and optionally
|
|
||||||
only some home networks or home services (picked from the devices the router
|
|
||||||
sees over DHCP). Devices of different people reach each other never, always,
|
|
||||||
or within circles (family sees family, guests see guests). "Who reaches what"
|
|
||||||
sums up the rules and "Check access" walks them step by step for a device
|
|
||||||
and an address.
|
|
||||||
- **Limits.** End dates (pause, keep, or remove devices when they pass), monthly
|
|
||||||
or total data limits, allowed hours, pause anyone. Devices
|
|
||||||
drop off the tunnel at once (`awg syncconf`, no interface restart).
|
|
||||||
- **Disguise presets** for AmneziaWG obfuscation (junk packets,
|
|
||||||
header and padding parameters), with what each preset needs from the apps.
|
|
||||||
- **Internet like a home device.** Tunnel clients' internet traffic enters the
|
|
||||||
router from the LAN, through a small network namespace on the LAN bridge
|
|
||||||
(needs `kmod-veth`). Whatever handles LAN traffic on the router (proxies, DPI
|
|
||||||
bypass, DNS filters, the `lan` zone) handles VPN clients too, with no
|
|
||||||
per-tool integration.
|
|
||||||
- **Overview.** Who is online with what, speed now, today and the last 30 days,
|
|
||||||
and a map of where people connect from (city level).
|
|
||||||
- **Diagnostics.** Health checks with one-click fixes, including the ones that
|
|
||||||
matter for reaching the portal from outside (DNS, port forwards, reply
|
|
||||||
routing behind proxies such as SSClash/Mihomo, certificate coverage). A
|
|
||||||
watchdog checks the tunnels, access rules, portal, resolver and LuCI link
|
|
||||||
every minute and repairs them on its own (a cron job looks after the agent
|
|
||||||
itself). One log holds people's activity and the service log: tunnel starts
|
|
||||||
and stops with netifd's reasons, repairs and errors (`dawnline log` on the
|
|
||||||
router).
|
|
||||||
- **Updates.** Dawnline itself, AmneziaWG builds for your firmware (choose
|
|
||||||
between [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt)
|
|
||||||
and [2Grey](https://github.com/2Grey/awg-openwrt), AmneziaWG 2.0 or 3.1), and
|
|
||||||
the few OpenWrt packages Dawnline adds.
|
|
||||||
- **Backups** nightly and before risky operations, JSON export/import to move
|
|
||||||
to another router.
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
- OpenWrt **24.10** (opkg, `.ipk`) or **25.12** (apk, `.apk`)
|
|
||||||
- AmneziaWG (`kmod-amneziawg`, `amneziawg-tools`, `luci-proto-amneziawg`):
|
|
||||||
the installer adds a build made for your firmware when it is missing
|
|
||||||
- About 2 MB of free flash
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
On the router:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||||
@@ -90,17 +184,21 @@ sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline
|
|||||||
|
|
||||||
The installer checks the firmware, the clock, free space and DNS, lets you pick
|
The installer checks the firmware, the clock, free space and DNS, lets you pick
|
||||||
a release (the latest is the default), shows the plan and asks before it
|
a release (the latest is the default), shows the plan and asks before it
|
||||||
changes anything. It downloads the Dawnline package for your package manager,
|
changes anything. It downloads the package for your package manager, checks it
|
||||||
checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware
|
against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
|
||||||
if it is missing, then installs Dawnline with its dependencies and checks that
|
missing, then installs Dawnline and checks that LuCI can reach it.
|
||||||
LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup
|
|
||||||
wizard.
|
|
||||||
|
|
||||||
Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
|
> [!NOTE]
|
||||||
and the service state to `/etc/dawnline/installer-backups/` (the newest three
|
> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
|
||||||
are kept); if a step fails, it puts them back. Packages are not rolled back: to
|
> and the service state to `/etc/dawnline/installer-backups/` (the newest three
|
||||||
return to an older release, run the installer with `--tag`. Everything it does
|
> are kept), and puts them back if a step fails. Packages are not rolled back:
|
||||||
is logged to `/tmp/dawnline-install.log`.
|
> to return to an older release, run the installer with `--tag`. Everything it
|
||||||
|
> does is logged to `/tmp/dawnline-install.log`.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Installer options</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
With options, download it first:
|
With options, download it first:
|
||||||
|
|
||||||
@@ -117,39 +215,64 @@ sh /tmp/dawnline-install.sh --awg grey # AmneziaWG from 2Grey
|
|||||||
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
|
| `-n`, `--dry-run` | Check the system, resolve, download and verify the release; change nothing |
|
||||||
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
|
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
|
||||||
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
|
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
|
||||||
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same |
|
| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov], then [2Grey] (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same |
|
||||||
| `--no-awg` | Same as `--awg skip` |
|
| `--no-awg` | Same as `--awg skip` |
|
||||||
|
|
||||||
When GitHub is slow or blocked, the installer retries downloads through
|
</details>
|
||||||
`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
|
|
||||||
through a mirror:
|
<details>
|
||||||
|
<summary><b>When GitHub is slow or blocked</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
The installer retries downloads through `ghfast.top` and `gh-proxy.com` on its
|
||||||
|
own. To fetch the installer itself through a mirror:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
|
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
|
||||||
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
|
||||||
```
|
```
|
||||||
|
|
||||||
By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases):
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Installing by hand</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
From a [release](https://github.com/tickcount/luci-app-dawnline/releases):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
|
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
|
||||||
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
|
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
|
||||||
```
|
```
|
||||||
|
|
||||||
**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
|
</details>
|
||||||
keys and history are kept, and a backup is made first.
|
|
||||||
|
|
||||||
**Remove** on the router:
|
**Upgrade** from <kbd>Dawnline</kbd> › <kbd>Updates</kbd>, or run the installer
|
||||||
|
again. Settings, keys and history are kept, and a backup is made first.
|
||||||
|
|
||||||
|
### Remove
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
|
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
|
||||||
```
|
```
|
||||||
|
|
||||||
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
|
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
|
||||||
removal (the same as **Settings → Remove Dawnline from this router**), removes
|
removal (the same as <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>),
|
||||||
the package and cleans up what is left. AmneziaWG stays installed, since other
|
removes the package and cleans up what is left. After installing Dawnline
|
||||||
tunnels may use it. After installing Dawnline again, restore the backup in
|
again, restore the backup in <kbd>Settings</kbd> › <kbd>Backups</kbd>.
|
||||||
**Settings → Backups**. With options, download it first:
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> AmneziaWG stays installed, since other tunnels may use it. Add `--remove-awg`
|
||||||
|
> to take it away too.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Uninstaller options</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
With options, download it first:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
|
wget -O /tmp/dawnline-uninstall.sh https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh
|
||||||
@@ -163,25 +286,83 @@ sh /tmp/dawnline-uninstall.sh --dry-run
|
|||||||
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
|
| `--remove-awg` | Also remove AmneziaWG, unless another interface still uses it (`--keep-awg`, the default, keeps it) |
|
||||||
| `-n`, `--dry-run` | Show what would be removed; change nothing |
|
| `-n`, `--dry-run` | Show what would be removed; change nothing |
|
||||||
|
|
||||||
By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then
|
By hand: <kbd>Settings</kbd> › <kbd>Remove Dawnline from this router</kbd>
|
||||||
`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
|
(keeps a backup), then `opkg remove luci-app-dawnline` or
|
||||||
|
`apk del luci-app-dawnline`.
|
||||||
|
|
||||||
## What Dawnline changes on the router
|
</details>
|
||||||
|
|
||||||
|
## ❓ FAQ
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Which apps do people use?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
AmneziaVPN or AmneziaWG on phones and computers, and plain WireGuard when the
|
||||||
|
disguise is off. The portal shows each person the app for their system and how
|
||||||
|
to add the connection in it.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>What happens when someone loses their link?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
Make a new one on their page. The old link stops working at once; their devices
|
||||||
|
keep working, unless you tick the ones to remove with it.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Does it touch the rest of my router?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
Only what it created, and `dawnline teardown` removes all of it. The full list
|
||||||
|
is under [What Dawnline changes on the router](#-what-dawnline-changes-on-the-router).
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>How do I move to another router?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<kbd>Export JSON</kbd> in <kbd>Settings</kbd> › <kbd>Backups</kbd> on the old
|
||||||
|
one, install Dawnline on the new one and import the file there.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Where do the places on the map come from?</b></summary>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
From the address a device connects from, looked up at city level and cached on
|
||||||
|
the router. It can be turned off in <kbd>Settings</kbd>.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## 🧾 What Dawnline changes on the router
|
||||||
|
|
||||||
Only objects it created: network interfaces tagged `_dawnline`, firewall
|
Only objects it created: network interfaces tagged `_dawnline`, firewall
|
||||||
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
|
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
|
||||||
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
|
the `dawnline` network namespace with its two veth links (`dlx0`, `dll0`, the
|
||||||
latter a port of the LAN bridge), policy rules for the tunnel interfaces with
|
latter a port of the LAN bridge, which needs `kmod-veth`), policy rules for the
|
||||||
one routing table, a second dnsmasq instance on port 5354
|
tunnel interfaces with one routing table, a second dnsmasq instance on port
|
||||||
(`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check
|
5354 (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat
|
||||||
and, while the portal is on, a uhttpd instance for it. `dawnline teardown`
|
check and, while the portal is on, a uhttpd instance for it.
|
||||||
removes all of them.
|
`dawnline teardown` removes all of them.
|
||||||
|
|
||||||
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
|
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
|
||||||
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
|
`/etc/dawnline/` (usage, events, issued configurations, backups). Live counters
|
||||||
are kept in `/var/run/dawnline` and flushed to flash at most hourly.
|
are kept in `/var/run/dawnline` and flushed to flash at most hourly. Access
|
||||||
|
changes reach the tunnel with `awg syncconf`, without restarting the interface;
|
||||||
|
`dawnline log` on the router shows the service log.
|
||||||
|
|
||||||
## Development
|
## 🛠️ Development
|
||||||
|
|
||||||
```
|
```
|
||||||
package/luci-app-dawnline/
|
package/luci-app-dawnline/
|
||||||
@@ -207,7 +388,7 @@ scripts/lint-ucode.py # static ucode checks
|
|||||||
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
scripts/check-ucode.sh root@router # compile every ucode file on a router
|
||||||
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
scripts/deploy.sh root@router # install the working tree (backs up configs first)
|
||||||
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
|
||||||
scripts/capture-screenshots.mjs # capture docs/screenshots/raw/*.png from a router
|
scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
|
||||||
scripts/frame-screenshots.py # frame them for this README
|
scripts/frame-screenshots.py # frame them for this README
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -215,6 +396,13 @@ The web bundles are committed: CI fails when they are out of date. Pushing a
|
|||||||
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK
|
tag `vX.Y.Z` (matching `PKG_VERSION`) builds both packages with the OpenWrt SDK
|
||||||
and publishes a release with `sha256sums.txt`.
|
and publishes a release with `sha256sums.txt`.
|
||||||
|
|
||||||
## License
|
---
|
||||||
|
|
||||||
[MIT](LICENSE)
|
<div align="center">
|
||||||
|
<sub>Made for OpenWrt · <a href="LICENSE">MIT license</a> · <a href="#readme">Back to top ↑</a></sub>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
[AmneziaWG]: https://docs.amnezia.org/
|
||||||
|
[Liminal]: https://github.com/tickcount/openwrt-liminal
|
||||||
|
[Slava-Shchipunov]: https://github.com/Slava-Shchipunov/awg-openwrt
|
||||||
|
[2Grey]: https://github.com/2Grey/awg-openwrt
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#ffffff"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#0a0a0a"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#0a0a0a" fill-opacity=".5"/></svg>
|
||||||
|
After Width: | Height: | Size: 254 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="16" fill="#0a0a0a"/><path d="M14 38a18 18 0 0 1 36 0z" fill="#ffffff"/><rect x="12" y="43" width="40" height="4" rx="2" fill="#ffffff" fill-opacity=".5"/></svg>
|
||||||
|
After Width: | Height: | Size: 254 B |
|
Before Width: | Height: | Size: 525 KiB |
|
Before Width: | Height: | Size: 908 KiB After Width: | Height: | Size: 457 KiB |
|
Before Width: | Height: | Size: 639 KiB After Width: | Height: | Size: 397 KiB |
|
Before Width: | Height: | Size: 825 KiB After Width: | Height: | Size: 430 KiB |
|
Before Width: | Height: | Size: 615 KiB After Width: | Height: | Size: 363 KiB |
|
Before Width: | Height: | Size: 138 KiB |
|
Before Width: | Height: | Size: 394 KiB After Width: | Height: | Size: 435 KiB |
|
Before Width: | Height: | Size: 191 KiB After Width: | Height: | Size: 373 KiB |
|
Before Width: | Height: | Size: 327 KiB After Width: | Height: | Size: 407 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
Before Width: | Height: | Size: 170 KiB After Width: | Height: | Size: 187 KiB |
@@ -6,7 +6,7 @@
|
|||||||
include $(TOPDIR)/rules.mk
|
include $(TOPDIR)/rules.mk
|
||||||
|
|
||||||
PKG_NAME:=luci-app-dawnline
|
PKG_NAME:=luci-app-dawnline
|
||||||
PKG_VERSION:=0.7.0
|
PKG_VERSION:=0.10.0
|
||||||
PKG_RELEASE:=1
|
PKG_RELEASE:=1
|
||||||
PKG_LICENSE:=MIT
|
PKG_LICENSE:=MIT
|
||||||
|
|
||||||
|
|||||||
@@ -5,25 +5,25 @@
|
|||||||
'require poll';
|
'require poll';
|
||||||
'require rpc';
|
'require rpc';
|
||||||
'require ui';
|
'require ui';
|
||||||
var gr=Object.create;var ao=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,wr=Object.prototype.hasOwnProperty;var yr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var kr=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of br(e))!wr.call(n,r)&&r!==o&&ao(n,r,{get:()=>e[r],enumerable:!(a=vr(e,r))||a.enumerable});return n};var $r=(n,e,o)=>(o=n!=null?gr(xr(n)):{},kr(e||!n||!n.__esModule?ao(o,"default",{value:n,enumerable:!0}):o,n));var bo=yr((go,vo)=>{"use strict";var fo=(function(){var n=function(E,y){var S=236,b=17,x=E,M=o[y],h=null,f=0,R=null,C=[],I={},Q=function(T,A){f=x*4+17,h=(function($){for(var H=new Array($),_=0;_<$;_+=1){H[_]=new Array($);for(var j=0;j<$;j+=1)H[_][j]=null}return H})(f),G(0,0),G(f-7,0),G(0,f-7),K(),z(),ce(T,A),x>=7&&X(T),R==null&&(R=U(x,M,C)),fe(R,A)},G=function(T,A){for(var $=-1;$<=7;$+=1)if(!(T+$<=-1||f<=T+$))for(var H=-1;H<=7;H+=1)A+H<=-1||f<=A+H||(0<=$&&$<=6&&(H==0||H==6)||0<=H&&H<=6&&($==0||$==6)||2<=$&&$<=4&&2<=H&&H<=4?h[T+$][A+H]=!0:h[T+$][A+H]=!1)},Y=function(){for(var T=0,A=0,$=0;$<8;$+=1){Q(!0,$);var H=r.getLostPoint(I);($==0||T>H)&&(T=H,A=$)}return A},z=function(){for(var T=8;T<f-8;T+=1)h[T][6]==null&&(h[T][6]=T%2==0);for(var A=8;A<f-8;A+=1)h[6][A]==null&&(h[6][A]=A%2==0)},K=function(){for(var T=r.getPatternPosition(x),A=0;A<T.length;A+=1)for(var $=0;$<T.length;$+=1){var H=T[A],_=T[$];if(h[H][_]==null)for(var j=-2;j<=2;j+=1)for(var Z=-2;Z<=2;Z+=1)j==-2||j==2||Z==-2||Z==2||j==0&&Z==0?h[H+j][_+Z]=!0:h[H+j][_+Z]=!1}},X=function(T){for(var A=r.getBCHTypeNumber(x),$=0;$<18;$+=1){var H=!T&&(A>>$&1)==1;h[Math.floor($/3)][$%3+f-8-3]=H}for(var $=0;$<18;$+=1){var H=!T&&(A>>$&1)==1;h[$%3+f-8-3][Math.floor($/3)]=H}},ce=function(T,A){for(var $=M<<3|A,H=r.getBCHTypeInfo($),_=0;_<15;_+=1){var j=!T&&(H>>_&1)==1;_<6?h[_][8]=j:_<8?h[_+1][8]=j:h[f-15+_][8]=j}for(var _=0;_<15;_+=1){var j=!T&&(H>>_&1)==1;_<8?h[8][f-_-1]=j:_<9?h[8][15-_-1+1]=j:h[8][15-_-1]=j}h[f-8][8]=!T},fe=function(T,A){for(var $=-1,H=f-1,_=7,j=0,Z=r.getMaskFunction(A),V=f-1;V>0;V-=2)for(V==6&&(V-=1);;){for(var pe=0;pe<2;pe+=1)if(h[H][V-pe]==null){var be=!1;j<T.length&&(be=(T[j]>>>_&1)==1);var ee=Z(H,V-pe);ee&&(be=!be),h[H][V-pe]=be,_-=1,_==-1&&(j+=1,_=7)}if(H+=$,H<0||f<=H){H-=$,$=-$;break}}},O=function(T,A){for(var $=0,H=0,_=0,j=new Array(A.length),Z=new Array(A.length),V=0;V<A.length;V+=1){var pe=A[V].dataCount,be=A[V].totalCount-pe;H=Math.max(H,pe),_=Math.max(_,be),j[V]=new Array(pe);for(var ee=0;ee<j[V].length;ee+=1)j[V][ee]=255&T.getBuffer()[ee+$];$+=pe;var Te=r.getErrorCorrectPolynomial(be),_e=s(j[V],Te.getLength()-1),to=_e.mod(Te);Z[V]=new Array(Te.getLength()-1);for(var ee=0;ee<Z[V].length;ee+=1){var no=ee+to.getLength()-Z[V].length;Z[V][ee]=no>=0?to.getAt(no):0}}for(var oo=0,ee=0;ee<A.length;ee+=1)oo+=A[ee].totalCount;for(var Mn=new Array(oo),Wt=0,ee=0;ee<H;ee+=1)for(var V=0;V<A.length;V+=1)ee<j[V].length&&(Mn[Wt]=j[V][ee],Wt+=1);for(var ee=0;ee<_;ee+=1)for(var V=0;V<A.length;V+=1)ee<Z[V].length&&(Mn[Wt]=Z[V][ee],Wt+=1);return Mn},U=function(T,A,$){for(var H=l.getRSBlocks(T,A),_=c(),j=0;j<$.length;j+=1){var Z=$[j];_.put(Z.getMode(),4),_.put(Z.getLength(),r.getLengthInBits(Z.getMode(),T)),Z.write(_)}for(var V=0,j=0;j<H.length;j+=1)V+=H[j].dataCount;if(_.getLengthInBits()>V*8)throw"code length overflow. ("+_.getLengthInBits()+">"+V*8+")";for(_.getLengthInBits()+4<=V*8&&_.put(0,4);_.getLengthInBits()%8!=0;)_.putBit(!1);for(;!(_.getLengthInBits()>=V*8||(_.put(S,8),_.getLengthInBits()>=V*8));)_.put(b,8);return O(_,H)};I.addData=function(T,A){A=A||"Byte";var $=null;switch(A){case"Numeric":$=d(T);break;case"Alphanumeric":$=p(T);break;case"Byte":$=u(T);break;case"Kanji":$=w(T);break;default:throw"mode:"+A}C.push($),R=null},I.isDark=function(T,A){if(T<0||f<=T||A<0||f<=A)throw T+","+A;return h[T][A]},I.getModuleCount=function(){return f},I.make=function(){if(x<1){for(var T=1;T<40;T++){for(var A=l.getRSBlocks(T,M),$=c(),H=0;H<C.length;H++){var _=C[H];$.put(_.getMode(),4),$.put(_.getLength(),r.getLengthInBits(_.getMode(),T)),_.write($)}for(var j=0,H=0;H<A.length;H++)j+=A[H].dataCount;if($.getLengthInBits()<=j*8)break}x=T}Q(!1,Y())},I.createTableTag=function(T,A){T=T||2,A=typeof A>"u"?T*4:A;var $="";$+='<table style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: "+A+"px;",$+='">',$+="<tbody>";for(var H=0;H<I.getModuleCount();H+=1){$+="<tr>";for(var _=0;_<I.getModuleCount();_+=1)$+='<td style="',$+=" border-width: 0px; border-style: none;",$+=" border-collapse: collapse;",$+=" padding: 0px; margin: 0px;",$+=" width: "+T+"px;",$+=" height: "+T+"px;",$+=" background-color: ",$+=I.isDark(H,_)?"#000000":"#ffffff",$+=";",$+='"/>';$+="</tr>"}return $+="</tbody>",$+="</table>",$},I.createSvgTag=function(T,A,$,H){var _={};typeof arguments[0]=="object"&&(_=arguments[0],T=_.cellSize,A=_.margin,$=_.alt,H=_.title),T=T||2,A=typeof A>"u"?T*4:A,$=typeof $=="string"?{text:$}:$||{},$.Line truncated
|
var vi=Object.create;var Po=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var wi=Object.getPrototypeOf,yi=Object.prototype.hasOwnProperty;var ki=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var $i=(n,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of xi(e))!yi.call(n,a)&&a!==r&&Po(n,a,{get:()=>e[a],enumerable:!(o=bi(e,a))||o.enumerable});return n};var Ci=(n,e,r)=>(r=n!=null?vi(wi(n)):{},$i(e||!n||!n.__esModule?Po(r,"default",{value:n,enumerable:!0}):r,n));var Wo=ki((Uo,Go)=>{"use strict";var jo=(function(){var n=function(C,k){var y=236,w=17,b=C,H=r[k],f=null,g=0,M=null,T=[],z={},W=function(A,N){g=b*4+17,f=(function(S){for(var O=new Array(S),_=0;_<S;_+=1){O[_]=new Array(S);for(var j=0;j<S;j+=1)O[_][j]=null}return O})(g),q(0,0),q(g-7,0),q(0,g-7),V(),I(),de(A,N),b>=7&&Q(A),M==null&&(M=F(b,H,T)),ee(M,N)},q=function(A,N){for(var S=-1;S<=7;S+=1)if(!(A+S<=-1||g<=A+S))for(var O=-1;O<=7;O+=1)N+O<=-1||g<=N+O||(0<=S&&S<=6&&(O==0||O==6)||0<=O&&O<=6&&(S==0||S==6)||2<=S&&S<=4&&2<=O&&O<=4?f[A+S][N+O]=!0:f[A+S][N+O]=!1)},Z=function(){for(var A=0,N=0,S=0;S<8;S+=1){W(!0,S);var O=a.getLostPoint(z);(S==0||A>O)&&(A=O,N=S)}return N},I=function(){for(var A=8;A<g-8;A+=1)f[A][6]==null&&(f[A][6]=A%2==0);for(var N=8;N<g-8;N+=1)f[6][N]==null&&(f[6][N]=N%2==0)},V=function(){for(var A=a.getPatternPosition(b),N=0;N<A.length;N+=1)for(var S=0;S<A.length;S+=1){var O=A[N],_=A[S];if(f[O][_]==null)for(var j=-2;j<=2;j+=1)for(var Y=-2;Y<=2;Y+=1)j==-2||j==2||Y==-2||Y==2||j==0&&Y==0?f[O+j][_+Y]=!0:f[O+j][_+Y]=!1}},Q=function(A){for(var N=a.getBCHTypeNumber(b),S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[Math.floor(S/3)][S%3+g-8-3]=O}for(var S=0;S<18;S+=1){var O=!A&&(N>>S&1)==1;f[S%3+g-8-3][Math.floor(S/3)]=O}},de=function(A,N){for(var S=H<<3|N,O=a.getBCHTypeInfo(S),_=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<6?f[_][8]=j:_<8?f[_+1][8]=j:f[g-15+_][8]=j}for(var _=0;_<15;_+=1){var j=!A&&(O>>_&1)==1;_<8?f[8][g-_-1]=j:_<9?f[8][15-_-1+1]=j:f[8][15-_-1]=j}f[g-8][8]=!A},ee=function(A,N){for(var S=-1,O=g-1,_=7,j=0,Y=a.getMaskFunction(N),J=g-1;J>0;J-=2)for(J==6&&(J-=1);;){for(var ue=0;ue<2;ue+=1)if(f[O][J-ue]==null){var xe=!1;j<A.length&&(xe=(A[j]>>>_&1)==1);var te=Y(O,J-ue);te&&(xe=!xe),f[O][J-ue]=xe,_-=1,_==-1&&(j+=1,_=7)}if(O+=S,O<0||g<=O){O-=S,S=-S;break}}},B=function(A,N){for(var S=0,O=0,_=0,j=new Array(N.length),Y=new Array(N.length),J=0;J<N.length;J+=1){var ue=N[J].dataCount,xe=N[J].totalCount-ue;O=Math.max(O,ue),_=Math.max(_,xe),j[J]=new Array(ue);for(var te=0;te<j[J].length;te+=1)j[J][te]=255&A.getBuffer()[te+S];S+=ue;var De=a.getErrorCorrectPolynomial(xe),Ae=s(j[J],De.getLength()-1),So=Ae.mod(De);Y[J]=new Array(De.getLength()-1);for(var te=0;te<Y[J].length;te+=1){var To=te+So.getLength()-Y[J].length;Y[J][te]=To>=0?So.getAt(To):0}}for(var _o=0,te=0;te<N.length;te+=1)_o+=N[te].totalCount;for(var Gn=new Array(_o),Qt=0,te=0;te<O;te+=1)for(var J=0;J<N.length;J+=1)te<j[J].length&&(Gn[Qt]=j[J][te],Qt+=1);for(var te=0;te<_;te+=1)for(var J=0;J<N.length;J+=1)te<Y[J].length&&(Gn[Qt]=Y[J][te],Qt+=1);return Gn},F=function(A,N,S){for(var O=l.getRSBlocks(A,N),_=d(),j=0;j<S.length;j+=1){var Y=S[j];_.put(Y.getMode(),4),_.put(Y.getLength(),a.getLengthInBits(Y.getMode(),A)),Y.write(_)}for(var J=0,j=0;j<O.length;j+=1)J+=O[j].dataCount;if(_.getLengthInBits()>J*8)throw"code length overflow. ("+_.getLengthInBits()+">"+J*8+")";for(_.getLengthInBits()+4<=J*8&&_.put(0,4);_.getLengthInBits()%8!=0;)_.putBit(!1);for(;!(_.getLengthInBits()>=J*8||(_.put(y,8),_.getLengthInBits()>=J*8));)_.put(w,8);return B(_,O)};z.addData=function(A,N){N=N||"Byte";var S=null;switch(N){case"Numeric":S=c(A);break;case"Alphanumeric":S=p(A);break;case"Byte":S=u(A);break;case"Kanji":S=x(A);break;default:throw"mode:"+N}T.push(S),M=null},z.isDark=function(A,N){if(A<0||g<=A||N<0||g<=N)throw A+","+N;return f[A][N]},z.getModuleCount=function(){return g},z.make=function(){if(b<1){for(var A=1;A<40;A++){for(var N=l.getRSBlocks(A,H),S=d(),O=0;O<T.length;O++){var _=T[O];S.put(_.getMode(),4),S.put(_.getLength(),a.getLengthInBits(_.getMode(),A)),_.write(S)}for(var j=0,O=0;O<N.length;O++)j+=N[O].dataCount;if(S.getLengthInBits()<=j*8)break}b=A}W(!1,Z())},z.createTableTag=function(A,N){A=A||2,N=typeof N>"u"?A*4:N;var S="";S+='<table style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: "+N+"px;",S+='">',S+="<tbody>";for(var O=0;O<z.getModuleCount();O+=1){S+="<tr>";for(var _=0;_<z.getModuleCount();_+=1)S+='<td style="',S+=" border-width: 0px; border-style: none;",S+=" border-collapse: collapse;",S+=" padding: 0px; margin: 0px;",S+=" width: "+A+"px;",S+=" height: "+A+"px;",S+=" background-color: ",S+=z.isDark(O,_)?"#000000":"#ffffff",S+=";",S+='"/>';S+="</tr>"}return S+="</tbody>",S+="</table>",S},z.createSvgTag=function(A,N,S,O){var _={};typeof arguments[0]=="object"&&(_=arguments[0],A=_.cellSize,N=_.margin,S=_.alt,O=_.title),A=A||2,N=typeof N>"u"?A*4:N,S=typeof S=="string"?{text:S}:S||{},S.Line truncated
|
||||||
`}return $%2&&T>0?_e.substring(0,_e.length-$-1)+Array($+1).join("▀"):_e.substring(0,_e.length-1)};return I.createASCII=function(T,A){if(T=T||1,T<2)return oe(A);T-=1,A=typeof A>"u"?T*2:A;var $=I.getModuleCount()*T+A*2,H=A,_=$-A,j,Z,V,pe,be=Array(T+1).join("██"),ee=Array(T+1).join(" "),Te="",_e="";for(j=0;j<$;j+=1){for(V=Math.floor((j-H)/T),_e="",Z=0;Z<$;Z+=1)pe=1,H<=Z&&Z<_&&H<=j&&j<_&&I.isDark(V,Math.floor((Z-H)/T))&&(pe=0),_e+=pe?be:ee;for(V=0;V<T;V+=1)Te+=_e+`
|
`}return S%2&&A>0?Ae.substring(0,Ae.length-S-1)+Array(S+1).join("▀"):Ae.substring(0,Ae.length-1)};return z.createASCII=function(A,N){if(A=A||1,A<2)return pe(N);A-=1,N=typeof N>"u"?A*2:N;var S=z.getModuleCount()*A+N*2,O=N,_=S-N,j,Y,J,ue,xe=Array(A+1).join("██"),te=Array(A+1).join(" "),De="",Ae="";for(j=0;j<S;j+=1){for(J=Math.floor((j-O)/A),Ae="",Y=0;Y<S;Y+=1)ue=1,O<=Y&&Y<_&&O<=j&&j<_&&z.isDark(J,Math.floor((Y-O)/A))&&(ue=0),Ae+=ue?xe:te;for(J=0;J<A;J+=1)De+=Ae+`
|
||||||
`}return Te.substring(0,Te.length-1)},I.renderTo2dContext=function(T,A){A=A||2;for(var $=I.getModuleCount(),H=0;H<$;H++)for(var _=0;_<$;_++)T.fillStyle=I.isDark(H,_)?"black":"white",T.fillRect(H*A,_*A,A,A)},I};n.stringToBytesFuncs={default:function(E){for(var y=[],S=0;S<E.length;S+=1){var b=E.charCodeAt(S);y.push(b&255)}return y}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(E,y){var S=(function(){for(var x=k(E),M=function(){var z=x.read();if(z==-1)throw"eof";return z},h=0,f={};;){var R=x.read();if(R==-1)break;var C=M(),I=M(),Q=M(),G=String.fromCharCode(R<<8|C),Y=I<<8|Q;f[G]=Y,h+=1}if(h!=y)throw h+" != "+y;return f})(),b=63;return function(x){for(var M=[],h=0;h<x.length;h+=1){var f=x.charCodeAt(h);if(f<128)M.push(f);else{var R=S[x.charAt(h)];typeof R=="number"?(R&255)==R?M.push(R):(M.push(R>>>8),M.push(R&255)):M.push(b)}}return M}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},o={L:1,M:0,Q:3,H:2},a={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},r=(function(){var E=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],y=1335,S=7973,b=21522,x={},M=function(h){for(var f=0;h!=0;)f+=1,h>>>=1;return f};return x.getBCHTypeInfo=function(h){for(var f=h<<10;M(f)-M(y)>=0;)f^=y<<M(f)-M(y);return(h<<10|f)^b},x.getBCHTypeNumber=function(h){for(var f=h<<12;M(f)-M(S)>=0;)f^=S<<M(f)-M(S);return h<<12|f},x.getPatternPosition=function(h){return E[h-1]},x.getMaskFunction=function(h){switch(h){case a.PATTERN000:return function(f,R){return(f+R)%2==0};case a.PATTERN001:return function(f,R){return f%2==0};case a.PATTERN010:return function(f,R){return R%3==0};case a.PATTERN011:return function(f,R){return(f+R)%3==0};case a.PATTERN100:return function(f,R){return(Math.floor(f/2)+Math.floor(R/3))%2==0};case a.PATTERN101:return function(f,R){return f*R%2+f*R%3==0};case a.PATTERN110:return function(f,R){return(f*R%2+f*R%3)%2==0};case a.PATTERN111:return function(f,R){return(f*R%3+(f+R)%2)%2==0};default:throw"bad maskPattern:"+h}},x.getErrorCorrectPolynomial=function(h){for(var f=s([1],0),R=0;R<h;R+=1)f=f.multiply(s([1,i.gexp(R)],0));return f},x.getLengthInBits=function(h,f){if(1<=f&&f<10)switch(h){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+h}else if(f<27)switch(h){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+h}else if(f<41)switch(h){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+h}else throw"type:"+f},x.getLostPoint=function(h){for(var f=h.getModuleCount(),R=0,C=0;C<f;C+=1)for(var I=0;I<f;I+=1){for(var Q=0,G=h.isDark(C,I),Y=-1;Y<=1;Y+=1)if(!(C+Y<0||f<=C+Y))for(var z=-1;z<=1;z+=1)I+z<0||f<=I+z||Y==0&&z==0||G==h.isDark(C+Y,I+z)&&(Q+=1);Q>5&&(R+=3+Q-5)}for(var C=0;C<f-1;C+=1)for(var I=0;I<f-1;I+=1){var K=0;h.isDark(C,I)&&(K+=1),h.isDark(C+1,I)&&(K+=1),h.isDark(C,I+1)&&(K+=1),h.isDark(C+1,I+1)&&(K+=1),(K==0||K==4)&&(R+=3)}for(var C=0;C<f;C+=1)for(var I=0;I<f-6;I+=1)h.isDark(C,I)&&!h.isDark(C,I+1)&&h.isDark(C,I+2)&&h.isDark(C,I+3)&&h.isDark(C,I+4)&&!h.isDark(C,I+5)&&h.isDark(C,I+6)&&(R+=40);for(var I=0;I<f;I+=1)for(var C=0;C<f-6;C+=1)h.isDark(C,I)&&!h.isDark(C+1,I)&&h.isDark(C+2,I)&&h.isDark(C+3,I)&&h.isDark(C+4,I)&&!h.isDark(C+5,I)&&h.isDark(C+6,I)&&(R+=40);for(var X=0,I=0;I<f;I+=1)for(var C=0;C<f;C+=1)h.isDark(C,I)&&(X+=1);var ce=Math.abs(100*X/f/f-50)/5;return R+=ce*10,R},x})(),i=(function(){for(var E=new Array(256),y=new Array(256),S=0;S<8;S+=1)E[S]=1<<S;for(var S=8;S<256;S+=1)E[S]=E[S-4]^E[S-5]^E[S-6]^E[S-8];for(var S=0;S<255;S+=1)y[E[S]]=S;var b={};return b.glog=function(x){if(x<1)throw"glog("+x+")";return y[x]},b.gexp=function(x){for(;x<0;)x+=255;for(;x>=256;)x-=255;return E[x]},b})();function s(E,y){if(typeof E.length>"u")throw E.length+"/"+y;var S=(function(){for(var x=0;x<E.length&&E[x]==0;)x+=1;for(var M=new Array(E.length-x+y),h=0;h<E.length-x;h+=1)M[h]=E[h+x];return M})(),b={};return b.getAt=function(x){return S[x]},b.getLength=function(){return S.length},b.multiply=function(x){for(var M=new Array(b.getLength()+x.getLength()-1),h=0;h<b.getLength();h+=1)for(var f=0;f<x.getLength();f+=1)M[h+f]^=i.gexp(i.glog(b.getAt(h))+i.glog(x.getAt(f)));return s(M,0)},b.mod=function(x){if(b.getLength()
Line truncated
|
`}return De.substring(0,De.length-1)},z.renderTo2dContext=function(A,N){N=N||2;for(var S=z.getModuleCount(),O=0;O<S;O++)for(var _=0;_<S;_++)A.fillStyle=z.isDark(O,_)?"black":"white",A.fillRect(O*N,_*N,N,N)},z};n.stringToBytesFuncs={default:function(C){for(var k=[],y=0;y<C.length;y+=1){var w=C.charCodeAt(y);k.push(w&255)}return k}},n.stringToBytes=n.stringToBytesFuncs.default,n.createStringToBytes=function(C,k){var y=(function(){for(var b=m(C),H=function(){var I=b.read();if(I==-1)throw"eof";return I},f=0,g={};;){var M=b.read();if(M==-1)break;var T=H(),z=H(),W=H(),q=String.fromCharCode(M<<8|T),Z=z<<8|W;g[q]=Z,f+=1}if(f!=k)throw f+" != "+k;return g})(),w=63;return function(b){for(var H=[],f=0;f<b.length;f+=1){var g=b.charCodeAt(f);if(g<128)H.push(g);else{var M=y[b.charAt(f)];typeof M=="number"?(M&255)==M?H.push(M):(H.push(M>>>8),H.push(M&255)):H.push(w)}}return H}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},o={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},a=(function(){var C=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,y=7973,w=21522,b={},H=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return b.getBCHTypeInfo=function(f){for(var g=f<<10;H(g)-H(k)>=0;)g^=k<<H(g)-H(k);return(f<<10|g)^w},b.getBCHTypeNumber=function(f){for(var g=f<<12;H(g)-H(y)>=0;)g^=y<<H(g)-H(y);return f<<12|g},b.getPatternPosition=function(f){return C[f-1]},b.getMaskFunction=function(f){switch(f){case o.PATTERN000:return function(g,M){return(g+M)%2==0};case o.PATTERN001:return function(g,M){return g%2==0};case o.PATTERN010:return function(g,M){return M%3==0};case o.PATTERN011:return function(g,M){return(g+M)%3==0};case o.PATTERN100:return function(g,M){return(Math.floor(g/2)+Math.floor(M/3))%2==0};case o.PATTERN101:return function(g,M){return g*M%2+g*M%3==0};case o.PATTERN110:return function(g,M){return(g*M%2+g*M%3)%2==0};case o.PATTERN111:return function(g,M){return(g*M%3+(g+M)%2)%2==0};default:throw"bad maskPattern:"+f}},b.getErrorCorrectPolynomial=function(f){for(var g=s([1],0),M=0;M<f;M+=1)g=g.multiply(s([1,i.gexp(M)],0));return g},b.getLengthInBits=function(f,g){if(1<=g&&g<10)switch(f){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+f}else if(g<27)switch(f){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+f}else if(g<41)switch(f){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+f}else throw"type:"+g},b.getLostPoint=function(f){for(var g=f.getModuleCount(),M=0,T=0;T<g;T+=1)for(var z=0;z<g;z+=1){for(var W=0,q=f.isDark(T,z),Z=-1;Z<=1;Z+=1)if(!(T+Z<0||g<=T+Z))for(var I=-1;I<=1;I+=1)z+I<0||g<=z+I||Z==0&&I==0||q==f.isDark(T+Z,z+I)&&(W+=1);W>5&&(M+=3+W-5)}for(var T=0;T<g-1;T+=1)for(var z=0;z<g-1;z+=1){var V=0;f.isDark(T,z)&&(V+=1),f.isDark(T+1,z)&&(V+=1),f.isDark(T,z+1)&&(V+=1),f.isDark(T+1,z+1)&&(V+=1),(V==0||V==4)&&(M+=3)}for(var T=0;T<g;T+=1)for(var z=0;z<g-6;z+=1)f.isDark(T,z)&&!f.isDark(T,z+1)&&f.isDark(T,z+2)&&f.isDark(T,z+3)&&f.isDark(T,z+4)&&!f.isDark(T,z+5)&&f.isDark(T,z+6)&&(M+=40);for(var z=0;z<g;z+=1)for(var T=0;T<g-6;T+=1)f.isDark(T,z)&&!f.isDark(T+1,z)&&f.isDark(T+2,z)&&f.isDark(T+3,z)&&f.isDark(T+4,z)&&!f.isDark(T+5,z)&&f.isDark(T+6,z)&&(M+=40);for(var Q=0,z=0;z<g;z+=1)for(var T=0;T<g;T+=1)f.isDark(T,z)&&(Q+=1);var de=Math.abs(100*Q/g/g-50)/5;return M+=de*10,M},b})(),i=(function(){for(var C=new Array(256),k=new Array(256),y=0;y<8;y+=1)C[y]=1<<y;for(var y=8;y<256;y+=1)C[y]=C[y-4]^C[y-5]^C[y-6]^C[y-8];for(var y=0;y<255;y+=1)k[C[y]]=y;var w={};return w.glog=function(b){if(b<1)throw"glog("+b+")";return k[b]},w.gexp=function(b){for(;b<0;)b+=255;for(;b>=256;)b-=255;return C[b]},w})();function s(C,k){if(typeof C.length>"u")throw C.length+"/"+k;var y=(function(){for(var b=0;b<C.length&&C[b]==0;)b+=1;for(var H=new Array(C.length-b+k),f=0;f<C.length-b;f+=1)H[f]=C[f+b];return H})(),w={};return w.getAt=function(b){return y[b]},w.getLength=function(){return y.length},w.multiply=function(b){for(var H=new Array(w.getLength()+b.getLength()-1),f=0;f<w.getLength();f+=1)for(var g=0;g<b.getLength();g+=1)H[f+g]^=i.gexp(i.glog(w.getAt(f))+i.glog(b.getAt(g)));return s(H,0)},w.mod=function(b){if(w.getLength()
Line truncated
|
||||||
`)}function Nr(n){let e=new Map(n.people.map(a=>[a.id,a.name])),o=new Map(n.people.flatMap(a=>a.devices.map(r=>[r.id,r.name])));return{people:e,devices:o}}function Ue(n,e,o,a="",r=[]){let i=Nr(n),s=[...e.map(p=>({ts:p.ts,category:_t(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:De(p)??""})),...r.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
|
`)}function qi(n){let e=new Map(n.people.map(o=>[o.id,o.name])),r=new Map(n.people.flatMap(o=>o.devices.map(a=>[a.id,a.name])));return{people:e,devices:r}}function Fe(n,e,r,o="",a=[]){let i=qi(n),s=[...e.map(p=>({ts:p.ts,category:It(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
|
||||||
${p.detail}`:""}`,where:Ct[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),c=`dawnline-activity${a?`-${a}`:""}-${l}.${o}`;if(o==="json"){Le(c,JSON.stringify(s,null,2),"application/json");return}Le(c,$o(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Hr=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],Eo=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function Ke(n,e,o,a,r,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...gt.map(c=>t("option",{value:c,selected:c===r?"selected":null},rt[c])),i?t("option",{value:"system",selected:r==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Hr.map(([c,d])=>t("option",{value:c},d)));ae(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[le()," ",D("Clear",async()=>{let c=0;if(s.value!=="system")try{c+=(await P.logsClear({...o,category:s.value,older_days:l.value})).removed}catch(d){F(ve(d),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{c+=(await P.serviceLogClear(l.value)).removed}catch(d){de(),F(`${s.value==="system"?"":`Activity: ${Eo(c).toLowerCase()}. `}The service log was not cleared: ${ve(d)}`,"error",1e4),a();return}de(),F(Eo(c),"success",3e3),a()},"negative")])}function vt(n,e,o,a){let r=n==="device"?`Clears ${o}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${o}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";ae(n==="all"?"Reset all traffic history?":`Reset traffic history for ${o}?`,[t("p",{class:"dl-muted"},r)],[le()," ",D("Reset",async()=>{await W(()=>P.usageClear(n,e),"Traffic history reset")&&(de(),a())},"negative")])}function ge(n,e,o){let a=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let r=!a.classList.contains("on");Dn(a,r),o?.(r)}},t("i"));return a}function Dn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Se=n=>n.classList.contains("on");function xe(n,e,o={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let a=t("div",{class:`dl-seg${o.cls?` ${o.cls}`:""}`,role:"radiogroup","aria-label":o.label??null,"data-value":e}),r=()=>a.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===a.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)a.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==a.dataset.value&&(o.optimistic!==!1&&(a.dataset.value=i,r()),o.onChange?.(i))}},s));return r(),a}function We(n,e,o,a={}){return t("button",{type:"button",...a,class:`dl-chipbtn${e?" on":""}${a.class?` ${a.class}`:""}`,"aria-pressed":e?"true":"false",click:o},n)}function Zt(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function se(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Rr={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Ir={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Br(n){let e={};for(let[o,a]of Object.entries(Ir))n[o]!=null&&n[o]!==""&&(e[a]=String(n[o]));return e}function Or(n,e){let o=n.amnezia,a=o.obfuscation??{},r=c=>a[c]!=null&&a[c]!==""?String(a[c]):Rr[c],i=o.host.replace(/^\[(.*)\]$/,"$1"),s={H1:r("h1"),H2:r("h2"),H3:r("h3"),H4:r("h4"),I1:r("i1"),I2:r("i2"),I3:r("i3"),I4:r("i4"),I5:r("i5"),Jc:r("jc"),Jmin:r("jmin"),Jmax:r("jmax"),S1:r("s1"),S2:r("s2"),S3:r("s3"),S4:r("s4"),...Br(a),allowed_ips:o.allowed_ips,client_ip:o.client_ip,client_priv_key:o.client_priv_key,client_pub_key:o.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
|
${p.detail}`:""}`,where:Bt[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,dr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var Ki=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],cr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function et(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Lt.map(d=>t("option",{value:d,selected:d===a?"selected":null},ut[d])),i?t("option",{value:"system",selected:a==="system"?"selected":null},"System"):""]),l=t("select",{class:"cbi-input-select"},Ki.map(([d,c])=>t("option",{value:d},c)));oe(n,[t("p",{class:"dl-muted"},`${e} This cannot be undone; export first if you want a copy.`),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Category"),s]),t("label",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Which events"),l])],[ie()," ",D("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await P.logsClear({...r,category:s.value,older_days:l.value})).removed}catch(c){U(be(c),"error",1e4);return}if(i&&(s.value==="system"||s.value===""))try{d+=(await P.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${cr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(cr(d),"success",3e3),o()},"negative")])}function Mt(n,e,r,o){let a=n==="device"?`Clears ${r}'s daily and monthly traffic history. Their person's totals and data limit are not changed.`:n==="person"?`Clears ${r}'s traffic history and that of their devices. Their data limit starts again from zero.`:"Clears traffic history for everyone. Data limits start again from zero.";oe(n==="all"?"Reset all traffic history?":`Reset traffic history for ${r}?`,[t("p",{class:"dl-muted"},a)],[ie()," ",D("Reset",async()=>{await G(()=>P.usageClear(n,e),"Traffic history reset")&&(ae(),o())},"negative")])}function ve(n,e,r){let o=t("button",{type:"button",role:"switch",class:`dl-switch${n?" on":""}`,"aria-checked":n?"true":"false","aria-label":e,click:()=>{let a=!o.classList.contains("on");eo(o,a),r?.(a)}},t("i"));return o}function eo(n,e){n.classList.toggle("on",e),n.setAttribute("aria-checked",e?"true":"false")}var Pe=n=>n.classList.contains("on");function we(n,e,r={}){n.some(([i])=>i===e)||(n=[...n,[e,e]]);let o=t("div",{class:`dl-seg${r.cls?` ${r.cls}`:""}`,role:"radiogroup","aria-label":r.label??null,"data-value":e}),a=()=>o.querySelectorAll(":scope > button").forEach(i=>{let s=i.dataset.v===o.dataset.value;i.classList.toggle("on",s),i.setAttribute("aria-checked",s?"true":"false")});for(let[i,s]of n)o.appendChild(t("button",{type:"button",role:"radio","data-v":i,click:()=>{i!==o.dataset.value&&(r.optimistic!==!1&&(o.dataset.value=i,a()),r.onChange?.(i))}},s));return a(),o}function qe(n,e,r,o={}){return t("button",{type:"button",...o,class:`dl-chipbtn${e?" on":""}${o.class?` ${o.class}`:""}`,"aria-pressed":e?"true":"false",click:r},n)}function hn(n,e){n.classList.toggle("on",e),n.setAttribute("aria-pressed",e?"true":"false")}function le(n,e={}){return t("input",{type:"text",class:"cbi-input-text",value:n,...e})}var Vi={jc:"0",jmin:"0",jmax:"0",s1:"0",s2:"0",s3:"0",s4:"0",h1:"1",h2:"2",h3:"3",h4:"4",i1:"",i2:"",i3:"",i4:"",i5:""},Ji={header_protection_key:"HeaderProtectionKey",content_padding_addition:"ContentPaddingAddition",rekey_after_time:"RekeyAfterTime",rekey_timeout:"RekeyTimeout",reject_after_time:"RejectAfterTime",keepalive_timeout:"KeepaliveTimeout",max_handshake_attempts:"MaxHandshakeAttempts",random_trailers:"RandomTrailers",disable_cookies:"DisableCookies"};function Yi(n){let e={};for(let[r,o]of Object.entries(Ji))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Zi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Vi[d],i=r.host.replace(/^\[(.*)\]$/,"$1"),s={H1:a("h1"),H2:a("h2"),H3:a("h3"),H4:a("h4"),I1:a("i1"),I2:a("i2"),I3:a("i3"),I4:a("i4"),I5:a("i5"),Jc:a("jc"),Jmin:a("jmin"),Jmax:a("jmax"),S1:a("s1"),S2:a("s2"),S3:a("s3"),S4:a("s4"),...Yi(o),allowed_ips:r.allowed_ips,client_ip:r.client_ip,client_priv_key:r.client_priv_key,client_pub_key:r.client_pub_key,config:n.conf.replace(/\r?\n/g,`\r
|
||||||
`),hostName:i,mtu:o.mtu,persistent_keep_alive:o.persistent_keep_alive,port:Number(o.port),psk_key:o.psk_key,server_pub_key:o.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(o.port),protocol_version:a.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return o.dns[0]&&(l.dns1=o.dns[0]),o.dns[1]&&(l.dns2=o.dns[1]),l}function jr(n){let e="";for(let o=0;o<n.length;o+=32768)e+=String.fromCharCode(...n.subarray(o,o+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ur(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let o=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),a=new Uint8Array(await new e.Response(o).arrayBuffer()),r=new Uint8Array(4+a.length);return new DataView(r.buffer).setUint32(0,n.length,!1),r.set(a,4),r}catch{return null}}async function An(n,e,o=!0){let a=new TextEncoder().encode(JSON.stringify(Or(n,e))),r=o?await Ur(a):null;return`vpn://${jr(r??a)}`}var Mo=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"standard",title:"Standard",ic:"shield",stealth:2,speed:4,text:"Junk packets and random headers. Gets through most VPN blocking with no speed cost.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"strong",title:"Strong",ic:"shieldplus",stealth:3,speed:3,text:"More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.",apps:"Every AmneziaWG and AmneziaVPN app",short:"Any AmneziaWG app"},{id:"balanced",title:"Balanced",ic:"shieldplus",stealth:3,speed:3,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Pt=n=>Mo.find(e=>e.id===n),Wr={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},Gr={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function Lo(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(o=>t("i",{class:o<n?"on":""})))])}function Qt(n,e,o,a,r=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,Mo.map(l=>{let c=!l.needs||n[l.needs],d=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":d?"true":"false","aria-disabled":c?null:"true",class:`dl-method${d?" on":""}${c?"":" off"}`,click:()=>{!c||d||(e=l.id,s(),o(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===a?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[Lo(l.stealth,"Stealth"),Lo(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},c?[v("phone"),t("span",{},l.apps)]:[v("alert"),t("span",{},(r?Wr:Gr)[l.needs])])])}));return s(),i}function So(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var To=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function Fr(n){let e=d=>n[d]!=null&&n[d]!=="",o=To.filter(([d])=>e(d));if(!o.length)return null;let a=(d,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},d==="header_protection_key"?`${n[d].slice(0,6)}••••`:n[d])]),r=(d,p,u,w)=>{let g=To.filter(([m])=>w.includes(m)&&e(m));return g.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},d)]),t("p",{},u),t("div",{class:"dl-pvals"},g.map(([m,k])=>a(m,k)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=o.map(([d,p])=>`${p} = ${n[d]}`).join(`
|
`),hostName:i,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},l={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(s),port:String(r.port),protocol_version:o.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:i};return r.dns[0]&&(l.dns1=r.dns[0]),r.dns[1]&&(l.dns2=r.dns[1]),l}function Qi(n){let e="";for(let r=0;r<n.length;r+=32768)e+=String.fromCharCode(...n.subarray(r,r+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Xi(n){let e=globalThis;if(typeof e.CompressionStream>"u")return null;try{let r=new e.Blob([n]).stream().pipeThrough(new e.CompressionStream("deflate")),o=new Uint8Array(await new e.Response(r).arrayBuffer()),a=new Uint8Array(4+o.length);return new DataView(a.buffer).setUint32(0,n.length,!1),a.set(o,4),a}catch{return null}}async function to(n,e,r=!0){let o=new TextEncoder().encode(JSON.stringify(Zi(n,e))),a=r?await Xi(o):null;return`vpn://${Qi(a??o)}`}var ur=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],Ot=n=>ur.find(e=>e.id===n),fn=n=>n.v3?"max":n.v2?"balanced":"off",jt=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,es={v2:"Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).",v3:"Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1)."},ts={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function pr(n,e){return t("span",{class:"dl-dots",title:`${e}: ${n} of 4`},[t("span",{class:"dl-dots-label"},e),t("span",{class:"dl-dots-row"},[0,1,2,3].map(r=>t("i",{class:r<n?"on":""})))])}function gn(n,e,r,o,a=!0){let i=t("div",{class:"dl-methods",role:"radiogroup","aria-label":"Disguise method"}),s=()=>dom.content(i,ur.map(l=>{let d=!l.needs||n[l.needs],c=l.id===e;return t("button",{type:"button",role:"radio","aria-checked":c?"true":"false","aria-disabled":d?null:"true",class:`dl-method${c?" on":""}${d?"":" off"}`,click:()=>{!d||c||(e=l.id,s(),r(l.id))}},[t("div",{class:"dl-method-head"},[t("span",{class:"dl-method-ic"},v(l.ic)),t("b",{},l.title),l.id===o?t("span",{class:"dl-pill ok"},"Current"):""]),t("p",{},l.text),t("div",{class:"dl-method-meters"},[pr(l.stealth,"Stealth"),pr(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[v(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[v("alert"),t("span",{},(a?es:ts)[l.needs])])])}));return s(),i}function mr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var hr=[["jc","Jc"],["jmin","Jmin"],["jmax","Jmax"],["s1","S1"],["s2","S2"],["s3","S3"],["s4","S4"],["h1","H1"],["h2","H2"],["h3","H3"],["h4","H4"],["i1","I1"],["i2","I2"],["i3","I3"],["i4","I4"],["i5","I5"],["header_protection_key","HeaderProtectionKey"],["content_padding_addition","ContentPaddingAddition"],["rekey_after_time","RekeyAfterTime"],["rekey_timeout","RekeyTimeout"],["reject_after_time","RejectAfterTime"],["keepalive_timeout","KeepaliveTimeout"],["max_handshake_attempts","MaxHandshakeAttempts"],["random_trailers","RandomTrailers"],["disable_cookies","DisableCookies"]];function ns(n){let e=c=>n[c]!=null&&n[c]!=="",r=hr.filter(([c])=>e(c));if(!r.length)return null;let o=(c,p)=>t("span",{class:"dl-pv"},[t("i",{},p),t("b",{},c==="header_protection_key"?`${n[c].slice(0,6)}••••`:n[c])]),a=(c,p,u,x)=>{let $=hr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[v(p),t("b",{},c)]),t("p",{},u),t("div",{class:"dl-pvals"},$.map(([h,m])=>o(h,m)))]):""},i=Number(n.jc||0),s=(n.i1??"").includes("0x8580")?"A first packet shaped like a DNS answer.":"Extra packets sent before the handshake.",l=r.map(([c,p])=>`${p} = ${n[c]}`).join(`
|
||||||
`),c=t("div",{class:"dl-pgrid"},[r("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),r("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),r("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),r("Signatures","globe",s,["i1","i2","i3","i4","i5"]),r("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),r("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(o.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:d=>{d.preventDefault(),ue(l,"Parameters copied")}},"Copy as config")]),c])}function _o(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let o=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!o)return document.createTextNode(n);let a=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},o[1])," ",a&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):o[2]])}function qr(n){let e=!1,o=t("pre",{class:"dl-conf"}),a=()=>dom.content(o,n.conf.split(`
|
`),d=t("div",{class:"dl-pgrid"},[a("Junk packets","zap",i?`${i} random packet${i===1?"":"s"} of ${n.jmin}–${n.jmax} bytes before each handshake.`:"No junk packets.",["jc","jmin","jmax"]),a("Padding","archive","Random bytes in front of handshake, cookie and data packets, so their sizes do not match WireGuard.",["s1","s2","s3","s4"]),a("Packet types","key","The values that replace WireGuard’s recognisable message types.",["h1","h2","h3","h4"]),a("Signatures","globe",s,["i1","i2","i3","i4","i5"]),a("Protection","lock","AmneziaWG 3.1: encrypted headers, random tails and extra padding on data packets.",["header_protection_key","content_padding_addition","random_trailers","disable_cookies"]),a("Timing","clock","Handshake and key timers vary within these ranges instead of WireGuard’s fixed values.",["rekey_after_time","rekey_timeout","reject_after_time","keepalive_timeout","max_handshake_attempts"])]);return t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Current parameters"),t("span",{class:"dl-pcount"},String(r.length)),t("span",{class:"dl-spacer"}),t("button",{type:"button",class:"dl-linkbtn",click:c=>{c.preventDefault(),me(l,"Parameters copied")}},"Copy as config")]),d])}function fr(n,e){if(/^\s*\[.+\]\s*$/.test(n))return t("span",{class:"dl-conf-sec"},n);let r=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(n);if(!r)return document.createTextNode(n);let o=/^(\s*)(PrivateKey|PresharedKey)\b/.test(n);return t("span",{},[t("span",{class:"dl-conf-k"},r[1])," ",o&&!e?t("span",{class:"dl-conf-mask"},"••••••••••••••••"):r[2]])}function os(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
|
||||||
`).flatMap((s,l)=>l?[`
|
`).flatMap((s,l)=>l?[`
|
||||||
`,_o(s,e)]:[_o(s,e)])),r=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(r,[v(e?"x":"key"),e?"Hide key":"Show key"]),a()}},[v("key"),"Show key"]);a();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes · import it in the app`)]),D([v("download")," Download"],()=>Le(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),r,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),o])])}async function Kr(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let o=await An(n,`${n.server} · ${n.person} · ${n.name}`),a={qr:()=>t("div",{class:"dl-qr-pane"},[qe(ft(n.conf),"dl-qr"),t("span",{class:"dl-sub"},"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},o),D("Copy",()=>ue(o,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>qr(n)},r=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===l)),dom.content(r,a[l]())};for(let[l,c]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},c));return s(e),t("div",{class:"dl-stack gap12"},[i,r])}async function Jr(n,e,o,a){let r=Pt(o),s=n.st.people.filter(c=>c.server===e.id).reduce((c,d)=>c+d.devices.length,0);await re(a?"Generate new disguise values?":`Switch to ${r.title}?`,`${s} AmneziaWG device${s===1?"":"s"} stop connecting until they import their configuration again (from their personal link or from you).${o==="max"?" They need an app with AmneziaWG 3.1.":o==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}`,a?"Generate and apply":"Switch and apply",!0)&&await W(()=>P.serverObfuscation(e.id,o),a?"New values applied":`${r.title} applied`)&&(F("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function Vr(n,e){let o=n.st,a=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),r=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=`${e.mtus.computer} for computers and routers, ${e.mtus.phone} for phones and tablets`,s=e.mtu?`Now ${i}. Empty = automatic.`:`Automatic by device type and disguise: now ${i}. Lower it if some sites hang.`,l=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),c=Pt(e.preset)?e.preset:void 0,d=c??"standard",p=D("",()=>Jr(n,e,d,d===c),"neutral"),u=()=>dom.content(p,d===c?[v("reset")," Generate new values"]:[`Switch to ${Pt(d).title}`]);u();let w=o.awg_state?.tools!==!1;return Tt("",[So("AmneziaWG",e.ifname),he("globe","Listening","Where devices reach this core from the internet",[ne("UDP port",a,"Opened on the WAN firewall automatically.")]),he("file","In every device configuration","Changing these marks devices “Update config” until they import again",[ne("MTU",r,s),ne("Keep-alive",l,"Seconds between packets devices send to keep NAT open. 0 = off.")]),he("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[Qt(o.awg,d,g=>{d=g,u()},c,w),w&&!o.awg.v3?ht("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",Fr(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),p])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ne("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ne("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ne("Server public key",t("span",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),D([v("copy")],()=>ue(e.public_key,"Public key copied"),"neutral",{title:"Copy",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]))])])],[t("span",{class:"dl-sub"},"Port, MTU and keep-alive apply at once."),D("Save",()=>n.save({port:a.value,mtu:r.value,keepalive:l.value},"AmneziaWG saved"),"positive")])}function Yr(n){let e=Pt(n.preset),o=n.obf??{},a=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(c=>t("i",{class:c<s?"on":""}))),r=[];+o.jc&&r.
Line truncated
|
`,fr(s,e)]:[fr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[v(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[v("key"),"Show key"]);o();let i=new Blob([n.conf]).size;return t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-filecard"},[t("span",{class:"dl-filecard-ic"},".conf"),t("span",{class:"dl-stack"},[t("span",{class:"dl-mono dl-ellipsis"},n.filename),t("span",{class:"dl-sub"},`AmneziaWG · ${i} bytes`)]),D([v("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),me(n.conf,"Configuration copied")}},[v("copy"),"Copy"])]),r])])}function no(n){let e=n.amnezia.obfuscation??{},r={h1:"1",h2:"2",h3:"3",h4:"4"};return Object.entries(e).every(([o,a])=>a==null||a===""||a===(r[o]??"0"))}async function rs(n,e="file"){if(!n.has_private_key)return t("div",{class:"dl-hint"},"This device generated its own keys in the browser, so its full configuration only exists on that device.");let r=await to(n,n.server),o={qr:()=>t("div",{class:"dl-qr-pane"},[an(n.conf),t("span",{class:"dl-sub"},no(n)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),key:()=>t("div",{class:"dl-stack gap8"},[t("div",{class:"dl-linkbox"},[t("span",{class:"dl-mono"},r),D("Copy",()=>me(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>os(n)},a=t("div",{class:"dl-connect-body"}),i=t("div",{class:"dl-seg"}),s=l=>{i.querySelectorAll("button").forEach(d=>d.classList.toggle("on",d.dataset.id===l)),dom.content(a,o[l]())};for(let[l,d]of[["file","File"],["key","Key"],["qr","QR code"]])i.appendChild(t("button",{type:"button","data-id":l,click:()=>s(l)},d));return s(e),t("div",{class:"dl-stack gap12"},[i,a])}async function as(n,e,r,o){let a=Ot(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await se(o?"Generate new disguise values?":`Switch to ${a.title}?`,`${s} AmneziaWG device${s===1?" stops":"s stop"} connecting until ${s===1?"it imports its":"they import their"} configuration again (from their personal link or from you).${r==="max"?" They need an app with AmneziaWG 3.1.":r==="balanced"?" They need an app with AmneziaWG 2.0 or newer.":""}${n.st.servers.length===1&&s?" To keep the old disguise for some people, add a second server and move them there.":""}`,o?"Generate and apply":"Switch and apply",!0)&&await G(()=>P.serverObfuscation(e.id,r),o?"New values applied":`${a.title} applied`)&&(U("Devices are marked “Update config” until they import again.","info",6e3),await n.refresh())}function is(n,e){let r=n.st,o=le(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=le(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=le(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=Ot(e.preset)?e.preset:void 0,l=s??fn(r.awg),d=D("",()=>as(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[v("reset")," Generate new values"]:[`Switch to ${Ot(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=ge("UDP port",o,()=>Rt(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));P.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=ge("MTU",a,()=>Zo(a.value,e.mtus)),h=ge("Keep-alive",i,()=>Qo(i.value));return Nt("",[mr("AmneziaWG",e.ifname),fe("globe","Listening","Where devices reach this core from the internet",[x]),fe("file","In every device configuration","Changing these marks devices “Update config” until they import again",[$,h]),fe("shield","Disguise","So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard",[jt(e.preset)?ct("warn",[t("b",{},jt(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",gn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?ct("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ns(e.obf??{})??"",t("div",{class:"dl-row-end"},[t("span",{class:"dl-sub"},"Applies at once: every AmneziaWG device imports its configuration again."),d])]),t("details",{class:"dl-params"},[t("summary",{},[v("chevron"),t("span",{},"Tunnel"),t("span",{class:"dl-pcount"},"3")]),t("div",{class:"dl-params-body"},[ce("Interface",t("span",{class:"dl-mono"},`${e.ifname} · router ${e.address}`)),ce("Tunnel subnet",t("span",{class:"dl-mono"},e.subnet),"Device addresses come from it."),ce("Server public key",t("span",{c
Line truncated
|
||||||
`),"Log copied"))]),p,u]),[w],"wide"),m([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},r?"Checking…":"Working…")]);let N=o??null,B=o?.id,E,y=0,S=h=>{B!==h.id&&(B=h.id,e.onJob?.(h))};if(o)e.onJob?.(o);else try{let h=await P.updatesStatus().catch(()=>null);E=h?.job?.id,y=h?.now??0;let f=await P.updatesRun(n);f.job&&f.job.state==="running"&&f.job.id!==E&&(N=f.job,S(f.job))}catch(h){return g=[ve(h)],p.textContent=g[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},ve(h))])),m([k(!0)]),F(ve(h),"error"),null}let b=null,x=0;for(;;){if(await sa(1e3),b=await P.updatesStatus().catch(()=>null),!b){if(++x>60)break;continue}x=0;let h=b.job;if(!h||!ia(h,B,E,y)){if(Date.now()-i>15e3)break;continue}if(S(h),N=h,h.log.length){g=h.log;let f=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=g.join(`
|
`),"Log copied"))]),p,u]),[x],"wide"),h([t("button",{class:"cbi-button cbi-button-neutral spinning",type:"button",disabled:"disabled"},a?"Checking…":"Working…")]);let E=r??null,R=r?.id,C,k=0,y=f=>{R!==f.id&&(R=f.id,e.onJob?.(f))};if(r)e.onJob?.(r);else try{let f=await P.updatesStatus().catch(()=>null);C=f?.job?.id,k=f?.now??0;let g=await P.updatesRun(n);g.job&&g.job.state==="running"&&g.job.id!==C&&(E=g.job,y(g.job))}catch(f){return $=[be(f)],p.textContent=$[0],dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},be(f))])),h([m(!0)]),U(be(f),"error"),null}let w=null,b=0;for(;;){if(await ia(1e3),w=await P.updatesStatus().catch(()=>null),!w){if(++b>60)break;continue}b=0;let f=w.job;if(!f||!aa(f,R,C,k)){if(Date.now()-i>15e3)break;continue}if(y(f),E=f,f.log.length){$=f.log;let g=p.scrollTop+p.clientHeight>=p.scrollHeight-8;p.textContent=$.join(`
|
||||||
`),f&&(p.scrollTop=p.scrollHeight)}if(l.textContent=aa(h,e.version??""),!l.isConnected&&l.textContent&&s.after(l),d.textContent=oa((h.finished??b.now)-h.started),h.state==="running"){c.hidden=!h.phase,c.textContent=h.phase;continue}break}if(p.scrollTop=p.scrollHeight,c.hidden=!1,!N||N.state==="running")return c.className="dl-pill warn",c.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),m([k()]),e.onDone?.(b),N;if(N.state==="failed")return c.className="dl-pill bad",c.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},N.error??"Operation failed"),r?"":". Nothing else was changed."])])),m([D("Copy log",()=>ue(g.join(`
|
`),g&&(p.scrollTop=p.scrollHeight)}if(l.textContent=oa(f,e.version??""),!l.isConnected&&l.textContent&&s.after(l),c.textContent=na((f.finished??w.now)-f.started),f.state==="running"){d.hidden=!f.phase,d.textContent=f.phase;continue}break}if(p.scrollTop=p.scrollHeight,d.hidden=!1,!E||E.state==="running")return d.className="dl-pill warn",d.textContent="No answer",dom.content(u,t("div",{class:"dl-comp-status warn"},[v("alert"),t("span",{},"The router stopped answering. The job may still finish: reopen Components in a minute.")])),h([m()]),e.onDone?.(w),E;if(E.state==="failed")return d.className="dl-pill bad",d.textContent="Failed",dom.content(u,t("div",{class:"dl-comp-status bad"},[v("x"),t("span",{},[t("b",{},E.error??"Operation failed"),a?"":". Nothing else was changed."])])),h([D("Copy log",()=>me($.join(`
|
||||||
`),"Log copied")),k(!0)]),F(`${cn[a]??"Update"}: ${N.error??"failed"}`,"error"),e.onDone?.(b),N;if(c.className="dl-pill ok",c.textContent="Finished",r&&b){let h=ra(b,a);if(dom.content(u,t("div",{class:`dl-comp-status ${h.tone}`},[v(h.tone==="ok"?"check":h.tone==="warn"?"alert":"download"),t("span",{},h.text)])),F(h.text,h.tone==="warn"?"warning":"success"),e.onDone?.(b),h.update&&e.onUpdate){let f=b;m([k(),D(`Update to ${h.update}`,()=>e.onUpdate(f),"positive")])}else m([k()]),h.tone==="ok"&&setTimeout(()=>u.isConnected&&de(),1200);return N}if(a==="app"&&N.to){let h=N.to,f=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${h} is installed. `),f])]));let R=()=>{ui.menu?.flushCache(),location.reload()};m([k(),D("Reload now",R,"positive")]),F(`Dawnline updated to ${h}`,"success",6e3);for(let C=1;C<=30;C++)if(f.textContent=`Waiting for the router to restart its services (${C} of 30)…`,await sa(1500),(await P.updatesStatus().catch(()=>null))?.version===h)return f.textContent="Services are back. Reloading…",setTimeout(R,800),N;return f.textContent="Services restarted. Reload the page to use the new version.",N}let M=a==="pkgs"?`Updated ${[...N.result?.pkgs?.updated??[],...N.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:a==="amneziawg"?`AmneziaWG${N.to?` ${N.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},M)])),m([k()]),F(M,"success"),e.onDone?.(b),N}var $i={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function la(n,e,o,a){return!await re(`Install ${e}?`,o,"Install")||(await Bt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>a?.(),4e3),!0)}function un(n){return la("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Ot(n,e,o){return n==="awg"?un(o):e.length?la(`pkgs:${e.join(",")}`,$i[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,o):!0}async function da(n,e){if(n==="awg")return un(e);let o=await W(()=>P.updatesStatus());return o?Ot(n,o.needs?.[n]??[],e):!1}var Ei=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Li={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function ca(n,e,o){let a=n.id,r=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,c="",d=!0,p=!0,u="all",w=!1,g=ea(r,a,o),m=new Set,k="",N=()=>JSON.stringify([p,l,l?"":c,d,[...m].sort()]),B=()=>s.detected.lan||s.saved.lan||"",E=()=>(l?s.detected.wan||s.saved.wan:c)||"",y=()=>new Map(s.devices.map(z=>[z.name,z])),S=()=>{let z=y();return[...d&&B()?[B()]:[],...[...m].filter(X=>X!==B())].filter(X=>X!==E()).map(X=>z.get(X)??{name:X,nets:[],missing:!0})},b=(z,K)=>{s=z,K&&(l=z.config.auto_wan,c=z.config.wan_device||z.detected.wan||z.saved.wan||"",d=z.config.auto_lan,p=z.config.lan_like,u=z.config.mesh??(z.config.device_mesh?"all":"off"),m=new Set(z.config.lan_devices),k=N()),G()},x=async z=>{let K=await P.interfaces(a).catch(X=>(F(X.message,"error"),null));K&&b(K,z)};function M(z){let K=d&&z.name===B(),X=!!z.own||!!z.master||z.name===E()||K;return K||m.has(z.name)||!X&&(z.nets.length>0||!!z.missing)}function h(z){let K=d&&z.name===B(),X=z.name===E(),ce=!K&&m.has(z.name),O=!(!!z.own||!!z.master||X||K)&&(z.nets.length>0||ce||!!z.missing),U=(ce||K)&&!z.zone&&!z.missing,q=z.missing?"Not present right now":z.own?"This server":z.master?`Port of ${z.master}`:X?`Internet${z.zone?` · zone ${z.zone}`:""}`:z.nets.length?z.nets.join(", "):"No IPv4 network",oe=t("button",{type:"button",class:`dl-if${ce?" sel":""}${K?" auto":""}${!O&&!ce&&!K?" off":""}${U?" warn":""}`,"aria-pressed":ce||K?"true":"false","aria-disabled":O?null:"true",click:()=>{O&&(m.has(z.name)?m.delete(z.name):m.add(z.name),G())}},[t("span",{class:"dl-if-ic"},v(Li[z.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},z.name),t("span",{class:"dl-if-sub"},q)]),K?t("span",{class:"dl-if-badge ok"},"Auto"):ce?t("span",{class:"dl-if-check"},v("check")):""]);return me(oe,()=>[t("div",{class:"dl-tip-title"},z.name),t("div",{class:"dl-muted"},[z.logical?`Interface ${z.logical}`:"No netifd interface",z.zone?` · zone ${z.zone}`:" · no firewall zone"]),z.members.length?t("div",{class:"dl-muted"},`Ports: ${z.members.join(", ")}`):"",z.nets.length?t("div",{class:"dl-mono"},z.nets.join(", ")):"",U?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",z.master?t("div",{class:"dl-muted"},`Choose ${z.master} to include it.`):""]),oe}function f(){let z=s.like_home;return!p||!s.config.lan_like
Line truncated
|
`),"Log copied")),m(!0)]),U(`${Mn[o]??"Update"}: ${E.error??"failed"}`,"error"),e.onDone?.(w),E;if(d.className="dl-pill ok",d.textContent="Finished",a&&w){let f=ra(w,o);if(dom.content(u,t("div",{class:`dl-comp-status ${f.tone}`},[v(f.tone==="ok"?"check":f.tone==="warn"?"alert":"download"),t("span",{},f.text)])),U(f.text,f.tone==="warn"?"warning":"success"),e.onDone?.(w),f.update&&e.onUpdate){let g=w;h([m(),D(`Update to ${f.update}`,()=>e.onUpdate(g),"positive")])}else h([m()]),f.tone==="ok"&&setTimeout(()=>u.isConnected&&ae(),1200);return E}if(o==="app"&&E.to){let f=E.to,g=t("span",{},"Waiting for the router to restart its services…");dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},[t("b",{},`Dawnline ${f} is installed. `),g])]));let M=()=>{ui.menu?.flushCache(),location.reload()};h([m(),D("Reload now",M,"positive")]),U(`Dawnline updated to ${f}`,"success",6e3);for(let T=1;T<=30;T++)if(g.textContent=`Waiting for the router to restart its services (${T} of 30)…`,await ia(1500),(await P.updatesStatus().catch(()=>null))?.version===f)return g.textContent="Services are back. Reloading…",setTimeout(M,800),E;return g.textContent="Services restarted. Reload the page to use the new version.",E}let H=o==="pkgs"?`Updated ${[...E.result?.pkgs?.updated??[],...E.result?.pkgs?.installed??[]].join(", ")||"system packages"}`:o==="amneziawg"?`AmneziaWG${E.to?` ${E.to}`:""} is installed`:"Operation completed";return dom.content(u,t("div",{class:"dl-comp-status ok"},[v("check"),t("span",{},H)])),h([m()]),U(H,"success"),e.onDone?.(w),E}var Ds={https:"HTTPS for the portal",acme:"ACME certificates",home:"the home-like link",awg:"AmneziaWG"};async function sa(n,e,r,o){return!await se(`Install ${e}?`,r,"Install")||(await Vt(n,{title:`Installing ${e}`}))?.state!=="done"?!1:(setTimeout(()=>o?.(),4e3),!0)}function Tn(n){return sa("amneziawg:auto","AmneziaWG","Dawnline installs the AmneziaWG build made for this firmware and loads it. If the network service has to restart to learn it, connections drop for a few seconds.",n)}async function Jt(n,e,r){return n==="awg"?Tn(r):e.length?sa(`pkgs:${e.join(",")}`,Ds[n],`${e.join(", ")} from the OpenWrt feeds. Dawnline sets the rest up when they arrive.`,r):!0}async function la(n,e){if(n==="awg")return Tn(e);let r=await G(()=>P.updatesStatus());return r?Jt(n,r.needs?.[n]??[],e):!1}var As=[["wan","WAN"],["ethernet","Ethernet"],["wifi","Wi-Fi"],["vpn","VPN & tunnels"],["other","Other"]],Hs={wan:"globe",ethernet:"ethernet",bridge:"bridge",wifi:"wifi",vpn:"tunnel",other:"link"};function da(n,e,r){let o=n.id,a=e,i=t("div",{class:"dl-stack gap16"},t("section",{class:"dl-setsec"},t("div",{class:"dl-setsec-body"},t("p",{class:"dl-muted"},"Loading interfaces…")))),s,l=!0,d="",c=!0,p=!0,u="all",x=!1,$=Xr(a,o,r),h=new Set,m="",E=()=>JSON.stringify([p,l,l?"":d,c,[...h].sort()]),R=()=>s.detected.lan||s.saved.lan||"",C=()=>(l?s.detected.wan||s.saved.wan:d)||"",k=()=>new Map(s.devices.map(I=>[I.name,I])),y=()=>{let I=k();return[...c&&R()?[R()]:[],...[...h].filter(Q=>Q!==R())].filter(Q=>Q!==C()).map(Q=>I.get(Q)??{name:Q,nets:[],missing:!0})},w=(I,V)=>{s=I,V&&(l=I.config.auto_wan,d=I.config.wan_device||I.detected.wan||I.saved.wan||"",c=I.config.auto_lan,p=I.config.lan_like,u=I.config.mesh??(I.config.device_mesh?"all":"off"),h=new Set(I.config.lan_devices),m=E()),q()},b=async I=>{let V=await P.interfaces(o).catch(Q=>(U(Q.message,"error"),null));V&&w(V,I)};function H(I){let V=c&&I.name===R(),Q=!!I.own||!!I.master||I.name===C()||V;return V||h.has(I.name)||!Q&&(I.nets.length>0||!!I.missing)}function f(I){let V=c&&I.name===R(),Q=I.name===C(),de=!V&&h.has(I.name),B=!(!!I.own||!!I.master||Q||V)&&(I.nets.length>0||de||!!I.missing),F=(de||V)&&!I.zone&&!I.missing,ne=I.missing?"Not present right now":I.own?"This server":I.master?`Port of ${I.master}`:Q?`Internet${I.zone?` · zone ${I.zone}`:""}`:I.nets.length?I.nets.join(", "):"No IPv4 network",pe=t("button",{type:"button",class:`dl-if${de?" sel":""}${V?" auto":""}${!B&&!de&&!V?" off":""}${F?" warn":""}`,"aria-pressed":de||V?"true":"false","aria-disabled":B?null:"true",click:()=>{B&&(h.has(I.name)?h.delete(I.name):h.add(I.name),q())}},[t("span",{class:"dl-if-ic"},v(Hs[I.kind]??"link")),t("span",{class:"dl-if-main"},[t("span",{class:"dl-if-name"},I.name),t("span",{class:"dl-if-sub"},ne)]),V?t("span",{class:"dl-if-badge ok"},"Auto"):de?t("span",{class:"dl-if-check"},v("check")):""]);return he(pe,()=>[t("div",{class:"dl-tip-title"},I.name),t("div",{class:"dl-muted"},[I.logical?`Interface ${I.logical}`:"No netifd interface",I.zone?` · zone ${I.zone}`:" · no firewall zone"]),I.members.length?t("div",{class:"dl-muted"},`Ports: ${I.members.join(", ")}`):"",I.nets.length?t("div",{class:"dl-mono"},I.nets.join(", ")):"",F?t("div",{class:"dl-warn"},"Not in a firewall zone: the firewall rejects this traffic."):"",I.master?t("div",{class:"dl-muted"},`Choose ${I.master} to include it.`):""]),pe}function g(){let I=s.like_home;return!p||!s.config.lan_li
Line truncated
|
||||||
`)){let c=l.trimEnd();if(i){/^```/.test(c.trim())?(e.push(t("pre",{},i.join(`
|
`)){let d=l.trimEnd();if(i){/^```/.test(d.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?(r.length&&s(),a||(a=t("ul",{}),e.push(a)),a.appendChild(t("li",{},o(p[1])))):c.trim()?(a&&(a=null),r.push(c.trim())):s()}return i&&e.push(t("pre",{},i.join(`
|
`))),i=null):i.push(l);continue}if(/^```/.test(d.trim())){s(),i=[];continue}let c=/^(#{1,6})\s+(.*)$/.exec(d),p=/^\s*[-*+]\s+(.*)$/.exec(d)??/^\s*\d+[.)]\s+(.*)$/.exec(d);c?(s(),e.push(t("h5",{},r(c[2])))):p?(a.length&&s(),o||(o=t("ul",{}),e.push(o)),o.appendChild(t("li",{},r(p[1])))):d.trim()?(o&&(o=null),a.push(d.trim())):s()}return i&&e.push(t("pre",{},i.join(`
|
||||||
`))),s(),e}function Ta(n){let e=[],o=!1;for(let a of n.replace(/\r/g,"").split(`
|
`))),s(),e}function Ma(n){let e=[],r=!1;for(let o of n.replace(/\r/g,"").split(`
|
||||||
`)){let r=/^#{1,6}\s+(.*)$/.exec(a);if(r){if(o=/^install\b/i.test(r[1].trim()),/^what.s new$/i.test(r[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(a)&&(o=!1);o||e.push(a)}return e.join(`
|
`)){let a=/^#{1,6}\s+(.*)$/.exec(o);if(a){if(r=/^install\b/i.test(a[1].trim()),/^what.s new$/i.test(a[1].trim()))continue}else/^\*\*Full Changelog\*\*/.test(o)&&(r=!1);r||e.push(o)}return e.join(`
|
||||||
`).replace(/\n{3,}/g,`
|
`).replace(/\n{3,}/g,`
|
||||||
|
|
||||||
`).trim()}async function Ut(n,e,o,a){let r=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";ae(o,[i,r],[D([v("copy")," Copy"],()=>ue(s,"Release notes copied"))," ",le("Close")],"wide");try{let l=await P.updatesNotes(n,e,a??"");s=Ta(l.body||"");let c=Ma(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},He(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),c?t("a",{href:c,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(r,s.trim()?Sa(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(r,t("p",{class:"dl-muted"},ve(l)))}}var _a={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Zn=n=>n?He(n):"";function Oi(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function Pa(n,e){let o=n.st,a=o.policy,r=o.kept?.app,i=e?.update&&e.tag?e.tag:o.version,s=w=>()=>Ut("app",w,`What’s new in Dawnline ${w.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?ji(n,e.tag,e.update?o.version:""):null,c=e?.tag??i,d=a.check&&o.auto?.check?o.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[a.interval]??24)*3600:0,p=(w,g)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},w),t("span",{class:"dl-comp-side-v"},g)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${o.repo}`,"_blank","noopener")},null,{label:`Reinstall ${o.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",o.version)},r?{label:`Roll back to ${r.version}`,ic:"archive",warn:!0,run:async()=>{await re(`Roll back to Dawnline ${r.version}?`,`The copy kept on the router replaces ${o.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",o.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",o.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[o.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Zn(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Zn(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(w=>t("li",{},w))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(c)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",o.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Ui(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${o.repo}`,target:"_blank",rel:"noopener"},o.repo)]),p("Auto-update",[a.auto?ye("ok","On"):ye("","Off"),t("span",{class:"dl-muted"},a.auto?a.mode==="immediate"?"as soon as found":`${_a[a.interval]==="weekly"?"weekly":"daily"} at ${a.time}`:a.check?`checks ${_a[a.interval]}`:"checks off")]),p("Last check",o.check?[ie(o.check.time,o.now),d>o.now?t("span",{class:"dl-faint"},`· next in ${pt(d-o.now)}`):""]:["Never"]),p("Rollback",r?[t("span",{class:"dl-mono"},r.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},a.keep?"Kept after the next update":"Off")])])])}function ji(n,e,o){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let a=r=>r.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
`).trim()}async function Zt(n,e,r,o){let a=t("div",{class:"dl-notes"},t("p",{class:"dl-muted dl-loading"},"Loading release notes…")),i=t("div",{class:"dl-op-head"}),s="";oe(r,[i,a],[D([v("copy")," Copy"],()=>me(s,"Release notes copied"))," ",ie("Close")],"wide");try{let l=await P.updatesNotes(n,e,o??"");s=Ma(l.body||"");let d=Ea(l.url);dom.content(i,[l.published?t("span",{class:"dl-pill"},Ue(l.published)):"",l.prerelease?t("span",{class:"dl-pill warn"},"Pre-release"):"",t("span",{class:"dl-spacer"}),d?t("a",{href:d,target:"_blank",rel:"noopener",class:"dl-linkbtn"},["On GitHub ",v("open")]):""]),dom.content(a,s.trim()?La(s):t("p",{class:"dl-muted"},"This release has no notes."))}catch(l){dom.content(a,t("p",{class:"dl-muted"},be(l)))}}var Sa={"6h":"every 6 h","12h":"every 12 h","1d":"daily","7d":"weekly"},Co=n=>n?Ue(n):"";function Js(n){let e=/^(.{20,}?)(?:;\s|:\s)/.exec(n)?.[1];return e||(n.length<=90?n:`${n.slice(0,90).replace(/[\s,;:]+\S*$/,"")}…`)}function _a(n,e){let r=n.st,o=r.policy,a=r.kept?.app,i=e?.update&&e.tag?e.tag:r.version,s=x=>()=>Zt("app",x,`What’s new in Dawnline ${x.replace(/^v/,"")}`),l=e?.tag&&(e.update||e.status==="latest")?Ys(n,e.tag,e.update?r.version:""):null,d=e?.tag??i,c=o.check&&r.auto?.check?r.auto.check+({"6h":6,"12h":12,"1d":24,"7d":168}[o.interval]??24)*3600:0,p=(x,$)=>t("div",{class:"dl-stack gap4"},[t("span",{class:"dl-metric-label"},x),t("span",{class:"dl-comp-side-v"},$)]),u=[{label:"What’s new",ic:"file",run:s(i)},{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${r.repo}`,"_blank","noopener")},null,{label:`Reinstall ${r.version}`,ic:"reset",warn:!0,run:()=>n.op("app:reinstall","Reinstalling Dawnline",r.version)},a?{label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back to Dawnline ${a.version}?`,`The copy kept on the router replaces ${r.version}. A backup of the settings is made first.`,"Roll back")&&n.op("app:rollback","Rolling back Dawnline",r.version)}}:null];return t("section",{class:"dl-panel flush dl-comp-hero"},[t("div",{class:"dl-comp-hero-main"},[t("div",{class:"dl-comp-hero-head"},[t("span",{class:"dl-group-ic"},v("sunrise")),t("b",{class:"dl-comp-name"},"Dawnline"),n.state("app",e,e?.latest??""),t("span",{class:"dl-spacer"}),n.round(()=>n.op("check:app","Checking Dawnline",r.version),u,!0)]),t("div",{class:"dl-comp-verrow"},[t("div",{class:"dl-stack"},[t("div",{class:"dl-comp-big"},[r.version,e?.update?t("small",{},`→ ${e.latest}`):e?.status==="dev"&&e.latest?t("small",{class:"dl-faint"},`release ${e.latest}`):""]),t("span",{class:"dl-faint dl-comp-meta"},e?.error?"":e?.update?e.published?`released ${Co(e.published)}`:"":e?.status==="dev"?"ahead of the latest release":e?`latest release${e.published?` · released ${Co(e.published)}`:""}`:"not checked yet")])]),l?.items.length?t("div",{class:"dl-stack gap4"},[t("ul",{class:"dl-comp-bullets"},l.items.map(x=>t("li",{},x))),l.total>l.items.length?t("button",{type:"button",class:"dl-linkbtn dl-comp-more",click:s(d)},`+${l.total-l.items.length} more in What’s new`):""]):"",e?.error?t("p",{class:"dl-sub dl-comp-lead dl-upd-bad"},e.error):"",e?.update?t("div",{class:"dl-comp-btns"},[D("Update now",()=>n.op("app","Updating Dawnline",r.version),"positive",{disabled:n.busy}),D("What’s new",s(i))]):"",Zs(n)]),t("div",{class:"dl-comp-hero-side"},[p("Source",[v("globe"),t("a",{href:`https://github.com/${r.repo}`,target:"_blank",rel:"noopener"},r.repo)]),p("Auto-update",[o.auto?Ee("ok","On"):Ee("","Off"),t("span",{class:"dl-muted"},o.auto?o.mode==="immediate"?"as soon as found":`${Sa[o.interval]==="weekly"?"weekly":"daily"} at ${o.time}`:o.check?`checks ${Sa[o.interval]}`:"checks off")]),p("Last check",r.check?[re(r.check.time,r.now),c>r.now?t("span",{class:"dl-faint"},`· next in ${xt(c-r.now)}`):""]:["Never"]),p("Rollback",a?[t("span",{class:"dl-mono"},a.version),t("span",{class:"dl-faint"},"kept on flash")]:[t("span",{class:"dl-muted"},o.keep?"Kept after the next update":"Off")])])])}function Ys(n,e,r){if(n.notes.has(e))return n.notes.get(e)??null;n.notes.set(e,null);let o=a=>a.replace(/\*\*|`|\[([^\]]+)\]\([^)]*\)/g,(i,s)=>s??"").trim();return(async()=>{let i=((await P.updatesNotes("app",e,"").catch(()=>null))?.body??"").split(`
|
||||||
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(o,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Oi(a(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Ui(n){let e=t("div",{class:"dl-params-body"}),o=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return o.addEventListener("toggle",()=>{n.versOpen=o.open,n.versOpen&&xn(n,e)}),n.versOpen&&xn(n,e),o}async function xn(n,e){let o=se("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),a=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return F("Enter a release tag like 0.3.1","warning");Ca(n,p)};o.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),a(o.value))});let r=t("div",{class:"dl-comp-tag"},[o,D("Install",()=>a(o.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),xn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),c=n.versCache.get(i);if(!c){dom.content(e,[r,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{c=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[r,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${ve(p)}`),D("Try again",()=>xn(n,e))]),l(!1)]);return}if(n.versCache.set(i,c),i!==n.versPage||!e.isConnected)return}if(!c.length)return dom.content(e,[r,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let d=n.st.version;dom.content(e,[r,...c.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Zn(p.published)),p.prerelease?ye("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},$e("file","What’s new",()=>Ut("app",p.tag,`What’s new in Dawnline ${u}`))),u===d?ye("ok","Installed"):D("Install",()=>Ca(n,p.tag),"neutral",{disabled:n.busy})])}),l(c.length>=5)])}async function Ca(n,e){let o=e.replace(/^v/,"");o.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await re(`Install Dawnline ${o}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${o}`,n.st.version)}function Da(n,e){let o=n.st,a=o.kept?.amneziawg,r=e?.sources??{},i=Object.keys(r),s=e?.current??null,l=s?r[s]:void 0,c=!!e?.ru,d=o.needs?.awg??[],p=d.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${c?":ru":""}`,"Reinstalling AmneziaWG",p)}),a&&u.push({label:`Roll back to ${a.version}`,ic:"archive",warn:!0,run:async()=>{await re(`Roll back AmneziaWG to ${a.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let w=[e?.release?{label:"What’s new",ic:"file",run:()=>Ut("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((h,f,R)=>h!==null||f>0&&R[f-1]!==null),g=o.tunnels??[],m=g.length?`Switching restarts ${g.length===1?"the tunnel":`${g.length} tunnels`} for a few seconds: ${g.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",k=g.length>1?`${g.slice(0,-1).join(", ")} and ${g[g.length-1]}`:g[0],N=g.length?`Switching restarts ${k} for a few seconds.`:"Switching takes a few seconds.",B=async h=>{let f=r[h];await re(p?`Switch to AmneziaWG ${f.gen}?`:`Install AmneziaWG ${f.gen}?`,`The ${f.label} build, ${f.version}. ${m}${f.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${h}${c?":ru":""}`,p?`Switching to AmneziaWG ${f.gen}`:"Installing AmneziaWG",p??void 0)},E=h=>{let f=r[h],R=s===h&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},f.gen?`AmneziaWG ${f.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${f.label} · ${f.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},f.version??"none yet"),t("span",{class:"dl-comp-bact"},R?ye("ok","Active"):f.version?D(p?"Switch":"Install",()=>B(h),p?"neutral":"positive",{disabled:n.busy}):ye("","No build"))])},y=i.map(h=>r[h]?.newer?`${r[h].label} moves to ${r[h].newer.gen} with OpenWrt ${r[h].newer.tag.replace(
Line truncated
|
`).map(l=>/^\s*[-*+]\s+(.*)$/.exec(l)?.[1]).filter(l=>!!l);i.length||(i=(await P.updatesChanges(r,e).catch(()=>null))?.items??[]);let s={items:i.slice(0,3).map(l=>Js(o(l))),total:i.length};n.notes.set(e,s),s.items.length&&n.root.isConnected&&n.paint()})(),null}function Zs(n){let e=t("div",{class:"dl-params-body"}),r=t("details",{class:"dl-params dl-comp-vers",open:n.versOpen?"open":null},[t("summary",{},[v("chevron"),t("span",{},"Versions"),t("span",{class:"dl-sub"},"install any release")]),e]);return r.addEventListener("toggle",()=>{n.versOpen=r.open,n.versOpen&&Nn(n,e)}),n.versOpen&&Nn(n,e),r}async function Nn(n,e){let r=le("",{placeholder:"Tag, e.g. 0.3.1",class:"cbi-input-text dl-mono","aria-label":"Release tag"}),o=p=>{if(p=p.trim(),!/^v?[0-9][0-9A-Za-z.+~-]{0,40}$/.test(p))return U("Enter a release tag like 0.3.1","warning");Ta(n,p)};r.addEventListener("keydown",p=>{p.key==="Enter"&&(p.preventDefault(),o(r.value))});let a=t("div",{class:"dl-comp-tag"},[r,D("Install",()=>o(r.value),"neutral",{disabled:n.busy})]),i=n.versPage,s=p=>{n.versPage=Math.max(1,n.versPage+p),Nn(n,e)},l=p=>t("div",{class:"dl-comp-pager"},[t("button",{type:"button",class:"dl-linkbtn",disabled:i<=1?"disabled":null,click:()=>s(-1)},"← Newer"),t("span",{class:"dl-faint"},`Page ${i}`),t("button",{type:"button",class:"dl-linkbtn",disabled:p?null:"disabled",click:()=>s(1)},"Older →")]),d=n.versCache.get(i);if(!d){dom.content(e,[a,t("p",{class:"dl-muted dl-loading"},"Loading versions…")]);try{d=(await P.updatesReleases(i)).releases}catch(p){if(i!==n.versPage||!e.isConnected)return;dom.content(e,[a,t("div",{class:"dl-row-actions"},[t("span",{class:"dl-muted"},`Failed to load versions: ${be(p)}`),D("Try again",()=>Nn(n,e))]),l(!1)]);return}if(n.versCache.set(i,d),i!==n.versPage||!e.isConnected)return}if(!d.length)return dom.content(e,[a,t("p",{class:"dl-muted"},i>1?"No more versions.":"No versions found."),l(!1)]);let c=n.st.version;dom.content(e,[a,...d.map(p=>{let u=p.tag.replace(/^v/,"");return t("div",{class:"dl-comp-ver"},[t("span",{class:"dl-mono"},u),t("span",{class:"dl-sub"},Co(p.published)),p.prerelease?Ee("warn","Pre-release"):"",t("span",{class:"dl-comp-ic"},Le("file","What’s new",()=>Zt("app",p.tag,`What’s new in Dawnline ${u}`))),u===c?Ee("ok","Installed"):D("Install",()=>Ta(n,p.tag),"neutral",{disabled:n.busy})])}),l(d.length>=5)])}async function Ta(n,e){let r=e.replace(/^v/,"");r.localeCompare(n.st.version,void 0,{numeric:!0})<0&&!await se(`Install Dawnline ${r}?`,`It is older than ${n.st.version}. A backup of the settings is made first; restore it from Settings if something looks wrong.`,"Install")||n.op(`app@${e}`,`Installing Dawnline ${r}`,n.st.version)}function Pa(n,e){let r=n.st,o=r.kept?.amneziawg,a=e?.sources??{},i=Object.keys(a),s=e?.current??null,l=s?a[s]:void 0,d=!!e?.ru,c=r.needs?.awg??[],p=c.length?null:e?.installed??null,u=[];s&&p&&u.push({label:"Reinstall this build",warn:!0,ic:"reset",run:()=>n.op(`amneziawg:${s}${d?":ru":""}`,"Reinstalling AmneziaWG",p)}),o&&u.push({label:`Roll back to ${o.version}`,ic:"archive",warn:!0,run:async()=>{await se(`Roll back AmneziaWG to ${o.version}?`,"The build kept on the router is installed again. Every AmneziaWG tunnel restarts for a few seconds.","Roll back")&&n.op("amneziawg:rollback","Rolling back AmneziaWG",p??void 0)}});let x=[e?.release?{label:"What’s new",ic:"file",run:()=>Zt("amneziawg",e.release,`What’s new in the ${l?.label??"AmneziaWG"} build`,s??"slava")}:null,{label:"Open on GitHub",ic:"globe",run:()=>window.open(`https://github.com/${l?.repo??"Slava-Shchipunov/awg-openwrt"}`,"_blank","noopener")},...u.length?[null,...u]:[]].filter((f,g,M)=>f!==null||g>0&&M[g-1]!==null),$=r.tunnels??[],h=$.length?`Switching restarts ${$.length===1?"the tunnel":`${$.length} tunnels`} for a few seconds: ${$.join(", ")}. Devices keep their configurations.`:"Switching takes a few seconds. Devices keep their configurations.",m=$.length>1?`${$.slice(0,-1).join(", ")} and ${$[$.length-1]}`:$[0],E=$.length?`Switching restarts ${m} for a few seconds.`:"Switching takes a few seconds.",R=async f=>{let g=a[f];await se(p?`Switch to AmneziaWG ${g.gen}?`:`Install AmneziaWG ${g.gen}?`,`The ${g.label} build, ${g.version}. ${h}${g.gen==="3.1"?" Devices need AmneziaVPN 3.1 or newer.":""}`,p?"Switch":"Install")&&n.op(`amneziawg:${f}${d?":ru":""}`,p?`Switching to AmneziaWG ${g.gen}`:"Installing AmneziaWG",p??void 0)},C=f=>{let g=a[f],M=s===f&&!!p;return t("div",{class:"dl-row"},[t("span",{class:"dl-row-main dl-stack"},[t("b",{},g.gen?`AmneziaWG ${g.gen}`:"AmneziaWG"),t("span",{class:"dl-sub"},`${g.label} · ${g.gen==="3.1"?"AmneziaVPN 3.1+":"every app"}`)]),t("span",{class:"dl-mono dl-faint dl-comp-bver"},g.version??"none yet"),t("span",{class:"dl-comp-bact"},M?Ee("ok","Active"):g.version?D(p?"Switch":"Install",()=>R(f),p?"neutral":"positive",{disabled:n.busy}):Ee("","No build"))])},k=i.map(f=>a[f]?.newer?`${a[f].label} moves to ${a[f].newer.gen} with OpenWrt ${a[f].newer.tag.replace(
Line truncated
|
||||||
`)}r.push(p),l+=d-1}let s=D([v("more")],()=>we(s,[{label:"Export CSV",icon:v("download"),run:()=>Ue(o,a,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Ue(o,a,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>Ke(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},a.length>10?`latest 10 of ${a.length}`:""),t("span",{class:"dl-spacer"}),s]),r.length?r:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var yn=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[o,a,r]=await Promise.all([P.status(30),e?P.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:o,ev:a?.events??null,use:r}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let o=this.st.people.find(s=>s.id===this.id);if(!o)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=o;for(let s of["head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let a=t("div",{},[t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:wt(o.server)},this.st.servers.find(s=>s.id===o.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:wt(o.server)},"People"),t("span",{},"/"),t("span",{},o.name)]),this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let r=new URLSearchParams(location.search),i=r.get("device")&&o.devices.find(s=>s.id===r.get("device"));return i?setTimeout(()=>Be(this.p,i,this.deviceOpts()),50):r.get("add")&&setTimeout(()=>it(this.p,this.deviceOpts()),50),this.poller=Ve({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>a.isConnected,apply:(s,l)=>this.apply(s,l)}),a}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,o){this.take(e);let a=this.st.people.find(r=>r.id===this.id);if(!a){o||(location.href=wt(this.p?.server));return}this.p=a,this.paint(o),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,o){var i;this.poller?.claim();let a=await W(()=>P.personUpdate(this.p.id,e),o);if(!a)return!1;this.poller?.claim();let r=this.st.people.findIndex(s=>s.id===this.p.id);return(i=a.person).rate??(i.rate=this.p.rate),r>=0&&(this.st.people[r]=a.person),this.p=a.person,this.paint(),!0}get today(){return Re(this.series.length?this.series:this.st.series)}get core(){return bt(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}paint(e=!1){Me(this.parts.head,ja(this),e),Me(this.parts.traffic,Ua(this),e),Me(this.parts.devices,Wa(this),e),Me(this.parts.limits,Ya(this),e),this.paintPlaces(e),Me(this.parts.activity,Qa(this),e)}paintPlaces(e=!1){let o=Za(this);o&&Me(this.parts.places,o,e&&!this.mapOpen)}};var Qi={ok:"check",warn:"alert",error:"x",skip:"pause"},kn=class{constructor(e,o,a,r){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=o,this.events=a,this.toLog=r,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(o,a)}async run(e){let o=e?await gn(e):await P.health().catch(()=>null);o&&(this.take(o),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let o=e.filter(s=>s.status==="error").length,a=e.filter(s=>s.status==="warn").length;dom.content(this.summary,o?ht("error",`${o} problem${o>1?"s":""} need attention.`):a?ht("warn",`${a} warning${a>1?"s":""}.`):ht("ok","All checks passed."));let r=new Map;for(let s of this.sl.watchdog
Line truncated
|
`)}a.push(p),l+=c-1}let s=D([v("more")],()=>Ce(s,[{label:"Export CSV",icon:v("download"),run:()=>Fe(r,o,"csv",e.id)},{label:"Export JSON",icon:v("download"),run:()=>Fe(r,o,"json",e.id)},null,{label:`Clear ${e.name}'s activity`,icon:v("trash"),danger:!0,run:()=>et(`Clear ${e.name}'s activity`,`Removes events about ${e.name} and their devices.`,{person:e.id},()=>n.refresh())}]),"neutral",{title:"Export or clear",class:"cbi-button cbi-button-neutral dl-icon-only"});return t("div",{class:"dl-panel flush"},[t("div",{class:"dl-panel-head pad"},[t("h3",{},"Activity"),t("span",{class:"dl-sub"},o.length>10?`latest 10 of ${o.length}`:""),t("span",{class:"dl-spacer"}),s]),a.length?a:t("div",{class:"dl-row dl-muted"},"Nothing yet.")])}var In=class{constructor(){this.id="";this.events=[];this.mapOpen=!1;this.map=null;this.parts={};this.series=[];this.devSeries={};this.ticks=0;this.fullNext=!1}async fetch(e){let[r,o,a]=await Promise.all([P.status(30),e?P.events(2e3,this.id).catch(()=>null):Promise.resolve(null),e?P.personUsage(this.id,30).catch(()=>null):Promise.resolve(null)]);return{st:r,ev:o?.events??null,use:a}}async load(){return this.id=new URLSearchParams(location.search).get("id")??"",this.fetch(!0)}render(e){this.take(e);let r=this.st.people.find(s=>s.id===this.id);if(!r)return t("div",{class:"dl-empty"},[t("h3",{},"Person not found"),t("p",{},"They may have been removed."),t("a",{class:"cbi-button",href:L.url("admin/network/dawnline/server")},"Back to Servers")]);this.p=r;for(let s of["crumbs","head","devices","traffic","places","activity","limits"])this.parts[s]=t("div",{});this.parts.devices.className="dl-person-devices";let o=t("div",{},[this.parts.crumbs,this.parts.head,t("div",{class:"dl-grid-person"},[t("div",{class:"dl-col"},[this.parts.devices,this.parts.traffic,this.parts.places,this.parts.activity]),t("div",{class:"dl-col"},[this.parts.limits])])]);this.paint();let a=new URLSearchParams(location.search),i=a.get("device")&&r.devices.find(s=>s.id===a.get("device"));return i?setTimeout(()=>Ge(this.p,i,this.deviceOpts()),50):a.get("add")&&setTimeout(()=>nt(this.p,this.deviceOpts()),50),this.poller=ot({fetch:s=>{let l=s||this.fullNext||++this.ticks%4===0;return this.fullNext=!1,this.fetch(l)},every:15,live:!0,active:()=>o.isConnected,apply:(s,l)=>this.apply(s,l)}),o}take(e){this.st=e.st,e.ev&&(this.events=e.ev),e.use&&(this.series=e.use.person,this.devSeries=e.use.devices)}apply(e,r){this.take(e);let o=this.st.people.find(a=>a.id===this.id);if(!o){r||(location.href=_t(this.p?.server));return}this.p=o,this.paint(r),this.map?.update(this.mapData())}async refresh(){this.fullNext=!0,await this.poller?.refresh()}async patch(e,r){var i;this.poller?.claim();let o=await G(()=>P.personUpdate(this.p.id,e),r);if(!o)return!1;this.poller?.claim();let a=this.st.people.findIndex(s=>s.id===this.p.id);return(i=o.person).rate??(i.rate=this.p.rate),a>=0&&(this.st.people[a]=o.person),this.p=o.person,this.paint(),!0}get today(){return Ie(this.series.length?this.series:this.st.series)}get core(){return St(this.st.servers,this.p.server)}deviceOpts(){return{refresh:()=>this.refresh(),geo:this.st.geo,now:this.st.now,today:this.today,core:this.core,events:()=>this.events}}mapData(){return{geo:this.st.geo,people:this.st.people,now:this.st.now,person:this.p.id}}crumbs(){let e=this.p;return t("nav",{class:"dl-crumbs","aria-label":"Breadcrumb"},[t("a",{href:_t(e.server)},this.st.servers.find(r=>r.id===e.server)?.name??"Servers"),t("span",{},"/"),t("a",{href:_t(e.server)},"People"),t("span",{},"/"),t("span",{},e.name)])}paint(e=!1){Se(this.parts.crumbs,this.crumbs(),e),Se(this.parts.head,ja(this),e),Se(this.parts.traffic,Ua(this),e),Se(this.parts.devices,Ga(this),e),Se(this.parts.limits,Ya(this),e),this.paintPlaces(e),Se(this.parts.activity,Qa(this),e)}paintPlaces(e=!1){let r=Za(this);r&&Se(this.parts.places,r,e&&!this.mapOpen)}};var sl={ok:"check",warn:"alert",error:"x",skip:"pause"},Bn=class{constructor(e,r,o,a){this.el=t("div",{});this.wdEl=t("div",{});this.checksEl=t("div",{class:"dl-panel"});this.recentEl=t("div",{class:"dl-panel flush dl-recent"});this.checks=null;this.summary=t("div",{});this.open=new Set;this.st=e,this.sl=r,this.events=o,this.toLog=a,dom.content(this.el,[this.summary,this.wdEl,t("div",{class:"dl-health-cols"},[this.checksEl,this.recentEl])]),this.paintChecks(),this.paintLive(r,o)}async run(e){let r=e?await An(e):await P.health().catch(()=>null);r&&(this.take(r),e==="netrestart"&&setTimeout(()=>this.el.isConnected&&void this.run(),5e3))}take(e){this.checks=e.checks,this.paintChecks(),this.paintLive(e,this.events)}paintChecks(){let e=this.checks;if(!e){dom.content(this.summary,""),dom.content(this.checksEl,[t("div",{class:"dl-panel-head"},[t("h3",{},"Checks")]),t("p",{class:"dl-muted dl-loading"},"Running checks…")]);return}let r=e.filter(s=>s.status==="error").length,o=e.filter(s=>s.status==="warn").length;dom.content(this.summary,r?ct("error",`${r} problem${r>1?"s":""} need attention.`):o?ct("warn",`${o} warnLine truncated
|
||||||
`);function hr(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=gs,n}function lt(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async a=>{let r=await e.render(a),i=document.createElement("div");return i.className="dl-root",i.append(hr(),r),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var zg=lt(jt),Ng=lt(st),Hg=lt(jt),Rg=lt(bn),Ig=lt(yn),Bg=lt(Ln),Og=lt(wn);function fr(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var jg=fr(""),Ug=fr("log");return baseclass.extend({ activity: Ug, diagnostics: Bg, health: jg, overview: zg, people: Ng, person: Ig, server: Hg, settings: Rg, updates: Og });
|
`);function fi(){let n=document.createElement("style");return n.dataset.dawnline="1",n.textContent=El,n}function ht(n){return()=>{let e=new n;return Object.assign({load:()=>e.load(),render:async o=>{let a=await e.render(o),i=document.createElement("div");return i.className="dl-root",i.append(fi(),a),i},addFooter(){return e.noFooter?document.createElement("div"):this.super("addFooter",[])}},{handleSave:null,handleSaveApply:null,handleReset:null})}}var C1=ht(Yt),E1=ht(mt),L1=ht(Yt),M1=ht(zn),S1=ht(In),T1=ht(Un),_1=ht(Rn);function gi(n){return()=>({load:()=>(ui.menu?.flushCache(),location.replace(`${L.url("admin/network/dawnline/diagnostics")}${n?`?tab=${n}`:""}`),new Promise(()=>{})),render:()=>document.createElement("div"),handleSave:null,handleSaveApply:null,handleReset:null})}var P1=gi(""),D1=gi("log");return baseclass.extend({ activity: D1, diagnostics: T1, health: P1, overview: C1, people: E1, person: S1, server: L1, settings: M1, updates: _1 });
|
||||||
@@ -12,11 +12,31 @@ import * as pc from 'dawnline.portalcert';
|
|||||||
import * as watchdog from 'dawnline.watchdog';
|
import * as watchdog from 'dawnline.watchdog';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
import * as store from 'dawnline.store';
|
import * as store from 'dawnline.store';
|
||||||
|
import * as devices from 'dawnline.devices';
|
||||||
import {
|
import {
|
||||||
VERSION, slog, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
|
VERSION, slog, slog_read, sh_out, q, take_iface_intent, read_json, write_json, ensure_dir, with_lock, RUN_DIR
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
|
|
||||||
const args = ARGV;
|
/** Options that take no value. */
|
||||||
|
const FLAGS = [ 'json', 'yes', 'conf' ];
|
||||||
|
|
||||||
|
// Options (--name value, or a bare --flag) can go anywhere; what is left are the words.
|
||||||
|
const opts = {};
|
||||||
|
const args = [];
|
||||||
|
for (let i = 0; i < length(ARGV); i++) {
|
||||||
|
let a = ARGV[i];
|
||||||
|
if (a == '-n')
|
||||||
|
a = '--n';
|
||||||
|
if (substr(a, 0, 2) == '--') {
|
||||||
|
let name = substr(a, 2);
|
||||||
|
if (index(FLAGS, name) >= 0)
|
||||||
|
opts[name] = true;
|
||||||
|
else
|
||||||
|
opts[name] = ARGV[++i] ?? '';
|
||||||
|
}
|
||||||
|
else
|
||||||
|
push(args, a);
|
||||||
|
}
|
||||||
const cmd = args[0] ?? 'help';
|
const cmd = args[0] ?? 'help';
|
||||||
|
|
||||||
function out(v) {
|
function out(v) {
|
||||||
@@ -24,10 +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() {
|
||||||
@@ -39,19 +90,24 @@ Usage: dawnline <command>
|
|||||||
sync Push devices and access rules to the tunnels
|
sync Push devices and access rules to the tunnels
|
||||||
status People and devices with live state (JSON)
|
status People and devices with live state (JSON)
|
||||||
health Run health checks (JSON)
|
health Run health checks (JSON)
|
||||||
|
person ls [--json] Everyone: id, name, access, state, devices, last seen
|
||||||
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
person add <name> [--slug s] [--access lan|internet|both] [--devices n]
|
||||||
[--expires YYYY-MM-DD] [--quota GB]
|
[--expires YYYY-MM-DD] [--quota GB] [--server id]
|
||||||
person link <slug> Print the personal portal link
|
person link <id> Print the personal portal link
|
||||||
person rm <slug> Remove a person and their devices
|
person rm <id> [--yes] Remove a person and their devices (--yes when they have any)
|
||||||
device add <slug> <name> [--kind phone|computer|tablet|router]
|
device ls [person] [--json]
|
||||||
|
device add <person> <name> [--kind phone|computer|tablet|router] [--conf]
|
||||||
device conf <id> Print a device configuration (.conf)
|
device conf <id> Print a device configuration (.conf)
|
||||||
device rm <id> Remove a device
|
device rm <id> Remove a device
|
||||||
backup Create a backup in /etc/dawnline/backups
|
backup Create a backup in /etc/dawnline/backups
|
||||||
portal-cert Print the certificate and key the portal uses
|
portal-cert Print the certificate and key the portal uses
|
||||||
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
|
portal-http-port Print the plain-HTTP port when an IP is among the portal addresses
|
||||||
log Service log: tunnel and service starts, stops, repairs (newest first)
|
log [-n N] [--since 2h|3d|date] [--level error|down|repair|up|info] [--src awg|dawnline|portal] [--json]
|
||||||
|
Service log: tunnel and service starts, stops, repairs (newest first)
|
||||||
teardown Remove everything Dawnline created on the router
|
teardown Remove everything Dawnline created on the router
|
||||||
version`);
|
version
|
||||||
|
|
||||||
|
Exit codes: 0 done, 1 refused or failed, 2 unknown command. health exits 1 when a check fails.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -106,40 +162,100 @@ try {
|
|||||||
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
||||||
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
|
out(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })));
|
||||||
}
|
}
|
||||||
else if (cmd == 'health')
|
else if (cmd == 'health') {
|
||||||
out(health.health());
|
let checks = health.health();
|
||||||
|
out(checks);
|
||||||
|
if (length(filter(checks, (c) => c.status == 'error')))
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
else if (cmd == 'person' && args[1] == 'ls') {
|
||||||
|
let m = core.load(), u = core.load_usage(), d = live.dump(m), st = view.states(m, u);
|
||||||
|
let people = sort(map(values(m.people), (p) => view.person_view(m, p, u, d, st, { admin: true })), (a, b) => a.name < b.name ? -1 : 1);
|
||||||
|
if (opts.json)
|
||||||
|
out(people);
|
||||||
|
else
|
||||||
|
table([ 'ID', 'NAME', 'SERVER', 'ACCESS', 'STATE', 'DEVICES', 'LAST SEEN' ], map(people, (p) => [
|
||||||
|
p.id, p.name, p.server, p.access, p.state, `${length(p.devices)}${p.online ? ` (${p.online} online)` : ''}`,
|
||||||
|
p.online ? 'now' : p.last_seen ? ago(time() - p.last_seen) + ' ago' : 'never',
|
||||||
|
]));
|
||||||
|
}
|
||||||
else if (cmd == 'person' && args[1] == 'add') {
|
else if (cmd == 'person' && args[1] == 'add') {
|
||||||
let id = store.transact((c, m) => core.create_person(c, m, {
|
let id = store.transact((c, m) => core.create_person(c, m, {
|
||||||
name: args[2], slug: opt('slug'), access: opt('access', 'internet'),
|
name: args[2], slug: opt('slug'), access: opt('access', 'internet'), server: opt('server'),
|
||||||
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
|
device_limit: opt('devices'), expires: opt('expires'), quota_gb: opt('quota'),
|
||||||
}));
|
}));
|
||||||
let m2 = core.load();
|
let m2 = core.load();
|
||||||
out(core.portal_url(m2, m2.people[id]) ?? id);
|
live.add_event({ type: 'person_added', person: id, detail: m2.people[id].name, by: 'admin' });
|
||||||
|
out(`Added ${m2.people[id].name} (${id})`);
|
||||||
|
out(core.portal_url(m2, m2.people[id]) ?? 'No personal link: the portal is off.');
|
||||||
}
|
}
|
||||||
else if (cmd == 'person' && args[1] == 'link') {
|
else if (cmd == 'person' && args[1] == 'link') {
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let p = m.people[args[2]] ?? die('Unknown person.');
|
let p = the_person(m, args[2]);
|
||||||
out(core.portal_url(m, p) ?? 'Set settings.portal_host first.');
|
out(core.portal_url(m, p) ?? 'No personal link: the portal is off.');
|
||||||
}
|
}
|
||||||
else if (cmd == 'person' && args[1] == 'rm') {
|
else if (cmd == 'person' && args[1] == 'rm') {
|
||||||
store.transact((c, m) => core.delete_person(c, m, args[2]));
|
let m = core.load();
|
||||||
apply.sync();
|
let p = the_person(m, args[2]);
|
||||||
|
let n = length(p.devices);
|
||||||
|
if (n && !opts.yes)
|
||||||
|
die(`${p.name} has ${n} device${n == 1 ? '' : 's'}: add --yes to remove them too.`);
|
||||||
|
store.transact((c, m) => core.delete_person(c, m, p.id));
|
||||||
|
live.add_event({ type: 'person_removed', person: p.id, detail: p.name, pname: p.name, by: 'admin' });
|
||||||
|
let s = apply.sync();
|
||||||
|
out(`Removed ${p.name}${n ? ` and ${n} device${n == 1 ? '' : 's'}` : ''}.`);
|
||||||
|
if (s.warning)
|
||||||
|
warn(`dawnline: ${s.warning}\n`);
|
||||||
|
}
|
||||||
|
else if (cmd == 'device' && args[1] == 'ls') {
|
||||||
|
let m = core.load(), d = live.dump(m);
|
||||||
|
let who = args[2] ? the_person(m, args[2]) : null;
|
||||||
|
let rows = [];
|
||||||
|
for (let id, dev in m.devices) {
|
||||||
|
let p = m.people[dev.person];
|
||||||
|
if (!p || (who && p.id != who.id))
|
||||||
|
continue;
|
||||||
|
let peer = d.peers[dev.public_key];
|
||||||
|
let online = live.online(d, id, peer);
|
||||||
|
push(rows, { id, person: p.id, name: dev.name, kind: dev.kind, address: dev.address, disabled: dev.disabled,
|
||||||
|
online, handshake: +(peer?.handshake ?? 0) });
|
||||||
|
}
|
||||||
|
rows = sort(rows, (a, b) => (a.person < b.person ? -1 : a.person > b.person ? 1 : 0) || (a.name < b.name ? -1 : 1));
|
||||||
|
if (opts.json)
|
||||||
|
out(rows);
|
||||||
|
else
|
||||||
|
table([ 'ID', 'PERSON', 'NAME', 'KIND', 'ADDRESS', 'STATE' ], map(rows, (r) => [
|
||||||
|
r.id, r.person, r.name, r.kind, r.address,
|
||||||
|
r.disabled ? 'off' : r.online ? 'online' : r.handshake ? `seen ${ago(time() - r.handshake)} ago` : 'never connected',
|
||||||
|
]));
|
||||||
}
|
}
|
||||||
else if (cmd == 'device' && args[1] == 'add') {
|
else if (cmd == 'device' && args[1] == 'add') {
|
||||||
// Keys first: generating them runs the awg tool, not worth holding the config lock for.
|
// Through the same door as LuCI and the portal: event, "issued" marker, capability check.
|
||||||
let keys = awg.new_keys();
|
let m = core.load();
|
||||||
let id = store.transact((c, m) => core.create_device(c, m, args[2], args[3], opt('kind', 'phone'), { by: 'admin', keys }));
|
let p = the_person(m, args[2]);
|
||||||
apply.sync();
|
if (!args[3])
|
||||||
out(id);
|
die('Which name? dawnline device add <person> <name>.');
|
||||||
|
let r = devices.add(p.id, args[3], opt('kind', 'phone'), { by: 'admin' });
|
||||||
|
if (opts.conf)
|
||||||
|
print(r.config.conf);
|
||||||
|
else
|
||||||
|
out(`${r.id} (dawnline device conf ${r.id} prints its configuration)`);
|
||||||
|
if (r.warning)
|
||||||
|
warn(`dawnline: ${r.warning}\n`);
|
||||||
}
|
}
|
||||||
else if (cmd == 'device' && args[1] == 'conf') {
|
else if (cmd == 'device' && args[1] == 'conf') {
|
||||||
let m = core.load();
|
let m = core.load();
|
||||||
let d = m.devices[args[2]] ?? die('Unknown device.');
|
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
|
||||||
|
awg.mark_issued(m, d.id);
|
||||||
print(awg.client_config(m, d).conf);
|
print(awg.client_config(m, d).conf);
|
||||||
}
|
}
|
||||||
else if (cmd == 'device' && args[1] == 'rm') {
|
else if (cmd == 'device' && args[1] == 'rm') {
|
||||||
store.transact((c, m) => core.delete_device(c, m, args[2]));
|
let m = core.load();
|
||||||
apply.sync();
|
let d = m.devices[args[2] ?? ''] ?? die('Unknown device.');
|
||||||
|
let r = devices.remove(d.id, { by: 'admin' });
|
||||||
|
out(`Removed ${d.name} (${m.people[d.person]?.name ?? d.person}).`);
|
||||||
|
if (r.warning)
|
||||||
|
warn(`dawnline: ${r.warning}\n`);
|
||||||
}
|
}
|
||||||
else if (cmd == 'backup')
|
else if (cmd == 'backup')
|
||||||
out(backup.backup_create(opt('reason')));
|
out(backup.backup_create(opt('reason')));
|
||||||
@@ -153,7 +269,22 @@ try {
|
|||||||
out(`${core.portal_http_port(m)}`);
|
out(`${core.portal_http_port(m)}`);
|
||||||
}
|
}
|
||||||
else if (cmd == 'log') {
|
else if (cmd == 'log') {
|
||||||
for (let e in watchdog.view(core.load()).log) {
|
let n = +opt('n', 0) || 0;
|
||||||
|
let since = since_time(opt('since'));
|
||||||
|
let level = opt('level'), src = opt('src');
|
||||||
|
if (level && index([ 'info', 'up', 'down', 'repair', 'error' ], level) < 0)
|
||||||
|
die('--level takes error, down, repair, up or info.');
|
||||||
|
if (src && index([ 'awg', 'dawnline', 'portal' ], src) < 0)
|
||||||
|
die('--src takes awg, dawnline or portal.');
|
||||||
|
let log = filter(slog_read(n && !since && !level && !src ? n : null),
|
||||||
|
(e) => (!since || e.ts >= since) && (!level || e.level == level) && (!src || e.src == src));
|
||||||
|
if (n && length(log) > n)
|
||||||
|
log = slice(log, 0, n);
|
||||||
|
if (opts.json) {
|
||||||
|
out(log);
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
for (let e in log) {
|
||||||
let t = localtime(e.ts);
|
let t = localtime(e.ts);
|
||||||
let text = e.by == 'admin'
|
let text = e.by == 'admin'
|
||||||
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
|
? join(' ', filter([ 'You', e.msg, e.kind, e.who, e.note ? '· ' + e.note : null ], (x) => x))
|
||||||
@@ -197,8 +328,12 @@ try {
|
|||||||
apply.teardown();
|
apply.teardown();
|
||||||
else if (cmd == 'version')
|
else if (cmd == 'version')
|
||||||
out(VERSION);
|
out(VERSION);
|
||||||
else
|
else if (cmd == 'help' || cmd == '--help' || cmd == '-h')
|
||||||
help();
|
help();
|
||||||
|
else {
|
||||||
|
warn(`dawnline: unknown command "${join(' ', slice(args, 0, 2))}" (dawnline help)\n`);
|
||||||
|
exit(2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
warn(`dawnline: ${e.message}\n`);
|
warn(`dawnline: ${e.message}\n`);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
import * as uloop from 'uloop';
|
import * as uloop from 'uloop';
|
||||||
import { open, readfile, writefile, stat, unlink } from 'fs';
|
import { open, readfile, writefile, stat, unlink } from 'fs';
|
||||||
import {
|
import {
|
||||||
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, DATA_DIR, RUN_DIR, VERSION
|
read_json, write_json, ensure_dir, sh_out, q, uniq, slog, slog_trim, slog_restore, date_end, DATA_DIR, RUN_DIR, VERSION
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
@@ -154,41 +154,6 @@ function check_people(m, states, events) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let last_home = 0;
|
|
||||||
// Addresses the watcher saw connect since the last tick: looked up first.
|
|
||||||
let geo_pending = {};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Locate client addresses for the admin map: the ones that just connected
|
|
||||||
* first, then anything still shown that is missing or stale — a few per
|
|
||||||
* minute, within a time budget, so a slow service never holds the tick.
|
|
||||||
*/
|
|
||||||
function check_geo(m) {
|
|
||||||
if (!m.settings.geo_enabled) {
|
|
||||||
geo_pending = {};
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let cache = geo.load();
|
|
||||||
let ips = keys(geo_pending);
|
|
||||||
geo_pending = {};
|
|
||||||
for (let id, rec in usage.devices)
|
|
||||||
for (let ip in keys(rec.ips ?? {}))
|
|
||||||
push(ips, ip);
|
|
||||||
let changed = geo.resolve(m.settings, cache, uniq(ips), 3, 12);
|
|
||||||
if (time() - last_home > 3600) {
|
|
||||||
last_home = time();
|
|
||||||
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
|
||||||
changed = geo.resolve_home(m.settings, cache, wan) || changed;
|
|
||||||
}
|
|
||||||
if (changed)
|
|
||||||
geo.save(cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
function place_of(ip) {
|
|
||||||
let pl = geo.place(geo.load(), ip);
|
|
||||||
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Connections from home: the DHCP name of the address, as it is now. */
|
/** Connections from home: the DHCP name of the address, as it is now. */
|
||||||
function named(e) {
|
function named(e) {
|
||||||
let h = net.event_hosts(e, net.lan_names());
|
let h = net.event_hosts(e, net.lan_names());
|
||||||
@@ -225,6 +190,116 @@ function save_presence(people) {
|
|||||||
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
|
write_json(live.PRESENCE, { online: last_online, endpoint: last_endpoint, rev, people: person_rev }, 0o600);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- locations ---------- */
|
||||||
|
|
||||||
|
// A lookup run: this many addresses at most, within this many seconds; a run
|
||||||
|
// still going after GEO_KILL seconds (past every timeout) is given up.
|
||||||
|
const GEO_PER_RUN = 3;
|
||||||
|
const GEO_BUDGET = 12;
|
||||||
|
const GEO_KILL = 60;
|
||||||
|
|
||||||
|
let last_home = 0;
|
||||||
|
// Addresses the watcher saw connect or roam that wait for a run.
|
||||||
|
let geo_pending = {};
|
||||||
|
// The run in a child process (uloop.task) and when it started; null when none.
|
||||||
|
let geo_task = null, geo_since = 0;
|
||||||
|
|
||||||
|
/** Every client address still shown on the map (the cache never pushes these out). */
|
||||||
|
function geo_shown() {
|
||||||
|
let ips = [];
|
||||||
|
for (let id, rec in usage.devices)
|
||||||
|
for (let ip in keys(rec.ips ?? {}))
|
||||||
|
push(ips, ip);
|
||||||
|
return uniq(ips);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* A run's results: into the cache (the agent is its only writer), onto the
|
||||||
|
* connections in the activity log that were logged before their place was
|
||||||
|
* known, and to open pages at once: the revision moves for the people seen
|
||||||
|
* from those addresses.
|
||||||
|
*/
|
||||||
|
function geo_done(found) {
|
||||||
|
let cache = geo.load();
|
||||||
|
if (type(found) != 'object' || !geo.merge(cache, found, geo_shown()))
|
||||||
|
return;
|
||||||
|
geo.save(cache);
|
||||||
|
let where = {};
|
||||||
|
for (let ip, r in found)
|
||||||
|
if (r)
|
||||||
|
where[ip] = geo.label(r);
|
||||||
|
if (!length(keys(where)))
|
||||||
|
return;
|
||||||
|
let m = watch_model(), people = {};
|
||||||
|
for (let id, rec in usage.devices)
|
||||||
|
for (let ip in keys(where))
|
||||||
|
if (rec.ips?.[ip] && m.devices[id])
|
||||||
|
people[m.devices[id].person] = true;
|
||||||
|
live.set_places(where, time() - 3600);
|
||||||
|
save_presence(keys(people));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Locate client addresses for the admin map in a child process: a lookup
|
||||||
|
* waits on the network for seconds, and neither the 1-second watcher nor the
|
||||||
|
* tick may wait with it. Addresses that just connected go first, at once
|
||||||
|
* (the watcher calls this on a connect); the tick adds anything still shown
|
||||||
|
* that is missing or stale (`more`). One run at a time, a few addresses each;
|
||||||
|
* what just connected and did not fit waits for the next run.
|
||||||
|
*/
|
||||||
|
function geo_lookup(m, more) {
|
||||||
|
if (!m.settings.geo_enabled) {
|
||||||
|
geo_pending = {};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (geo_task && !geo_task.finished()) {
|
||||||
|
if (time() - geo_since < GEO_KILL)
|
||||||
|
return;
|
||||||
|
geo_task.kill();
|
||||||
|
}
|
||||||
|
geo_task = null;
|
||||||
|
let todo = geo.stale(geo.load(), [ ...keys(geo_pending), ...(more ?? []) ]);
|
||||||
|
let want = slice(todo, 0, GEO_PER_RUN);
|
||||||
|
let rest = {};
|
||||||
|
for (let ip in slice(todo, GEO_PER_RUN))
|
||||||
|
if (geo_pending[ip])
|
||||||
|
rest[ip] = true;
|
||||||
|
geo_pending = rest;
|
||||||
|
if (!length(want))
|
||||||
|
return;
|
||||||
|
let provider = m.settings.geo_provider;
|
||||||
|
let t = null;
|
||||||
|
t = uloop.task(() => {
|
||||||
|
// The child shares the instance lock: it must not keep it past the agent (a restart would find it taken).
|
||||||
|
instance.close();
|
||||||
|
return geo.lookup_all(provider, want, GEO_PER_RUN, GEO_BUDGET);
|
||||||
|
}, (found) => {
|
||||||
|
if (geo_task == t)
|
||||||
|
geo_task = null;
|
||||||
|
geo_done(found);
|
||||||
|
if (length(keys(geo_pending)))
|
||||||
|
geo_lookup(watch_model());
|
||||||
|
});
|
||||||
|
geo_task = t;
|
||||||
|
geo_since = time();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The tick: shown addresses missing or stale get a run; the router's own place about hourly. */
|
||||||
|
function check_geo(m) {
|
||||||
|
geo_lookup(m, geo_shown());
|
||||||
|
if (!m.settings.geo_enabled || time() - last_home <= 3600)
|
||||||
|
return;
|
||||||
|
last_home = time();
|
||||||
|
let cache = geo.load();
|
||||||
|
let wan = live.iface_status('wan')?.['ipv4-address']?.[0]?.address;
|
||||||
|
if (geo.resolve_home(m.settings, cache, wan))
|
||||||
|
geo.save(cache);
|
||||||
|
}
|
||||||
|
|
||||||
|
function place_of(ip) {
|
||||||
|
return geo.label(geo.place(geo.load(), ip));
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* One look at the tunnels. Connects (a new handshake from a device that was
|
* One look at the tunnels. Connects (a new handshake from a device that was
|
||||||
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
|
* away), disconnects (its session expired: no handshake for live.ONLINE_WINDOW;
|
||||||
@@ -282,16 +357,19 @@ function watch() {
|
|||||||
return;
|
return;
|
||||||
live.collect(m, usage, d);
|
live.collect(m, usage, d);
|
||||||
live.save_usage(usage, false);
|
live.save_usage(usage, false);
|
||||||
// A location lookup waits on the network: never here, on the next tick
|
// The event carries the place when the cache already knows it. A new
|
||||||
// (check_geo). The event carries the place when the cache already knows it.
|
// address is looked up at once, in a child process (geo_lookup): its place
|
||||||
if (m.settings.geo_enabled)
|
// goes onto this event and the revision moves again when it is known.
|
||||||
for (let ip in ips)
|
|
||||||
geo_pending[ip] = true;
|
|
||||||
for (let e in events)
|
for (let e in events)
|
||||||
if (e.type == 'connect')
|
if (e.type == 'connect')
|
||||||
e.where = place_of(e.detail);
|
e.where = place_of(e.detail);
|
||||||
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
|
live.add_events(map(events, (e) => e.type == 'disconnect' ? e : named(e)), live.policy(m.settings.retention));
|
||||||
save_presence(keys(people));
|
save_presence(keys(people));
|
||||||
|
if (m.settings.geo_enabled && length(ips)) {
|
||||||
|
for (let ip in ips)
|
||||||
|
geo_pending[ip] = true;
|
||||||
|
geo_lookup(m);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// What the service log was already told. On flash: the public address often
|
// What the service log was already told. On flash: the public address often
|
||||||
@@ -306,6 +384,33 @@ function note(k, v) {
|
|||||||
write_json(NOTES, notes, 0o600);
|
write_json(NOTES, notes, 0o600);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* End dates in the activity log: a heads-up once per end date when its
|
||||||
|
* warning window opens, and "keep access" passing it (which changes no
|
||||||
|
* state, so nothing else would say it). Not on a clock that is not set.
|
||||||
|
*/
|
||||||
|
function check_expiry(m, events) {
|
||||||
|
let ts = time();
|
||||||
|
if (localtime(ts).year < 2025)
|
||||||
|
return;
|
||||||
|
for (let id, p in m.people) {
|
||||||
|
if (!p.expires)
|
||||||
|
continue;
|
||||||
|
let end = date_end(p.expires);
|
||||||
|
if (end == null)
|
||||||
|
continue;
|
||||||
|
let left = end > ts ? int((end - ts) / 86400) + 1 : 0;
|
||||||
|
if (left > 0 && p.expire_warn > 0 && left <= p.expire_warn && notes[`warned:${id}`] != p.expires) {
|
||||||
|
note(`warned:${id}`, p.expires);
|
||||||
|
push(events, { type: 'expiring', person: id, detail: `${left} day${left == 1 ? '' : 's'}` });
|
||||||
|
}
|
||||||
|
if (left == 0 && p.expire_action == 'notify' && notes[`kept:${id}`] != p.expires) {
|
||||||
|
note(`kept:${id}`, p.expires);
|
||||||
|
push(events, { type: 'expired_kept', person: id, detail: p.expires });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** "Jan 1 2027" from the certificate, or null. */
|
/** "Jan 1 2027" from the certificate, or null. */
|
||||||
function cert_end(path) {
|
function cert_end(path) {
|
||||||
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
|
let m = match(sh_out(`openssl x509 -enddate -noout -in ${q(path)} 2>/dev/null`) ?? '', /notAfter=([A-Za-z]+) +([0-9]+) [0-9:]+ ([0-9]+)/);
|
||||||
@@ -464,6 +569,7 @@ const STEPS = [
|
|||||||
{ who: 'People', run: (t) => {
|
{ who: 'People', run: (t) => {
|
||||||
t.states = apply.states_for(t.m, usage);
|
t.states = apply.states_for(t.m, usage);
|
||||||
check_people(t.m, t.states, t.events);
|
check_people(t.m, t.states, t.events);
|
||||||
|
check_expiry(t.m, t.events);
|
||||||
} },
|
} },
|
||||||
{ who: 'Access rules', run: (t) => {
|
{ who: 'Access rules', run: (t) => {
|
||||||
if (t.states)
|
if (t.states)
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{--bg: #fcfcfc;--card: #ffffff;--elevated: #ffffff;--text: #0d0d0d;--muted: #5d5d5d;--faint: #8f8f8f;--line: #0000001a;--input: #00000026;--soft: #0d0d0d0d;--soft-hover: #0d0d0d1a;--primary: #0d0d0d;--primary-fg: #ffffff;--accent: #3a83f7;--info: #2c67c5;--ok: #00a240;--ok-wash: #00a24026;--warn: #e25507;--warn-wash: #e2550726;--bad: #e02e2a;--bad-wash: #e02e2a1f;--chart: #3a83f7;--track: #0d0d0d1a;--scrim: #00000040;--shadow: 0 1px 2px -1px #00000014;--shadow-xl: 0 8px 16px -4px #0000001f;--radius: 16px;--mono: "Geist Mono", ui-monospace, Menlo, monospace;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg: #000000;--card: #0a0a0a;--elevated: #131313;--text: #ededed;--muted: #edededa6;--faint: #ededed78;--line: #ededed13;--input: #ededed24;--soft: #ededed0d;--soft-hover: #ededed1a;--primary: #ededed;--primary-fg: #131313;--accent: #006efe;--info: #5ba2fe;--ok: #40c977;--ok-wash: #40c97726;--warn: #ff8549;--warn-wash: #ff854926;--bad: #ff6764;--bad-wash: #ff676422;--chart: #3a83f7;--track: #ededed1a;--scrim: #00000099;--shadow: none;--shadow-xl: 0 8px 16px -4px #00000080}}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--text);font:400 15px/22px Geist,-apple-system,system-ui,Segoe UI,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh}body.locked{overflow:hidden}a{color:var(--info);text-decoration:none}a:hover{text-decoration:underline}h1,h2{margin:0;font-weight:500;letter-spacing:-.01em}h1{font-size:24px;line-height:32px}h2{font-size:16px;line-height:24px}.muted{color:var(--muted)}.faint{color:var(--faint)}.s{font-size:13px;line-height:18px}.ok{color:var(--ok)}.warn{color:var(--warn)}.strong{font-weight:500}.center{text-align:center}.mono{font-family:var(--mono);font-size:12px}.stack{display:flex;flex-direction:column;gap:2px;min-width:0}.stack.gap{gap:10px}.grow{flex:1}.row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.row.gap{gap:8px;flex-wrap:nowrap}.row-baseline{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.offscreen{position:fixed;left:-9999px;opacity:0}.top{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:max(12px,env(safe-area-inset-top)) 16px 12px;border-bottom:1px solid var(--line);position:sticky;top:0;background:color-mix(in srgb,var(--bg) 85%,transparent);backdrop-filter:saturate(180%) blur(12px);z-index:5}.brand{display:flex;align-items:center;gap:8px;font-weight:500;min-width:0}.brand .faint{font-weight:400}.logo{display:inline-flex;width:22px;height:22px;color:var(--text)}.logo svg{width:100%;height:100%}.wrap{width:100%;max-width:1048px;margin:0 auto;padding:20px 16px max(32px,env(safe-area-inset-bottom));display:flex;flex-direction:column;gap:20px}.hello{display:flex;align-items:center;gap:12px}.avatar{width:44px;height:44px;border-radius:50%;background:var(--soft-hover);display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;position:relative;flex:0 0 auto}.avatar.online:after{content:"";position:absolute;right:0;bottom:0;width:10px;height:10px;border-radius:50%;background:var(--ok);box-shadow:0 0 0 3px var(--bg)}.notice{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border-radius:12px;background:var(--warn-wash);font-size:14px}.notice.bad{background:var(--bad-wash)}.notice .ic{color:var(--warn)}.notice.bad .ic{color:var(--bad)}.alert{display:flex;gap:12px;align-items:center;padding:12px 16px;border:1px solid var(--line);border-radius:12px;background:var(--card);font-size:14px;line-height:20px}.alert-ic{width:30px;height:30px;border-radius:9px;display:inline-flex;align-items:center;justify-content:center;flex:none;background:var(--warn-wash);color:var(--warn)}.alert-ic.bad{background:var(--bad-wash);color:var(--bad)}.alert-ic .ic-svg{width:15px;height:15px}.layout{display:grid;grid-template-columns:minmax(0,1fr);gap:20px;grid-template-areas:"access" "devices"}.access{grid-area:access}.devices{grid-area:devices;display:flex;flex-direction:column;gap:12px;min-width:0}.desktop-only{display:none!important}@media(min-width:960px){.top{padding-left:max(16px,calc((100vw - 1048px)/2 + 16px));padding-right:max(16px,calc((100vw - 1048px)/2 + 16px))}.layout{grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);grid-template-areas:"devices access";align-items:start;gap:16px}.desktop-only{display:inline-flex!important}.wrap{padding-top:28px}}.card{backgrouLine truncated
|
@font-face{font-family:Geist;src:url(geist-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+2000-206F,U+20AC,U+2122,U+2190-21FF,U+2212,U+2215}@font-face{font-family:Geist;src:url(geist-cyrillic-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap;unicode-range:U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116}@font-face{font-family:Geist Mono;src:url(geist-mono-latin-wght-normal.woff2) format("woff2");font-weight:100 900;font-display:swap}:root{color-scheme:dark;--bg: #080808;--raised: #121212;--field: #161616;--knob: #232323;--seg: rgba(237, 237, 237, .05);--seg-shadow: none;--line: rgba(255, 255, 255, .06);--text: #ededed;--text-2: #8c8c8a;--text-3: #4f4f4e;--accent: #4eafff;--accent-ink: #ffffff;--accent-soft: rgba(78, 175, 255, .13);--ok: #57d64b;--ok-soft: rgba(87, 214, 75, .14);--warn: #ff8a3d;--bad: #ff5c5c;--bad-soft: rgba(255, 92, 92, .13);--sel-bg: rgba(131, 209, 255, .25);--sel-fg: #64c6ff;--scrim: rgba(8, 8, 8, .8);--line-glass: rgba(255, 255, 255, .07);--pop-shadow: 0 18px 48px -14px rgba(0, 0, 0, .75);--sheet-shadow: 0 24px 64px -16px rgba(0, 0, 0, .6);--bar: rgba(237, 237, 237, .13);--toast: #232323;--toast-fg: #ededed;--qr-bg: #0a0a0a;--gi-a: rgba(255, 255, 255, .58);--gi-b: rgba(255, 255, 255, .14);--gi-rim: rgba(255, 255, 255, .5);--gi-edge: rgba(0, 0, 0, 0);--gi-detail: #ffffff;--t-grey-a: #cfcfcd;--t-grey-b: #5a5a59;--t-blue-a: #a6d9ff;--t-blue-b: #1d84e6;--t-green-a: #a8f29c;--t-green-b: #3aa32c;--t-red-a: #ffadad;--t-red-b: #dc3a3a;--t-orange-a: #ffc08f;--t-orange-b: #ec6a12;--font: Geist, -apple-system, system-ui, "Segoe UI", sans-serif;--mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;--r-sheet: 36px;--r-card: 28px;--r-row: 20px;--r-field: 16px;--r-tile: 12px;--ease-out: cubic-bezier(.23, 1, .32, 1);--gutter-l: max(16px, env(safe-area-inset-left, 0px));--gutter-r: max(16px, env(safe-area-inset-right, 0px))}@media(prefers-color-scheme:light){:root{color-scheme:light;--bg: #f2f2f1;--raised: #ffffff;--field: #f3f3f2;--knob: #e8e8e7;--seg: #ffffff;--seg-shadow: 0 1px 2px rgba(0, 0, 0, .08), 0 0 0 .5px rgba(0, 0, 0, .05);--line: rgba(0, 0, 0, .07);--text: #0b0b0b;--text-2: #6d6d6b;--text-3: #a6a6a4;--accent: #2b9dff;--accent-soft: rgba(43, 157, 255, .12);--ok: #33a328;--ok-soft: rgba(51, 163, 40, .12);--warn: #ee6a12;--bad: #e5484d;--bad-soft: rgba(229, 72, 77, .1);--sel-bg: rgba(78, 175, 255, .22);--sel-fg: #0a76cf;--scrim: rgba(236, 236, 235, .62);--line-glass: rgba(0, 0, 0, .07);--pop-shadow: 0 18px 44px -14px rgba(0, 0, 0, .2);--sheet-shadow: 0 24px 64px -18px rgba(0, 0, 0, .22);--bar: rgba(11, 11, 11, .11);--toast: #0b0b0b;--toast-fg: #f2f2f1;--qr-bg: #ffffff;--gi-a: rgba(250, 250, 249, .72);--gi-b: rgba(206, 206, 204, .5);--gi-rim: rgba(255, 255, 255, .9);--gi-edge: rgba(0, 0, 0, .11);--gi-detail: rgba(28, 28, 28, .72);--t-grey-a: #a9a9a7;--t-grey-b: #3d3d3c;--t-blue-a: #7cc4ff;--t-blue-b: #0a6fd6;--t-green-a: #82e070;--t-green-b: #2e8a22;--t-red-a: #ff9090;--t-red-b: #c92a2a}}*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scrollbar-gutter:stable}body{margin:0;background:var(--bg);color:var(--text);font:400 15px/22px var(--font);letter-spacing:-.011em;-webkit-font-smoothing:antialiased;min-height:100vh;min-height:100dvh;cursor:default}body.locked{overflow:hidden}input,textarea,.linkrow .mono,.conf{cursor:text}::selection{background:var(--sel-bg);color:var(--sel-fg)}button{font:inherit;color:inherit;letter-spacing:inherit;background:none;border:0;padding:0;margin:0;cursor:pointer;-webkit-tap-highlight-color:transparent}button:disabled{cursor:default}a{color:inherit;text-decoration:none}:focus{outline:none}:focus-visible{outline:2px solid color-mix(in srgb,var(--accent) 65%,transparent);outline-offset:2px}[hidden]{display:none!important}.offscreen{position:fixed;left:-9999px;top:0;opacity:0}.mono{font-family:var(--mono);letter-spacing:0}.num{font-variant-numeric:tabular-nums}.ok-t{color:var(--ok)}.warn-t{color:var(--warn)}.bad-t{color:var(--bad)}.here-t{color:var(--accent)}.i{width:18px;height:18px;flex:none}.gi{width:24px;height:24px;flex:none;overflow:visible;--ta: var(--t-grey-a);--tb: var(--t-grey-b)}.gi.t-blue{--ta: var(--t-blue-a);--tb: var(--t-blue-b)}.gi.t-green{--ta: var(--t-green-a);--tb: var(--t-green-b)}.gi.t-red{--ta: var(--t-red-a);--tb: var(--t-red-b)}.gi.t-orange{--ta: var(--t-orange-a);--tb: var(--t-orange-b)}.gi .ta{stop-color:var(--ta)}.gi .tb{stop-color:var(--tb)}.gi .fa{stop-color:var(--gi-a)}.gi .fb{stop-color:var(--gi-b)}.gi .fc{stop-color:var(--ta);stop-opacity:.28}.gi .ge{stroke:var(--gi-edge)}.gi .gr{stroke:var(--gi-rim)}.gi .gd{stroke:var(--gi-detail)}.gi .gdf{color:var(--gi-detail)}.knob{width:32px;height:32px;border-radius:50%;background:var(--knob);color:var(--text);display:grid;place-items:center;flex:none;transition:transform .15s var(--ease-out),background-color .15s}.knob:hover{background:color-miLine truncated
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use strict";(()=>{var ut=Object.create;var Ke=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var vt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gt=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of ft(t))!pt.call(e,l)&&l!==r&&Ke(e,l,{get:()=>t[l],enumerable:!(s=dt(t,l))||s.enumerable});return e};var mt=(e,t,r)=>(r=e!=null?ut(ht(e)):{},gt(t||!e||!e.__esModule?Ke(r,"default",{value:e,enumerable:!0}):r,e));var Qe=vt((ze,Je)=>{"use strict";var je=(function(){var e=function(x,k){var b=236,f=17,c=x,y=r[k],i=null,a=0,w=null,h=[],m={},L=function(u,d){a=c*4+17,i=(function(o){for(var p=new Array(o),g=0;g<o;g+=1){p[g]=new Array(o);for(var M=0;M<o;M+=1)p[g][M]=null}return p})(a),D(0,0),D(a-7,0),D(0,a-7),G(),K(),J(u,d),c>=7&&z(u),w==null&&(w=ct(c,y,h)),Q(w,d)},D=function(u,d){for(var o=-1;o<=7;o+=1)if(!(u+o<=-1||a<=u+o))for(var p=-1;p<=7;p+=1)d+p<=-1||a<=d+p||(0<=o&&o<=6&&(p==0||p==6)||0<=p&&p<=6&&(o==0||o==6)||2<=o&&o<=4&&2<=p&&p<=4?i[u+o][d+p]=!0:i[u+o][d+p]=!1)},S=function(){for(var u=0,d=0,o=0;o<8;o+=1){L(!0,o);var p=l.getLostPoint(m);(o==0||u>p)&&(u=p,d=o)}return d},K=function(){for(var u=8;u<a-8;u+=1)i[u][6]==null&&(i[u][6]=u%2==0);for(var d=8;d<a-8;d+=1)i[6][d]==null&&(i[6][d]=d%2==0)},G=function(){for(var u=l.getPatternPosition(c),d=0;d<u.length;d+=1)for(var o=0;o<u.length;o+=1){var p=u[d],g=u[o];if(i[p][g]==null)for(var M=-2;M<=2;M+=1)for(var C=-2;C<=2;C+=1)M==-2||M==2||C==-2||C==2||M==0&&C==0?i[p+M][g+C]=!0:i[p+M][g+C]=!1}},z=function(u){for(var d=l.getBCHTypeNumber(c),o=0;o<18;o+=1){var p=!u&&(d>>o&1)==1;i[Math.floor(o/3)][o%3+a-8-3]=p}for(var o=0;o<18;o+=1){var p=!u&&(d>>o&1)==1;i[o%3+a-8-3][Math.floor(o/3)]=p}},J=function(u,d){for(var o=y<<3|d,p=l.getBCHTypeInfo(o),g=0;g<15;g+=1){var M=!u&&(p>>g&1)==1;g<6?i[g][8]=M:g<8?i[g+1][8]=M:i[a-15+g][8]=M}for(var g=0;g<15;g+=1){var M=!u&&(p>>g&1)==1;g<8?i[8][a-g-1]=M:g<9?i[8][15-g-1+1]=M:i[8][15-g-1]=M}i[a-8][8]=!u},Q=function(u,d){for(var o=-1,p=a-1,g=7,M=0,C=l.getMaskFunction(d),_=a-1;_>0;_-=2)for(_==6&&(_-=1);;){for(var R=0;R<2;R+=1)if(i[p][_-R]==null){var F=!1;M<u.length&&(F=(u[M]>>>g&1)==1);var T=C(p,_-R);T&&(F=!F),i[p][_-R]=F,g-=1,g==-1&&(M+=1,g=7)}if(p+=o,p<0||a<=p){p-=o,o=-o;break}}},re=function(u,d){for(var o=0,p=0,g=0,M=new Array(d.length),C=new Array(d.length),_=0;_<d.length;_+=1){var R=d[_].dataCount,F=d[_].totalCount-R;p=Math.max(p,R),g=Math.max(g,F),M[_]=new Array(R);for(var T=0;T<M[_].length;T+=1)M[_][T]=255&u.getBuffer()[T+o];o+=R;var Y=l.getErrorCorrectPolynomial(F),j=A(M[_],Y.getLength()-1),He=j.mod(Y);C[_]=new Array(Y.getLength()-1);for(var T=0;T<C[_].length;T+=1){var Ie=T+He.getLength()-C[_].length;C[_][T]=Ie>=0?He.getAt(Ie):0}}for(var Oe=0,T=0;T<d.length;T+=1)Oe+=d[T].totalCount;for(var xe=new Array(Oe),he=0,T=0;T<p;T+=1)for(var _=0;_<d.length;_+=1)T<M[_].length&&(xe[he]=M[_][T],he+=1);for(var T=0;T<g;T+=1)for(var _=0;_<d.length;_+=1)T<C[_].length&&(xe[he]=C[_][T],he+=1);return xe},ct=function(u,d,o){for(var p=E.getRSBlocks(u,d),g=N(),M=0;M<o.length;M+=1){var C=o[M];g.put(C.getMode(),4),g.put(C.getLength(),l.getLengthInBits(C.getMode(),u)),C.write(g)}for(var _=0,M=0;M<p.length;M+=1)_+=p[M].dataCount;if(g.getLengthInBits()>_*8)throw"code length overflow. ("+g.getLengthInBits()+">"+_*8+")";for(g.getLengthInBits()+4<=_*8&&g.put(0,4);g.getLengthInBits()%8!=0;)g.putBit(!1);for(;!(g.getLengthInBits()>=_*8||(g.put(b,8),g.getLengthInBits()>=_*8));)g.put(f,8);return re(g,p)};m.addData=function(u,d){d=d||"Byte";var o=null;switch(d){case"Numeric":o=$(u);break;case"Alphanumeric":o=P(u);break;case"Byte":o=q(u);break;case"Kanji":o=O(u);break;default:throw"mode:"+d}h.push(o),w=null},m.isDark=function(u,d){if(u<0||a<=u||d<0||a<=d)throw u+","+d;return i[u][d]},m.getModuleCount=function(){return a},m.make=function(){if(c<1){for(var u=1;u<40;u++){for(var d=E.getRSBlocks(u,y),o=N(),p=0;p<h.length;p++){var g=h[p];o.put(g.getMode(),4),o.put(g.getLength(),l.getLengthInBits(g.getMode(),u)),g.write(o)}for(var M=0,p=0;p<d.length;p++)M+=d[p].dataCount;if(o.getLengthInBits()<=M*8)break}c=u}L(!1,S())},m.createTableTag=function(u,d){u=u||2,d=typeof d=="undefined"?u*4:d;var o="";o+='<table style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: "+d+"px;",o+='">',o+="<tbody>";for(var p=0;p<m.getModuleCount();p+=1){o+="<tr>";for(var g=0;g<m.getModuleCount();g+=1)o+='<td style="',o+=" border-width: 0px; border-style: none;",o+=" border-collapse: collapse;",o+=" padding: 0px; margin: 0px;",o+=" width: "+u+"px;",o+=" height: "+u+"px;",o+=" background-color: ",o+=m.isDark(p,g)?"#000000":"#ffffff",o+=";",o+='"/>';o+="</tr>"}return o+="</tbody>",o+="</table>",o},m.createSvgTag=function(u,d,o,p){var g={};typeof arguments[0]=="object"&&(g=arguments[0],u=g.cellSize,d=g.margin,o=g.alt,p=g.title),u=u||2,d=typeof d=="undefined"?u*4:d,o=typeof o=="string"?{text:o}:o||{},o.text=o.text||nLine truncated
|
"use strict";(()=>{var Oo=Object.create;var On=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var Ko=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var qo=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of No(e))!Fo.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(r=Ro(e,o))||r.enumerable});return t};var Go=(t,e,n)=>(n=t!=null?Oo(Io(t)):{},qo(e||!t||!t.__esModule?On(n,"default",{value:t,enumerable:!0}):n,t));var gr=Ko((hr,mr)=>{"use strict";var fr=(function(){var t=function(d,m){var s=236,h=17,f=d,E=n[m],p=null,l=0,L=null,x=[],C={},R=function(w,k){l=f*4+17,p=(function(y){for(var T=new Array(y),S=0;S<y;S+=1){T[S]=new Array(y);for(var D=0;D<y;D+=1)T[S][D]=null}return T})(l),I(0,0),I(l-7,0),I(0,l-7),et(),Q(),it(w,k),f>=7&&ot(w),L==null&&(L=$t(f,E,x)),G(L,k)},I=function(w,k){for(var y=-1;y<=7;y+=1)if(!(w+y<=-1||l<=w+y))for(var T=-1;T<=7;T+=1)k+T<=-1||l<=k+T||(0<=y&&y<=6&&(T==0||T==6)||0<=T&&T<=6&&(y==0||y==6)||2<=y&&y<=4&&2<=T&&T<=4?p[w+y][k+T]=!0:p[w+y][k+T]=!1)},z=function(){for(var w=0,k=0,y=0;y<8;y+=1){R(!0,y);var T=o.getLostPoint(C);(y==0||w>T)&&(w=T,k=y)}return k},Q=function(){for(var w=8;w<l-8;w+=1)p[w][6]==null&&(p[w][6]=w%2==0);for(var k=8;k<l-8;k+=1)p[6][k]==null&&(p[6][k]=k%2==0)},et=function(){for(var w=o.getPatternPosition(f),k=0;k<w.length;k+=1)for(var y=0;y<w.length;y+=1){var T=w[k],S=w[y];if(p[T][S]==null)for(var D=-2;D<=2;D+=1)for(var K=-2;K<=2;K+=1)D==-2||D==2||K==-2||K==2||D==0&&K==0?p[T+D][S+K]=!0:p[T+D][S+K]=!1}},ot=function(w){for(var k=o.getBCHTypeNumber(f),y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[Math.floor(y/3)][y%3+l-8-3]=T}for(var y=0;y<18;y+=1){var T=!w&&(k>>y&1)==1;p[y%3+l-8-3][Math.floor(y/3)]=T}},it=function(w,k){for(var y=E<<3|k,T=o.getBCHTypeInfo(y),S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<6?p[S][8]=D:S<8?p[S+1][8]=D:p[l-15+S][8]=D}for(var S=0;S<15;S+=1){var D=!w&&(T>>S&1)==1;S<8?p[8][l-S-1]=D:S<9?p[8][15-S-1+1]=D:p[8][15-S-1]=D}p[l-8][8]=!w},G=function(w,k){for(var y=-1,T=l-1,S=7,D=0,K=o.getMaskFunction(k),N=l-1;N>0;N-=2)for(N==6&&(N-=1);;){for(var X=0;X<2;X+=1)if(p[T][N-X]==null){var nt=!1;D<w.length&&(nt=(w[D]>>>S&1)==1);var q=K(T,N-X);q&&(nt=!nt),p[T][N-X]=nt,S-=1,S==-1&&(D+=1,S=7)}if(T+=y,T<0||l<=T){T-=y,y=-y;break}}},V=function(w,k){for(var y=0,T=0,S=0,D=new Array(k.length),K=new Array(k.length),N=0;N<k.length;N+=1){var X=k[N].dataCount,nt=k[N].totalCount-X;T=Math.max(T,X),S=Math.max(S,nt),D[N]=new Array(X);for(var q=0;q<D[N].length;q+=1)D[N][q]=255&w.getBuffer()[q+y];y+=X;var gt=o.getErrorCorrectPolynomial(nt),vt=c(D[N],gt.getLength()-1),Dn=vt.mod(gt);K[N]=new Array(gt.getLength()-1);for(var q=0;q<K[N].length;q+=1){var Bn=q+Dn.getLength()-K[N].length;K[N][q]=Bn>=0?Dn.getAt(Bn):0}}for(var Hn=0,q=0;q<k.length;q+=1)Hn+=k[q].totalCount;for(var on=new Array(Hn),Ae=0,q=0;q<T;q+=1)for(var N=0;N<k.length;N+=1)q<D[N].length&&(on[Ae]=D[N][q],Ae+=1);for(var q=0;q<S;q+=1)for(var N=0;N<k.length;N+=1)q<K[N].length&&(on[Ae]=K[N][q],Ae+=1);return on},$t=function(w,k,y){for(var T=g.getRSBlocks(w,k),S=v(),D=0;D<y.length;D+=1){var K=y[D];S.put(K.getMode(),4),S.put(K.getLength(),o.getLengthInBits(K.getMode(),w)),K.write(S)}for(var N=0,D=0;D<T.length;D+=1)N+=T[D].dataCount;if(S.getLengthInBits()>N*8)throw"code length overflow. ("+S.getLengthInBits()+">"+N*8+")";for(S.getLengthInBits()+4<=N*8&&S.put(0,4);S.getLengthInBits()%8!=0;)S.putBit(!1);for(;!(S.getLengthInBits()>=N*8||(S.put(s,8),S.getLengthInBits()>=N*8));)S.put(h,8);return V(S,T)};C.addData=function(w,k){k=k||"Byte";var y=null;switch(k){case"Numeric":y=u(w);break;case"Alphanumeric":y=M(w);break;case"Byte":y=b(w);break;case"Kanji":y=A(w);break;default:throw"mode:"+k}x.push(y),L=null},C.isDark=function(w,k){if(w<0||l<=w||k<0||l<=k)throw w+","+k;return p[w][k]},C.getModuleCount=function(){return l},C.make=function(){if(f<1){for(var w=1;w<40;w++){for(var k=g.getRSBlocks(w,E),y=v(),T=0;T<x.length;T++){var S=x[T];y.put(S.getMode(),4),y.put(S.getLength(),o.getLengthInBits(S.getMode(),w)),S.write(y)}for(var D=0,T=0;T<k.length;T++)D+=k[T].dataCount;if(y.getLengthInBits()<=D*8)break}f=w}R(!1,z())},C.createTableTag=function(w,k){w=w||2,k=typeof k=="undefined"?w*4:k;var y="";y+='<table style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: "+k+"px;",y+='">',y+="<tbody>";for(var T=0;T<C.getModuleCount();T+=1){y+="<tr>";for(var S=0;S<C.getModuleCount();S+=1)y+='<td style="',y+=" border-width: 0px; border-style: none;",y+=" border-collapse: collapse;",y+=" padding: 0px; margin: 0px;",y+=" width: "+w+"px;",y+=" height: "+w+"px;",y+=" background-color: ",y+=C.isDark(T,S)?"#000000":"#ffffff",y+=";",y+='"/>';y+="</tr>"}return y+="</tbody>",y+="</table>",y},C.createSvgTag=function(w,k,y,T){var S={};typeof arguments[0]=="object"&&(S=arguments[0],w=S.cellSize,k=S.margin,y=S.alt,T=S.title),w=w||2,k=typeof k=="undefined"?w*4:k,y=typeof y=="string"?{text:y}:y||{Line truncated
|
||||||
`}return o%2&&u>0?j.substring(0,j.length-o-1)+Array(o+1).join("▀"):j.substring(0,j.length-1)};return m.createASCII=function(u,d){if(u=u||1,u<2)return lt(d);u-=1,d=typeof d=="undefined"?u*2:d;var o=m.getModuleCount()*u+d*2,p=d,g=o-d,M,C,_,R,F=Array(u+1).join("██"),T=Array(u+1).join(" "),Y="",j="";for(M=0;M<o;M+=1){for(_=Math.floor((M-p)/u),j="",C=0;C<o;C+=1)R=1,p<=C&&C<g&&p<=M&&M<g&&m.isDark(_,Math.floor((C-p)/u))&&(R=0),j+=R?F:T;for(_=0;_<u;_+=1)Y+=j+`
|
`}return y%2&&w>0?vt.substring(0,vt.length-y-1)+Array(y+1).join("▀"):vt.substring(0,vt.length-1)};return C.createASCII=function(w,k){if(w=w||1,w<2)return rn(k);w-=1,k=typeof k=="undefined"?w*2:k;var y=C.getModuleCount()*w+k*2,T=k,S=y-k,D,K,N,X,nt=Array(w+1).join("██"),q=Array(w+1).join(" "),gt="",vt="";for(D=0;D<y;D+=1){for(N=Math.floor((D-T)/w),vt="",K=0;K<y;K+=1)X=1,T<=K&&K<S&&T<=D&&D<S&&C.isDark(N,Math.floor((K-T)/w))&&(X=0),vt+=X?nt:q;for(N=0;N<w;N+=1)gt+=vt+`
|
||||||
`}return Y.substring(0,Y.length-1)},m.renderTo2dContext=function(u,d){d=d||2;for(var o=m.getModuleCount(),p=0;p<o;p++)for(var g=0;g<o;g++)u.fillStyle=m.isDark(p,g)?"black":"white",u.fillRect(p*d,g*d,d,d)},m};e.stringToBytesFuncs={default:function(x){for(var k=[],b=0;b<x.length;b+=1){var f=x.charCodeAt(b);k.push(f&255)}return k}},e.stringToBytes=e.stringToBytesFuncs.default,e.createStringToBytes=function(x,k){var b=(function(){for(var c=le(x),y=function(){var K=c.read();if(K==-1)throw"eof";return K},i=0,a={};;){var w=c.read();if(w==-1)break;var h=y(),m=y(),L=y(),D=String.fromCharCode(w<<8|h),S=m<<8|L;a[D]=S,i+=1}if(i!=k)throw i+" != "+k;return a})(),f=63;return function(c){for(var y=[],i=0;i<c.length;i+=1){var a=c.charCodeAt(i);if(a<128)y.push(a);else{var w=b[c.charAt(i)];typeof w=="number"?(w&255)==w?y.push(w):(y.push(w>>>8),y.push(w&255)):y.push(f)}}return y}};var t={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},r={L:1,M:0,Q:3,H:2},s={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},l=(function(){var x=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],k=1335,b=7973,f=21522,c={},y=function(i){for(var a=0;i!=0;)a+=1,i>>>=1;return a};return c.getBCHTypeInfo=function(i){for(var a=i<<10;y(a)-y(k)>=0;)a^=k<<y(a)-y(k);return(i<<10|a)^f},c.getBCHTypeNumber=function(i){for(var a=i<<12;y(a)-y(b)>=0;)a^=b<<y(a)-y(b);return i<<12|a},c.getPatternPosition=function(i){return x[i-1]},c.getMaskFunction=function(i){switch(i){case s.PATTERN000:return function(a,w){return(a+w)%2==0};case s.PATTERN001:return function(a,w){return a%2==0};case s.PATTERN010:return function(a,w){return w%3==0};case s.PATTERN011:return function(a,w){return(a+w)%3==0};case s.PATTERN100:return function(a,w){return(Math.floor(a/2)+Math.floor(w/3))%2==0};case s.PATTERN101:return function(a,w){return a*w%2+a*w%3==0};case s.PATTERN110:return function(a,w){return(a*w%2+a*w%3)%2==0};case s.PATTERN111:return function(a,w){return(a*w%3+(a+w)%2)%2==0};default:throw"bad maskPattern:"+i}},c.getErrorCorrectPolynomial=function(i){for(var a=A([1],0),w=0;w<i;w+=1)a=a.multiply(A([1,v.gexp(w)],0));return a},c.getLengthInBits=function(i,a){if(1<=a&&a<10)switch(i){case t.MODE_NUMBER:return 10;case t.MODE_ALPHA_NUM:return 9;case t.MODE_8BIT_BYTE:return 8;case t.MODE_KANJI:return 8;default:throw"mode:"+i}else if(a<27)switch(i){case t.MODE_NUMBER:return 12;case t.MODE_ALPHA_NUM:return 11;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 10;default:throw"mode:"+i}else if(a<41)switch(i){case t.MODE_NUMBER:return 14;case t.MODE_ALPHA_NUM:return 13;case t.MODE_8BIT_BYTE:return 16;case t.MODE_KANJI:return 12;default:throw"mode:"+i}else throw"type:"+a},c.getLostPoint=function(i){for(var a=i.getModuleCount(),w=0,h=0;h<a;h+=1)for(var m=0;m<a;m+=1){for(var L=0,D=i.isDark(h,m),S=-1;S<=1;S+=1)if(!(h+S<0||a<=h+S))for(var K=-1;K<=1;K+=1)m+K<0||a<=m+K||S==0&&K==0||D==i.isDark(h+S,m+K)&&(L+=1);L>5&&(w+=3+L-5)}for(var h=0;h<a-1;h+=1)for(var m=0;m<a-1;m+=1){var G=0;i.isDark(h,m)&&(G+=1),i.isDark(h+1,m)&&(G+=1),i.isDark(h,m+1)&&(G+=1),i.isDark(h+1,m+1)&&(G+=1),(G==0||G==4)&&(w+=3)}for(var h=0;h<a;h+=1)for(var m=0;m<a-6;m+=1)i.isDark(h,m)&&!i.isDark(h,m+1)&&i.isDark(h,m+2)&&i.isDark(h,m+3)&&i.isDark(h,m+4)&&!i.isDark(h,m+5)&&i.isDark(h,m+6)&&(w+=40);for(var m=0;m<a;m+=1)for(var h=0;h<a-6;h+=1)i.isDark(h,m)&&!i.isDark(h+1,m)&&i.isDark(h+2,m)&&i.isDark(h+3,m)&&i.isDark(h+4,m)&&!i.isDark(h+5,m)&&i.isDark(h+6,m)&&(w+=40);for(var z=0,m=0;m<a;m+=1)for(var h=0;h<a;h+=1)i.isDark(h,m)&&(z+=1);var J=Math.abs(100*z/a/a-50)/5;return w+=J*10,w},c})(),v=(function(){for(var x=new Array(256),k=new Array(256),b=0;b<8;b+=1)x[b]=1<<b;for(var b=8;b<256;b+=1)x[b]=x[b-4]^x[b-5]^x[b-6]^x[b-8];for(var b=0;b<255;b+=1)k[x[b]]=b;var f={};return f.glog=function(c){if(c<1)throw"glog("+c+")";return k[c]},f.gexp=function(c){for(;c<0;)c+=255;for(;c>=256;)c-=255;return x[c]},f})();function A(x,k){if(typeof x.length=="undefined")throw x.length+"/"+k;var b=(function(){for(var c=0;c<x.length&&x[c]==0;)c+=1;for(var y=new Array(x.length-c+k),i=0;i<x.length-c;i+=1)y[i]=x[i+c];return y})(),f={};return f.getAt=function(c){return b[c]},f.getLength=function(){return b.length},f.multiply=function(c){for(var y=new Array(f.getLength()+c.getLength()-1),i=0;i<f.getLength();i+=1)for(var a=0;a<c.getLength();a+=1)y[i+a]^=v.gexp(v.glog(f.getAt(i))+v.glog(c.getAt(a)));return A(y,0)},f.mod=function(c){if(f.getLe
Line truncated
|
`}return gt.substring(0,gt.length-1)},C.renderTo2dContext=function(w,k){k=k||2;for(var y=C.getModuleCount(),T=0;T<y;T++)for(var S=0;S<y;S++)w.fillStyle=C.isDark(T,S)?"black":"white",w.fillRect(T*k,S*k,k,k)},C};t.stringToBytesFuncs={default:function(d){for(var m=[],s=0;s<d.length;s+=1){var h=d.charCodeAt(s);m.push(h&255)}return m}},t.stringToBytes=t.stringToBytesFuncs.default,t.createStringToBytes=function(d,m){var s=(function(){for(var f=P(d),E=function(){var Q=f.read();if(Q==-1)throw"eof";return Q},p=0,l={};;){var L=f.read();if(L==-1)break;var x=E(),C=E(),R=E(),I=String.fromCharCode(L<<8|x),z=C<<8|R;l[I]=z,p+=1}if(p!=m)throw p+" != "+m;return l})(),h=63;return function(f){for(var E=[],p=0;p<f.length;p+=1){var l=f.charCodeAt(p);if(l<128)E.push(l);else{var L=s[f.charAt(p)];typeof L=="number"?(L&255)==L?E.push(L):(E.push(L>>>8),E.push(L&255)):E.push(h)}}return E}};var e={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},n={L:1,M:0,Q:3,H:2},r={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},o=(function(){var d=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],m=1335,s=7973,h=21522,f={},E=function(p){for(var l=0;p!=0;)l+=1,p>>>=1;return l};return f.getBCHTypeInfo=function(p){for(var l=p<<10;E(l)-E(m)>=0;)l^=m<<E(l)-E(m);return(p<<10|l)^h},f.getBCHTypeNumber=function(p){for(var l=p<<12;E(l)-E(s)>=0;)l^=s<<E(l)-E(s);return p<<12|l},f.getPatternPosition=function(p){return d[p-1]},f.getMaskFunction=function(p){switch(p){case r.PATTERN000:return function(l,L){return(l+L)%2==0};case r.PATTERN001:return function(l,L){return l%2==0};case r.PATTERN010:return function(l,L){return L%3==0};case r.PATTERN011:return function(l,L){return(l+L)%3==0};case r.PATTERN100:return function(l,L){return(Math.floor(l/2)+Math.floor(L/3))%2==0};case r.PATTERN101:return function(l,L){return l*L%2+l*L%3==0};case r.PATTERN110:return function(l,L){return(l*L%2+l*L%3)%2==0};case r.PATTERN111:return function(l,L){return(l*L%3+(l+L)%2)%2==0};default:throw"bad maskPattern:"+p}},f.getErrorCorrectPolynomial=function(p){for(var l=c([1],0),L=0;L<p;L+=1)l=l.multiply(c([1,a.gexp(L)],0));return l},f.getLengthInBits=function(p,l){if(1<=l&&l<10)switch(p){case e.MODE_NUMBER:return 10;case e.MODE_ALPHA_NUM:return 9;case e.MODE_8BIT_BYTE:return 8;case e.MODE_KANJI:return 8;default:throw"mode:"+p}else if(l<27)switch(p){case e.MODE_NUMBER:return 12;case e.MODE_ALPHA_NUM:return 11;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 10;default:throw"mode:"+p}else if(l<41)switch(p){case e.MODE_NUMBER:return 14;case e.MODE_ALPHA_NUM:return 13;case e.MODE_8BIT_BYTE:return 16;case e.MODE_KANJI:return 12;default:throw"mode:"+p}else throw"type:"+l},f.getLostPoint=function(p){for(var l=p.getModuleCount(),L=0,x=0;x<l;x+=1)for(var C=0;C<l;C+=1){for(var R=0,I=p.isDark(x,C),z=-1;z<=1;z+=1)if(!(x+z<0||l<=x+z))for(var Q=-1;Q<=1;Q+=1)C+Q<0||l<=C+Q||z==0&&Q==0||I==p.isDark(x+z,C+Q)&&(R+=1);R>5&&(L+=3+R-5)}for(var x=0;x<l-1;x+=1)for(var C=0;C<l-1;C+=1){var et=0;p.isDark(x,C)&&(et+=1),p.isDark(x+1,C)&&(et+=1),p.isDark(x,C+1)&&(et+=1),p.isDark(x+1,C+1)&&(et+=1),(et==0||et==4)&&(L+=3)}for(var x=0;x<l;x+=1)for(var C=0;C<l-6;C+=1)p.isDark(x,C)&&!p.isDark(x,C+1)&&p.isDark(x,C+2)&&p.isDark(x,C+3)&&p.isDark(x,C+4)&&!p.isDark(x,C+5)&&p.isDark(x,C+6)&&(L+=40);for(var C=0;C<l;C+=1)for(var x=0;x<l-6;x+=1)p.isDark(x,C)&&!p.isDark(x+1,C)&&p.isDark(x+2,C)&&p.isDark(x+3,C)&&p.isDark(x+4,C)&&!p.isDark(x+5,C)&&p.isDark(x+6,C)&&(L+=40);for(var ot=0,C=0;C<l;C+=1)for(var x=0;x<l;x+=1)p.isDark(x,C)&&(ot+=1);var it=Math.abs(100*ot/l/l-50)/5;return L+=it*10,L},f})(),a=(function(){for(var d=new Array(256),m=new Array(256),s=0;s<8;s+=1)d[s]=1<<s;for(var s=8;s<256;s+=1)d[s]=d[s-4]^d[s-5]^d[s-6]^d[s-8];for(var s=0;s<255;s+=1)m[d[s]]=s;var h={};return h.glog=function(f){if(f<1)throw"glog("+f+")";return m[f]},h.gexp=function(f){for(;f<0;)f+=255;for(;f>=256;)f-=255;return d[f]},h})();function c(d,m){if(typeof d.length=="undefined")throw d.length+"/"+m;var s=(function(){for(var f=0;f<d.length&&d[f]==0;)f+=1;for(var E=new Array(d.length-f+m),p=0;p<d.length-f;p+=1)E[p]=d[p+f];return E})(),h={};return h.getAt=function(f){return s[f]},h.getLength=function(){return s.length},h.multiply=function(f){for(var E=new Array(h.getLength()+f.getLength()-1),p=0;p<h.getLength();p+=1)for(var l=0;l<f.getLength();l+=1)E[p+l]^=a.gexp(a.glog(h.getAt(p))+a.glog(f.getAt(l)));return c(E,0)},h.mod=function(
Line truncated
|
||||||
`),hostName:v,mtu:r.mtu,persistent_keep_alive:r.persistent_keep_alive,port:Number(r.port),psk_key:r.psk_key,server_pub_key:r.server_pub_key},E={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(A),port:String(r.port),protocol_version:s.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:t,hostName:v};return r.dns[0]&&(E.dns1=r.dns[0]),r.dns[1]&&(E.dns2=r.dns[1]),E}function _t(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ct(e){let t=globalThis;if(typeof t.CompressionStream=="undefined")return null;try{let r=new t.Blob([e]).stream().pipeThrough(new t.CompressionStream("deflate")),s=new Uint8Array(await new t.Response(r).arrayBuffer()),l=new Uint8Array(4+s.length);return new DataView(l.buffer).setUint32(0,e.length,!1),l.set(s,4),l}catch{return null}}async function Te(e,t,r=!0){let s=new TextEncoder().encode(JSON.stringify(At(e,t))),l=r?await Ct(s):null;return`vpn://${_t(l!=null?l:s)}`}var $e=()=>{var e;return(e=B==null?void 0:B.today)!=null?e:pe(new Date)};function n(e,t={},...r){let s=document.createElement(e);for(let[v,A]of Object.entries(t))A==null||A===!1||(v.startsWith("on")&&typeof A=="function"?s.addEventListener(v.slice(2),A):v==="class"?s.className=String(A):A===!0?s.setAttribute(v,""):s.setAttribute(v,String(A)));let l=v=>{v==null||v===!1||(Array.isArray(v)?v.forEach(l):s.appendChild(typeof v=="string"?document.createTextNode(v):v))};return r.forEach(l),s}function U(e){let t=n("span",{class:"ic"});return t.innerHTML=Ye(e,"ic-svg"),t}var Tt='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 15a9 9 0 0 1 18 0z" fill="currentColor"/><rect x="2" y="17" width="20" height="2" rx="1" fill="currentColor" opacity=".45"/></svg>',Se=document.getElementById("app"),tt,me=(tt=Se.dataset.base)!=null?tt:"",Lt=Se.dataset.title||"Dawnline",De=()=>window.matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent),B=null,Dt=/^\/[a-z]{6}-[a-z]{6}-[a-z]{6}$/.test(me)?me.slice(1):"",Ee=class extends Error{constructor(r,s,l){super(s);this.status=r;this.httpsUrl=l}};async function ne(e,t){var l;let r=await fetch(`${me}/api/${e}`,{method:t===void 0?"GET":"POST",credentials:"omit",headers:t===void 0?{}:{"Content-Type":"application/json"},body:t===void 0?void 0:JSON.stringify(t),cache:"no-store"}),s=null;try{s=await r.json()}catch{}if(!r.ok)throw new Ee(r.status,(l=s==null?void 0:s.error)!=null?l:`Request failed (${r.status})`,(s==null?void 0:s.https_url)||void 0);return s}function te(e,t=!1){let r=n("div",{class:`toast${t?" bad":""}`,role:"status"},e);document.body.appendChild(r),requestAnimationFrame(()=>r.classList.add("show")),setTimeout(()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),300)},2600)}async function oe(e,t="Copied"){try{await navigator.clipboard.writeText(e)}catch{let r=n("textarea",{class:"offscreen"},e);document.body.appendChild(r),r.select();let s=document.execCommand("copy");if(r.remove(),!s)return te("Copying is blocked here. Select the text and copy it by hand.",!0)}te(t)}function nt(e,t){let r=URL.createObjectURL(new Blob([t],{type:"application/octet-stream"})),s=n("a",{href:r,download:e,class:"offscreen"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(r),s.remove()},1e3)}var W=null;function rt(e,t){let r=s=>{W!=null||(W=document.body.appendChild(n("div",{class:"tip"}))),W.replaceChildren(...t().map((l,v)=>n("div",{class:v?"muted":"tip-title"},l))),W.style.display="",W.style.left=`${s.clientX}px`,W.style.top=`${s.clientY-10}px`};e.addEventListener("mouseenter",r),e.addEventListener("mousemove",r),e.addEventListener("mouseleave",()=>W&&(W.style.display="none"))}function Et(e){let t=Math.max(1,...e),r=n("div",{class:"spark"});return e.forEach((s,l)=>{let v=n("i",{class:s?"":"zero"});v.style.height=`${Math.max(8,s/t*100)}%`;let A=e.length-1-l;rt(v,()=>[A===0?"Today":A===1?"Yesterday":ve(Ue($e(),-A)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),se(s)]),r.appendChild(v)}),r}async function Pe(e,t){if(!e.disabled){e.disabled=!0;try{await t()}finally{e.disabled=!1}}}var ie=null,ue=null;function ee(e=!1){if(!ie)return;let t=ie;if(ie=null,document.body.classList.remove("locked"),ue==null||ue(),ue=null,e){t.remove();return}t.classList.remove("open"),setTimeout(()=>t.remove(),250)}function ce(e,t,...r){let s=!!ie;ee(!0);let l=n("div",{class:"sheet-panel",role:"dialog","aria-modal":"true","aria-label":e},n("div",{class:"grab"}),n("div",{class:"sheet-head"},n("div",{class:"stack"},n("h2",{},e),t?n("span",{class:"muted s"},t):null),n("button",{class:"icon-btn","aria-label":"Close",onclick:()=>ee()},U("x"))),n("div",{class:"sheet-body"},...r)),v=n("div",{class:"sheet",onclick:A=>{A.target===v&&ee()}},l);return document.body.appendChild(v),document.body.classList.add("locked"),s?v.classList.add("open
Line truncated
|
`),hostName:a,mtu:n.mtu,persistent_keep_alive:n.persistent_keep_alive,port:Number(n.port),psk_key:n.psk_key,server_pub_key:n.server_pub_key},g={containers:[{container:"amnezia-awg",awg:{isThirdPartyConfig:!0,last_config:JSON.stringify(c),port:String(n.port),protocol_version:r.header_protection_key?"3.1":"2",transport_proto:"udp"}}],defaultContainer:"amnezia-awg",description:e,hostName:a};return n.dns[0]&&(g.dns1=n.dns[0]),n.dns[1]&&(g.dns2=n.dns[1]),g}function bi(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wi(t){let e=globalThis;if(typeof e.CompressionStream=="undefined")return null;try{let n=new e.Blob([t]).stream().pipeThrough(new e.CompressionStream("deflate")),r=new Uint8Array(await new e.Response(n).arrayBuffer()),o=new Uint8Array(4+r.length);return new DataView(o.buffer).setUint32(0,t.length,!1),o.set(r,4),o}catch{return null}}async function Ln(t,e,n=!0){let r=new TextEncoder().encode(JSON.stringify(xi(t,e))),o=n?await wi(r):null;return`vpn://${bi(o!=null?o:r)}`}var Zr=t=>t.replace(/^vpn:\/\//,"");var to=["height","marginTop","marginBottom","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"];function qt(t,e={}){let n=i("div",{class:`acc${e.inset?" inset":""}`}),r=t.map((u,M)=>{var $;let b=u.body.filter(d=>!!d),A=!b.length,O=[u.icon,i("span",{class:"acc-title"},i("span",{class:"t"},u.title),($=u.tag)!=null?$:null),u.val?i("span",{class:`acc-val${u.valHide?" hide-open":""}`},u.val):null],B=M===e.open&&!A,P=A?i("div",{class:"acc-head"},...O):i("button",{type:"button",class:"acc-head","aria-expanded":String(B),onclick:()=>v(H)},...O,F("chevron","i acc-chev")),H=i("div",{class:`acc-row${A?" still":""}${B?" open":""}`},P,i("div",{class:"acc-body"},...b));return n.appendChild(H),H}),o=u=>u.querySelector(".acc-body"),a=()=>r.forEach((u,M)=>{let b=u.classList.contains("open");u.classList.toggle("rt",M===0||b||r[M-1].classList.contains("open")),u.classList.toggle("rb",M===r.length-1||b||r[M+1].classList.contains("open"))}),c=u=>{let M=getComputedStyle(u),b={};for(let A of to)b[A]=A==="height"?`${u.getBoundingClientRect().height}px`:M[A];return b},g=()=>r.forEach(u=>{var M;return(M=u.querySelector("button.acc-head"))==null?void 0:M.setAttribute("aria-expanded",String(u.classList.contains("open")))});function v(u){var B;let M=r.map(c);r.forEach(P=>P.getAnimations().forEach(H=>H.cancel())),r.forEach(P=>o(P).getAnimations().forEach(H=>H.cancel()));let b=!u.classList.contains("open"),A=r.filter(P=>P.classList.contains("open")&&(P===u||b));r.forEach(P=>{P.classList.remove("closing"),P!==u&&P.classList.remove("open")}),u.classList.toggle("open",b),a();let O=ce();r.forEach((P,H)=>{let $=c(P);to.some(d=>M[H][d]!==$[d])&&(A.includes(P)&&P.classList.add("closing"),_(P,[M[H],$],{duration:Et.duration,easing:Et.easing}).onfinish=()=>P.classList.remove("closing"))}),A.forEach(P=>_(o(P),[{opacity:1},{opacity:0,filter:"blur(2px)"}],{duration:160,easing:J,fill:"forwards"})),b&&_(o(u),[{opacity:0,filter:"blur(2px)"},{opacity:1,filter:"blur(0px)"}],{duration:300,easing:"cubic-bezier(0,0,.58,1)"}),de(O),g(),(B=e.onToggle)==null||B.call(e,r.indexOf(u),b,!1)}return a(),{el:n,openIndex:()=>r.findIndex(u=>u.classList.contains("open")),setOpen(u){r.forEach((M,b)=>M.classList.toggle("open",b===u&&!M.classList.contains("still"))),a(),g(),r.forEach((M,b)=>{var A;return(A=e.onToggle)==null?void 0:A.call(e,b,M.classList.contains("open"),!0)})}}}function eo(t,e,n){let r=i("span",{class:"seg-pill"}),o=i("div",{class:"seg appseg",role:"tablist"},r),a=t.map(A=>{let O=i("button",{type:"button",class:"seg-b",role:"tab","aria-label":A.label,title:A.label,onclick:()=>b(A.value)},F(A.icon),i("span",{class:"seg-l"},A.label));return O.dataset.v=A.value,o.appendChild(O),O}),c=A=>A.querySelector(".seg-l"),g=()=>a.forEach(A=>{let O=A.dataset.v===e;A.classList.toggle("on",O),A.setAttribute("aria-selected",String(O))}),v=()=>{let A=a.find(O=>O.dataset.v===e);return A&&A.offsetWidth?[A.offsetLeft,o.clientWidth-A.offsetLeft-A.offsetWidth]:null},u=()=>{let A=v();A&&(r.style.left=`${A[0]}px`,r.style.right=`${A[1]}px`)},M=0;function b(A){if(A===e)return;let O=a.findIndex(C=>C.dataset.v===e),B=a.findIndex(C=>C.dataset.v===A),P=getComputedStyle(r),H=parseFloat(P.left)||0,$=parseFloat(P.right)||0,d=a.map(C=>parseFloat(getComputedStyle(C).flexGrow)||0),m=c(a[O]),s=m.getBoundingClientRect().width;[...a,...a.map(c)].forEach(C=>C.getAnimations().forEach(R=>R.cancel())),e=A,g(),a.forEach((C,R)=>{let I=R===B?1:0;d[R]!==I&&_(C,[{flexGrow:d[R]},{flexGrow:I}],{duration:U.duration,easing:U.easing})}),_(m,[{opacity:1,maxWidth:`${s}px`,marginLeft:"0px"},{opacity:0,maxWidth:"0px",marginLeft:"-8px"}],{duration:220,easing:"ease-out"}),_(c(a[B]),[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,delay:70,easing:Y,fill:"backwards"});let h=B>O,f=Lt()?U:Fn,E=performance.now(),p=Math.m
Line truncated
|
||||||
`).flatMap((v,A)=>A?[`
|
`).flatMap((u,M)=>M?[`
|
||||||
`,et(v,t)]:[et(v,t)])),l=n("button",{class:"btn small",onclick:v=>{v.preventDefault(),t=!t,l.replaceChildren(U(t?"x":"key"),n("span",{},t?"Hide key":"Show key")),s()}},U("key"),n("span",{},"Show key"));return s(),n("div",{class:"pane"},n("div",{class:"filecard"},n("span",{class:"filecard-ic"},".conf"),n("span",{class:"stack"},n("span",{class:"mono ellipsis"},e.filename),n("span",{class:"faint s"},"For computers and routers: import it in AmneziaWG or AmneziaVPN")),n("button",{class:"btn primary",onclick:()=>nt(e.filename,e.conf)},U("download"),n("span",{},"Download"))),n("details",{class:"confbox"},n("summary",{},U("chevron"),n("span",{},"Configuration"),n("span",{class:"grow"}),l,n("button",{class:"btn small",onclick:v=>{v.preventDefault(),oe(e.conf,"Configuration copied")}},U("copy"),n("span",{},"Copy"))),r))}async function de(e,t,r){let s=r!=null?r:await Re(e);if(!s)return;let l=await Te(s,`${s.server} · ${s.name}`),v=De(),A={app:()=>n("div",{class:"pane"},n("a",{class:"btn primary block big",href:l},U("open"),n("span",{},"Open in AmneziaVPN")),n("ol",{class:"steps"},n("li",{},"No AmneziaVPN yet? ",n("a",{href:"https://amnezia.org/downloads",target:"_blank",rel:"noopener noreferrer"},"Get it here"),"."),n("li",{},"Tap ",n("b",{},"Open in AmneziaVPN")," and confirm the import."),n("li",{},"Turn the connection on — this page shows ",n("span",{class:"ok"},"Connected")," within a minute."))),qr:()=>{let f=n("div",{class:"qr"});return f.innerHTML=Ze(s.conf),n("div",{class:"pane center"},f,n("p",{class:"muted s"},"Scan with the phone’s camera or AmneziaVPN / AmneziaWG."))},key:()=>n("div",{class:"pane"},n("p",{class:"muted s"},"In AmneziaVPN choose “Add server → Insert key”."),n("div",{class:"keybox"},n("span",{class:"mono"},l),n("button",{class:"btn small",onclick:()=>oe(l,"Key copied")},"Copy")),n("p",{class:"faint s"},"Keep it private: anyone with the key can use your connection.")),file:()=>Ut(s)},E=v?["app","qr","key","file"]:["qr","key","file"],N={app:"Open in app",qr:"QR code",key:"Key",file:"File"},$=n("div",{class:"tab-body"}),P=n("div",{class:"tabs",role:"tablist"}),q=f=>{P.querySelectorAll("button").forEach(c=>c.classList.toggle("on",c.dataset.id===f)),$.replaceChildren(A[f]())};for(let f of E)P.appendChild(n("button",{role:"tab","data-id":f,onclick:()=>q(f)},N[f]));q(t&&E.includes(t)?t:E[0]);let O=n("div",{class:"waiting"}),H=f=>{f!=null&&f.online?O.replaceChildren(n("span",{class:"ok"},`${e.name} is connected`)):f!=null&&f.handshake?O.replaceChildren(n("span",{class:"muted"},`Last connected ${Me(f.handshake)}`)):O.replaceChildren(n("span",{class:"warn"},"Waiting for the first connection…"))};H(e);let I=0,le=0,Z=!!e.handshake||e.disabled,we=Date.now(),x=async()=>{if(I=0,!(Z||Date.now()-we>6e5)){if(document.hidden){k();return}try{let f=await ne("state");B=f;let c=f.person.devices.find(y=>y.id===e.id);if(H(c),c!=null&&c.online||c!=null&&c.handshake){Z=!0;return}}catch(f){if(f.status===404||f.status===401){Z=!0;return}}le++,k()}},k=()=>{!Z&&!I&&(I=window.setTimeout(x,le<6?5e3:le<12?15e3:3e4))},b=()=>{!document.hidden&&!Z&&!I&&x()};document.addEventListener("visibilitychange",b),k(),ce(e.handshake?`Connect ${e.name}`:`${e.name} is ready`,v?"Add it to AmneziaVPN on this phone":"Scan with the phone’s camera or AmneziaVPN",P,$,O),ue=()=>{Z=!0,I&&clearTimeout(I),document.removeEventListener("visibilitychange",b),B&&fe(B)}}function Ft(e){let t=n("input",{type:"text",value:e.name,maxlength:48,"aria-label":"Device name"}),r=n("button",{class:"btn primary block",type:"submit"},"Save");ce(`Rename ${e.name}`,null,n("form",{class:"stack gap",onsubmit:s=>{s.preventDefault(),Pe(r,async()=>{try{B=(await ne(`devices/${e.id}`,{action:"rename",name:t.value})).state,ee(),fe(B),te("Renamed")}catch(l){te(l.message,!0)}})}},t,r)),setTimeout(()=>t.select(),50)}function Gt(e,t){let r=t.here===e.id;ce(`New keys for ${e.name}?`,null,n("p",{class:"muted"},r?"This device is connected through the configuration it has now: it disconnects a few seconds after you confirm. Import the new configuration that opens next.":"Its current configuration stops working. Set the device up again with the new one that opens next."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn primary block",onclick:s=>Pe(s.currentTarget,async()=>{try{let l=await ne(`devices/${e.id}`,{action:"rotate"});B=l.state,fe(B),await de(e,void 0,l.config)}catch(l){te(l.message,!0)}})},"New keys")))}function qt(e){ce(`Remove ${e.name}?`,null,n("p",{class:"muted"},"Its connection stops working immediately. You can add it again later."),n("div",{class:"row gap"},n("button",{class:"btn block",onclick:()=>ee()},"Cancel"),n("button",{class:"btn danger-solid block",onclick:t=>Pe(t.currentTarget,async()=>{try{B=(await ne(`devices/${e.id}`,{action:"delete"})).state,ee(),fe(B),te("Device removed")}catch(r){te(r.message,!0)}})},"Remove")))}var V=navigator.userAgent,ot=/iPad/.test(V)||/Macintosh/.test(V)&&navi
Line truncated
|
`,ro(u,e)]:[ro(u,e)]));r();let o=!!Wt(t.filename,t.conf),a=i("button",{type:"button",class:"btn soft sm",onclick:()=>{e=!e,a.replaceChildren(F(e?"x":"key"),i("span",{},e?"Hide key":"Show key")),r(),n.querySelectorAll(".mask, .k").forEach(u=>_(u,[{filter:"blur(4px)",opacity:.4},{filter:"none",opacity:1}],{duration:320,easing:Y}))}},F("key"),i("span",{},"Show key")),c=i("button",{type:"button",class:"btn soft sm",onclick:u=>pt(t.conf,"Configuration copied",u.currentTarget)},F("copy"),i("span",{class:"lbl"},"Copy")),g=i("div",{class:"filecard"},i("div",{class:"fc-row"},i("span",{class:"filecard-ic"},".conf"),i("span",{class:"t"},i("span",{class:"mono"},t.filename),i("span",{},"For computers and routers"))),i("button",{type:"button",class:"btn accent sm block",onclick:()=>ye(t.filename,t.conf)},F(o?"open":"download"),i("span",{},o?"Share file":"Download"))),v=qt([{icon:j("file"),title:"Configuration",body:[i("div",{class:"confbar"},a,c),n]}],{inset:!0});return i("div",{class:"step-box"},g,v.el)}function fo(t){let e=i("span",{class:"osm-p"},at[t]),n=Dr(me(t,"ios"),me(t,"android"));return{el:i("span",{class:"scanline"},i("span",{},"In ",e,":"),n.el),set(r){Z(e,at[r],void 0,{whole:!0}),n.set(me(r,"ios"),me(r,"android"))}}}function ho(t){let e=i("span",{class:"tt"}),n=i("span",{class:"tt-m"}),r=i("span",{class:"hp-tip","aria-hidden":"true"},e,n),o=i("button",{type:"button",class:"hp-b",onclick:()=>ye(t().file,t().text)},F("download")),a=i("button",{type:"button",class:"hp-b"},F("copy")),c=i("div",{class:"hpill",role:"group","aria-label":"The connection","data-key":"conn"},o,a,r),g=null,v=0,u=0,M=s=>{var h;return s===a&&a.classList.contains("done")?"Copied":(h=s.getAttribute("aria-label"))!=null?h:""},b=(s,h)=>{n.textContent=h;let f=n.offsetWidth+20;return Math.min(s.offsetLeft+s.offsetWidth/2,c.offsetWidth+46-f/2)},A=s=>`translateX(${s}px) translateX(-50%)`,O=s=>{let h=getComputedStyle(r).transform;r.getAnimations().forEach(f=>f.cancel()),r.style.transform=A(s),_(r,[{transform:h},{transform:A(s)}],{duration:U.duration,easing:U.easing})},B=s=>Z(e,s),P=s=>{if(clearTimeout(v),g===s&&r.classList.contains("on"))return;if(g=s,r.classList.contains("on")){let f=M(s);return O(b(s,f)),B(f)}let h=()=>{let f=M(s);bt(e,f);let E=b(s,f);r.getAnimations().forEach(p=>p.cancel()),r.style.transform=A(E),r.classList.add("on"),_(r,[{opacity:0,transform:`${A(E)} translateY(-3px) scale(.96)`,filter:"blur(3px)"},{opacity:1,transform:A(E),filter:"blur(0px)"}],{duration:220,easing:Y})};performance.now()<u?h():v=window.setTimeout(h,420)},H=()=>{clearTimeout(v),g=null,r.classList.contains("on")&&(u=performance.now()+500,r.classList.remove("on"),_(r,[{opacity:1},{opacity:0}],{duration:120,easing:"ease-out"}))};for(let s of[o,a])s.addEventListener("pointerenter",h=>{h.pointerType==="mouse"&&P(s)}),s.addEventListener("focus",()=>{s.matches(":focus-visible")&&P(s)}),s.addEventListener("blur",H);c.addEventListener("pointerleave",H);let $=s=>{let h=F(s);a.querySelector("svg").replaceWith(h),_(h,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:yt.duration,easing:yt.easing})},d=()=>{if(g!==a||!r.classList.contains("on"))return;let s=M(a);O(b(a,s)),B(s)},m=0;return a.addEventListener("click",()=>{let s=t();pt(s.text,s.msg),clearTimeout(m),a.classList.contains("done")||(a.classList.add("done"),$("check"),d()),m=window.setTimeout(()=>{a.classList.remove("done"),$("copy"),d()},1600)}),{el:c,sync(){let s=t().app;o.setAttribute("aria-label",`Download ${s} config`),a.setAttribute("aria-label",`Copy ${s} config`)}}}function go(t){let e=i("b",{},"Waiting for the connection"),n=i("span",{class:"ws",hidden:!0}),r=i("div",{class:"way",role:"status","aria-live":"polite"},i("div",{class:"way-row"},i("span",{class:"way-end"},F(t.kind)),i("span",{class:"way-track"},i("span",{class:"way-glow"},i("i")),i("span",{class:"way-fill"})),i("span",{class:"way-end home"},F("server"))),i("div",{class:"way-text"},i("span",{class:"t"},e,n)));return{el:r,connected(){r.classList.add("done"),Z(e,`${t.name} connected`)},gaveUp(){r.classList.add("stopped"),Z(e,"No connection yet"),n.textContent="Close this and open it again to keep checking.",n.hidden=!1,_(e.parentElement,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:Y})}}}function vo(t,e=4){window.setTimeout(async()=>{var n;try{let r=await ut("state");xt(r),be()||Mt(),!((n=r.person.devices.find(o=>o.id===t))!=null&&n.online)&&e>1&&vo(t,e-1)}catch{}},1500)}function yo(t,e,n){let r=te(),o=0,a=0,c=!1,g=Date.now(),v=async()=>{if(o=0,!c){if(Date.now()-g>6e5){c=!0,n();return}if(document.hidden)return u();try{let b=await ut("state");xt(b);let A=b.person.devices.find(O=>O.id===t.id);if(A&&A.handshake>r){c=!0,e(),A.online||vo(t.id);return}}catch(b){if(Oe(b)){c=!0;return}}a++,u()}},u=()=>{!c&&!o&&(o=window.setTimeout(v,a<6?5e3:a<12?15e3:3e4))},M=()=>{!document.hidden&&!c&&!o&&v()};return document.addEventListener("visibilitychange",M),u(),()=>{c=!0,o
Line truncated
|
||||||
@@ -18,6 +18,8 @@
|
|||||||
"settings_get",
|
"settings_get",
|
||||||
"portal_info",
|
"portal_info",
|
||||||
"interfaces",
|
"interfaces",
|
||||||
|
"server_ports",
|
||||||
|
"endpoint_probe",
|
||||||
"events"
|
"events"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,19 +35,17 @@ function log(who, msg, level, detail) {
|
|||||||
|
|
||||||
/* ---------- hostnames ---------- */
|
/* ---------- hostnames ---------- */
|
||||||
|
|
||||||
function host_label(s) {
|
|
||||||
let l = replace(lc(s), /[^a-z0-9]+/g, '-');
|
|
||||||
l = replace(l, /^-+|-+$/g, '');
|
|
||||||
return substr(l, 0, 40) || 'device';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function sync_hosts(m) {
|
export function sync_hosts(m) {
|
||||||
let lines = [];
|
let lines = [];
|
||||||
if (m.settings.hostnames)
|
if (m.settings.hostnames)
|
||||||
for (let id, d in m.devices) {
|
for (let pid, p in m.people) {
|
||||||
let p = m.people[d.person];
|
// One label per device, unique within the person (the UI shows the same).
|
||||||
if (p && ip2int(d.address) != null)
|
let labels = core.device_labels(m, p);
|
||||||
push(lines, `${d.address} ${host_label(d.name)}.${p.id}.${m.settings.domain}`);
|
for (let id in p.devices) {
|
||||||
|
let d = m.devices[id];
|
||||||
|
if (ip2int(d.address) != null)
|
||||||
|
push(lines, `${d.address} ${labels[id]}.${p.id}.${m.settings.domain}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let ls = loop.status();
|
let ls = loop.status();
|
||||||
if (ls.active)
|
if (ls.active)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
import { readfile, stat, unlink } from 'fs';
|
import { readfile, stat, unlink } from 'fs';
|
||||||
import {
|
import {
|
||||||
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, ensure_dir, write_file, read_json, write_json, lock, unlock,
|
q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, tunnel_name, ensure_dir, write_file, read_json, write_json, lock, unlock,
|
||||||
slog, iface_status, DATA_DIR, RUN_DIR
|
slog, iface_status, DATA_DIR, RUN_DIR
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
@@ -226,11 +226,14 @@ function dns_answer() {
|
|||||||
/**
|
/**
|
||||||
* Generate obfuscation parameters for a method:
|
* Generate obfuscation parameters for a method:
|
||||||
* off plain WireGuard-compatible packets
|
* off plain WireGuard-compatible packets
|
||||||
* standard junk packets and random headers (any AmneziaWG client)
|
* balanced AmneziaWG 2.0: junk packets, random headers, padded cookie and
|
||||||
* strong more and larger junk (any AmneziaWG client)
|
* data packets, DNS-shaped signature packets
|
||||||
* max AmneziaWG 3.1: protected headers, random trailers, padding,
|
* max AmneziaWG 3.1: protected headers, random trailers, padding,
|
||||||
* jittered timers and a DNS-like first packet — the values
|
* jittered timers and a DNS-like first packet — the values
|
||||||
* AmneziaVPN itself uses for 3.1 servers
|
* AmneziaVPN itself uses for 3.1 servers
|
||||||
|
* Servers made before 0.8 may still carry the old "standard" or "strong"
|
||||||
|
* values (1.0-style junk only): they keep running as they are, the picker
|
||||||
|
* offers Balanced or Maximum instead.
|
||||||
*/
|
*/
|
||||||
export function obf_preset(name) {
|
export function obf_preset(name) {
|
||||||
if (name == 'max')
|
if (name == 'max')
|
||||||
@@ -247,12 +250,11 @@ export function obf_preset(name) {
|
|||||||
};
|
};
|
||||||
if (name == 'off')
|
if (name == 'off')
|
||||||
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
|
return { jc: '0', jmin: '0', jmax: '0', s1: '0', s2: '0', h1: '1', h2: '2', h3: '3', h4: '4' };
|
||||||
let strong = name == 'strong', balanced = name == 'balanced';
|
|
||||||
let o = {};
|
let o = {};
|
||||||
o.jc = `${strong ? rand_int(6, 10) : balanced ? rand_int(4, 8) : rand_int(3, 6)}`;
|
o.jc = `${rand_int(4, 8)}`;
|
||||||
let jmin = rand_int(64, strong || balanced ? 128 : 96);
|
let jmin = rand_int(64, 128);
|
||||||
o.jmin = `${jmin}`;
|
o.jmin = `${jmin}`;
|
||||||
o.jmax = `${jmin + rand_int(strong ? 200 : balanced ? 150 : 32, strong ? 600 : balanced ? 400 : 160)}`;
|
o.jmax = `${jmin + rand_int(150, 400)}`;
|
||||||
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
|
let s1 = rand_int(15, 64), s2 = rand_int(15, 64);
|
||||||
while (s1 + 56 == s2)
|
while (s1 + 56 == s2)
|
||||||
s2 = rand_int(15, 64);
|
s2 = rand_int(15, 64);
|
||||||
@@ -261,7 +263,6 @@ export function obf_preset(name) {
|
|||||||
let used = {};
|
let used = {};
|
||||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
||||||
o[k] = rand_h(used);
|
o[k] = rand_h(used);
|
||||||
if (balanced) {
|
|
||||||
// AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept
|
// AmneziaWG 2.0: padded cookie and data packets (S4 costs MTU, kept
|
||||||
// small: core.tunnel_mtu) and DNS-shaped signature packets before each
|
// small: core.tunnel_mtu) and DNS-shaped signature packets before each
|
||||||
// handshake — what 1.0 traffic lacks and gets recognised by.
|
// handshake — what 1.0 traffic lacks and gets recognised by.
|
||||||
@@ -269,7 +270,6 @@ export function obf_preset(name) {
|
|||||||
o.s4 = `${rand_int(4, 16)}`;
|
o.s4 = `${rand_int(4, 16)}`;
|
||||||
o.i1 = dns_query();
|
o.i1 = dns_query();
|
||||||
o.i2 = dns_answer();
|
o.i2 = dns_answer();
|
||||||
}
|
|
||||||
return o;
|
return o;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -336,25 +336,6 @@ export function obf_neutral(o) {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
/*
|
|
||||||
* The .conf file name doubles as the tunnel name in WireGuard apps (15
|
|
||||||
* characters at most): the device first, so a person's devices stay apart,
|
|
||||||
* and a number when the cut would still make two of them alike.
|
|
||||||
*/
|
|
||||||
function conf_filename(m, p, dev) {
|
|
||||||
let label = (d) => trim(substr(trim(replace(lc(d.name + '-' + p.id), /[^a-z0-9]+/g, '-'), '-'), 0, 15), '-');
|
|
||||||
let order = sort(map(p.devices, (id) => m.devices[id]),
|
|
||||||
(a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
||||||
let seen = {};
|
|
||||||
for (let d in order) {
|
|
||||||
let l = label(d);
|
|
||||||
let n = seen[l] = (seen[l] ?? 0) + 1;
|
|
||||||
if (d.id == dev.id)
|
|
||||||
return (n > 1 ? trim(substr(l, 0, 15 - length(`-${n}`)), '-') + `-${n}` : l) + '.conf';
|
|
||||||
}
|
|
||||||
return label(dev) + '.conf';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The junk a device sends is its own: within the preset's own ranges, the
|
* The junk a device sends is its own: within the preset's own ranges, the
|
||||||
* count and sizes are shifted a little by the device (deterministic, so the
|
* count and sizes are shifted a little by the device (deterministic, so the
|
||||||
@@ -423,7 +404,8 @@ export function client_config(m, dev) {
|
|||||||
name: dev.name,
|
name: dev.name,
|
||||||
person: p.name,
|
person: p.name,
|
||||||
server: srv.name,
|
server: srv.name,
|
||||||
filename: conf_filename(m, p, dev),
|
// The file name is the tunnel's name in WireGuard apps: the server's, in the portal and the admin alike.
|
||||||
|
filename: `${tunnel_name(srv.name)}.conf`,
|
||||||
conf: join('\n', lines) + '\n',
|
conf: join('\n', lines) + '\n',
|
||||||
has_private_key: dev.private_key != '',
|
has_private_key: dev.private_key != '',
|
||||||
amnezia: {
|
amnezia: {
|
||||||
@@ -464,6 +446,9 @@ export function netifd_options(srv) {
|
|||||||
return o;
|
return o;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Person states whose devices stay in the tunnel: active, and the limits the portal explains. */
|
||||||
|
export const SOFT_STATES = [ 'active', 'quota', 'hours' ];
|
||||||
|
|
||||||
/** Push the peer list of every server to the kernel without restarting it. */
|
/** Push the peer list of every server to the kernel without restarting it. */
|
||||||
export function sync_peers(m, states) {
|
export function sync_peers(m, states) {
|
||||||
ensure_dir(RUN_DIR);
|
ensure_dir(RUN_DIR);
|
||||||
@@ -480,8 +465,11 @@ export function sync_peers(m, states) {
|
|||||||
for (let did, d in m.devices) {
|
for (let did, d in m.devices) {
|
||||||
let p = m.people[d.person];
|
let p = m.people[d.person];
|
||||||
// One malformed line makes syncconf refuse the whole server: such a device
|
// One malformed line makes syncconf refuse the whole server: such a device
|
||||||
// stays out (Health's Data check names it).
|
// stays out (Health's Data check names it). Over the data limit or
|
||||||
if (!p || p.server != id || d.disabled || states[p.id] != 'active' || !valid_key(d.public_key) || ip2int(d.address) == null)
|
// outside the allowed hours the tunnel stays: the access table blocks
|
||||||
|
// everything but the portal, which says why (a silent handshake failure
|
||||||
|
// would look like a broken VPN).
|
||||||
|
if (!p || p.server != id || d.disabled || index(SOFT_STATES, states[p.id]) < 0 || !valid_key(d.public_key) || ip2int(d.address) == null)
|
||||||
continue;
|
continue;
|
||||||
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
push(lines, '[Peer]', `PublicKey = ${d.public_key}`);
|
||||||
if (d.preshared_key)
|
if (d.preshared_key)
|
||||||
@@ -654,3 +642,33 @@ export function mark_issued(m, id) {
|
|||||||
unlock(l);
|
unlock(l);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* ---------- set up again (Reconnect) ---------- */
|
||||||
|
|
||||||
|
const RECONNECT = `${DATA_DIR}/reconnect.json`;
|
||||||
|
|
||||||
|
/** Device id → when the person asked to set it up again (router clock). */
|
||||||
|
export function reconnects() {
|
||||||
|
return read_json(RECONNECT, {});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The handshake a device counts with: none from before it was set up again,
|
||||||
|
* so it shows "Not set up yet" until it connects after that.
|
||||||
|
*/
|
||||||
|
export function handshake_since(hs, since) {
|
||||||
|
return since && hs <= since ? 0 : hs;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A device is set up again: handshakes up to `at` (router clock) are its old configuration's. */
|
||||||
|
export function mark_reconnect(m, id, at) {
|
||||||
|
let l = lock('reconnect');
|
||||||
|
let all = reconnects();
|
||||||
|
all[id] = at ?? time();
|
||||||
|
for (let k in keys(all))
|
||||||
|
if (!m.devices[k])
|
||||||
|
delete all[k];
|
||||||
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
write_json(RECONNECT, all, 0o600);
|
||||||
|
unlock(l);
|
||||||
|
};
|
||||||
|
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import {
|
import {
|
||||||
valid_name, valid_key, valid_host, valid_date, slugify, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
valid_name, valid_key, valid_host, valid_date, slugify, host_label, ucut, NAME_RULE, parse_cidr, cidr_overlaps, int2ip, ip2int,
|
||||||
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
rand_hex, rand_bytes, date_end, month_key, read_json, DATA_DIR, RUN_DIR, uniq
|
||||||
} from 'dawnline.util';
|
} from 'dawnline.util';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
@@ -81,7 +81,6 @@ export function load(c) {
|
|||||||
portal_alt: g('portal_alt'),
|
portal_alt: g('portal_alt'),
|
||||||
portal_cert: g('portal_cert'),
|
portal_cert: g('portal_cert'),
|
||||||
portal_key: g('portal_key'),
|
portal_key: g('portal_key'),
|
||||||
portal_title: g('portal_title'),
|
|
||||||
// Where unknown portal links go instead of a bare 404 (empty = 404).
|
// Where unknown portal links go instead of a bare 404 (empty = 404).
|
||||||
portal_redirect: g('portal_redirect'),
|
portal_redirect: g('portal_redirect'),
|
||||||
default_device_limit: g('default_device_limit'),
|
default_device_limit: g('default_device_limit'),
|
||||||
@@ -482,7 +481,7 @@ 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, '_');
|
||||||
@@ -540,7 +539,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) {
|
||||||
@@ -599,7 +598,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])
|
||||||
@@ -615,6 +614,24 @@ export function update_person(c, m, id, a) {
|
|||||||
fail('Unknown circle.');
|
fail('Unknown circle.');
|
||||||
set('circle', a.circle);
|
set('circle', a.circle);
|
||||||
}
|
}
|
||||||
|
// Another server: every device gets an address in its tunnel (so each
|
||||||
|
// needs its configuration again); circles and home networks are the old
|
||||||
|
// server's and go.
|
||||||
|
if (a.server != null && a.server != '' && a.server != p.server) {
|
||||||
|
if (!m.servers[a.server])
|
||||||
|
fail('Unknown server.');
|
||||||
|
set('server', a.server);
|
||||||
|
p.server = a.server;
|
||||||
|
for (let did in p.devices) {
|
||||||
|
let addr = alloc_address(m, m.servers[a.server]);
|
||||||
|
if (!addr)
|
||||||
|
fail(`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') {
|
if (type(a.home_nets) == 'array') {
|
||||||
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
|
let nets = uniq(filter(map(a.home_nets, (x) => trim(`${x}`)), (x) => match(x, /^[A-Za-z0-9_.@-]{1,32}$/)));
|
||||||
if (length(nets))
|
if (length(nets))
|
||||||
@@ -820,6 +837,50 @@ export function model_errors(m) {
|
|||||||
return errs;
|
return errs;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give every device on a server an address in `subnet` (the server's new
|
||||||
|
* tunnel network), lowest first: used by server_update when the network
|
||||||
|
* changes. Each device then needs its configuration again (the address is
|
||||||
|
* in it). Fails when the subnet cannot hold them.
|
||||||
|
*/
|
||||||
|
export function renumber_server(c, m, srv, subnet) {
|
||||||
|
srv.subnet = subnet;
|
||||||
|
for (let pid, p in m.people)
|
||||||
|
if (p.server == srv.id)
|
||||||
|
for (let did in p.devices)
|
||||||
|
m.devices[did].address = '';
|
||||||
|
for (let pid, p in m.people)
|
||||||
|
if (p.server == srv.id)
|
||||||
|
for (let did in p.devices) {
|
||||||
|
let addr = alloc_address(m, srv);
|
||||||
|
if (!addr)
|
||||||
|
fail(`${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 }].
|
* Port forwards from `zone` for `proto` that aren't Dawnline's: [{ from, to, name }].
|
||||||
* A forwarded port never reaches the router itself, so nothing here can listen on it.
|
* A forwarded port never reaches the router itself, so nothing here can listen on it.
|
||||||
@@ -883,7 +944,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). */
|
||||||
|
|||||||
@@ -104,6 +104,21 @@ export function rotate(id, opts) {
|
|||||||
return cfg;
|
return cfg;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a device up from scratch (a new phone, the app reinstalled, settings
|
||||||
|
* the admin changed): new keys, so the configuration it holds stops working
|
||||||
|
* with the sync, and it counts as not set up until it connects with the new
|
||||||
|
* one. The usage keeps the old keys' last handshake: awg.handshake_since hides
|
||||||
|
* it. Returns the new configuration, as rotate.
|
||||||
|
*/
|
||||||
|
export function reconnect(id, opts) {
|
||||||
|
opts ??= {};
|
||||||
|
let cfg = rotate(id, opts);
|
||||||
|
// A deferred sync (the page came through this device) lets the old keys live a few seconds more.
|
||||||
|
awg.mark_reconnect(core.load(), id, time() + (opts.defer ? 5 : 0));
|
||||||
|
return cfg;
|
||||||
|
};
|
||||||
|
|
||||||
/** Remove a device. Returns the runtime sync. */
|
/** Remove a device. Returns the runtime sync. */
|
||||||
export function remove(id, opts) {
|
export function remove(id, opts) {
|
||||||
opts ??= {};
|
opts ??= {};
|
||||||
|
|||||||
@@ -3,8 +3,9 @@
|
|||||||
// Client addresses are looked up once with a third-party service (ipwho.is,
|
// Client addresses are looked up once with a third-party service (ipwho.is,
|
||||||
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
|
// ipapi.co as fallback) and cached: the live copy in RUN_DIR (tmpfs), put on
|
||||||
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
|
// flash (DATA_DIR/geo.json) by flush() about hourly, like the usage
|
||||||
// counters. Only the agent performs lookups, on its minute tick and within a
|
// counters. Only the agent performs lookups, in a child process (the network
|
||||||
// time budget, never on the 1-second watcher; the UI reads the cache.
|
// may take seconds; neither its watcher nor its tick waits for them) and
|
||||||
|
// merges them into the cache itself; the UI reads the cache.
|
||||||
|
|
||||||
import { stat } from 'fs';
|
import { stat } from 'fs';
|
||||||
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
|
import { read_json, write_json, sh_out, q, ensure_dir, ip2int, DATA_DIR, RUN_DIR } from 'dawnline.util';
|
||||||
@@ -13,7 +14,7 @@ const CACHE = `${RUN_DIR}/geo.json`;
|
|||||||
const SAVED = `${DATA_DIR}/geo.json`;
|
const SAVED = `${DATA_DIR}/geo.json`;
|
||||||
const TTL = 30 * 86400;
|
const TTL = 30 * 86400;
|
||||||
const RETRY = 86400;
|
const RETRY = 86400;
|
||||||
// Entries kept at least; addresses still shown are never pushed out (resolve).
|
// Entries kept at least; addresses still shown are never pushed out (merge).
|
||||||
const CAP = 500;
|
const CAP = 500;
|
||||||
|
|
||||||
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
// [base, prefix] of ranges with no meaningful location (private, CGNAT, multicast, …).
|
||||||
@@ -99,40 +100,64 @@ export function lookup(provider, ip) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve up to `max` of `ips` that are missing or stale, within `budget`
|
* The public addresses of `ips` the cache does not know or knows from too
|
||||||
* seconds (each lookup may wait on the network). Returns true when the cache
|
* long ago (a failed lookup is retried after a day), once each and in order.
|
||||||
* changed (the caller saves it). `ips` is also what is still shown: the cache
|
* Returns an empty array when there is nothing to look up.
|
||||||
* is kept bounded by dropping other entries only, oldest first, so a lookup
|
|
||||||
* is never repeated for an address that is still on the map.
|
|
||||||
*/
|
*/
|
||||||
export function resolve(settings, cache, ips, max, budget) {
|
export function stale(cache, ips, ts) {
|
||||||
let now = time(), changed = false, done = 0;
|
let now = ts ?? time(), out = [], seen = {};
|
||||||
let started = now;
|
|
||||||
for (let ip in ips) {
|
for (let ip in ips) {
|
||||||
if (done >= max || (budget != null && time() - started >= budget))
|
if (seen[ip] || !is_public(ip))
|
||||||
break;
|
|
||||||
if (!is_public(ip))
|
|
||||||
continue;
|
continue;
|
||||||
|
seen[ip] = true;
|
||||||
let c = cache.ips[ip];
|
let c = cache.ips[ip];
|
||||||
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
if (c && ((c.fail && now - c.fail < RETRY) || (!c.fail && c.asn != null && now - c.ts < TTL)))
|
||||||
continue;
|
continue;
|
||||||
let r = lookup(settings.geo_provider, ip);
|
push(out, ip);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Look up at most `max` of `ips`, within `budget` seconds (each lookup may
|
||||||
|
* wait on the network). Returns { ip: place, or false when the services had
|
||||||
|
* nothing } for the ones tried. Network only, no cache: the agent runs it in
|
||||||
|
* a child process and merges the result itself.
|
||||||
|
*/
|
||||||
|
export function lookup_all(provider, ips, max, budget) {
|
||||||
|
let started = time(), out = {}, done = 0;
|
||||||
|
for (let ip in ips) {
|
||||||
|
if (done >= max || (budget != null && time() - started >= budget))
|
||||||
|
break;
|
||||||
|
let r = lookup(provider, ip);
|
||||||
done++;
|
done++;
|
||||||
changed = true;
|
if (r)
|
||||||
if (r) {
|
|
||||||
delete r.ip;
|
delete r.ip;
|
||||||
r.ts = now;
|
out[ip] = r ?? false;
|
||||||
cache.ips[ip] = r;
|
|
||||||
}
|
}
|
||||||
else
|
return out;
|
||||||
cache.ips[ip] = { fail: now };
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Put lookup_all() results into the cache. Returns true when the cache
|
||||||
|
* changed (the caller saves it). `shown` is what is still on the map: the
|
||||||
|
* cache is kept bounded by dropping other entries only, oldest first, so a
|
||||||
|
* lookup is never repeated for an address that is still on the map.
|
||||||
|
*/
|
||||||
|
export function merge(cache, found, shown, ts) {
|
||||||
|
let now = ts ?? time(), changed = false;
|
||||||
|
for (let ip, r in found) {
|
||||||
|
if (!is_public(ip))
|
||||||
|
continue;
|
||||||
|
cache.ips[ip] = r ? { ...r, ts: now } : { fail: now };
|
||||||
|
changed = true;
|
||||||
}
|
}
|
||||||
let shown = {};
|
let keep = {};
|
||||||
for (let ip in ips)
|
for (let ip in shown)
|
||||||
shown[ip] = true;
|
keep[ip] = true;
|
||||||
let all = keys(cache.ips);
|
let all = keys(cache.ips);
|
||||||
if (length(all) > CAP) {
|
if (length(all) > CAP) {
|
||||||
let other = sort(filter(all, (ip) => !shown[ip]),
|
let other = sort(filter(all, (ip) => !keep[ip]),
|
||||||
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
(a, b) => (cache.ips[a].ts ?? cache.ips[a].fail ?? 0) - (cache.ips[b].ts ?? cache.ips[b].fail ?? 0));
|
||||||
for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
|
for (let i = 0; i < length(all) - CAP && i < length(other); i++) {
|
||||||
delete cache.ips[other[i]];
|
delete cache.ips[other[i]];
|
||||||
@@ -159,6 +184,11 @@ export function place(cache, ip) {
|
|||||||
return (c && !c.fail) ? c : null;
|
return (c && !c.fail) ? c : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** "City · ISP" for the activity log; null for no place. */
|
||||||
|
export function label(pl) {
|
||||||
|
return pl ? join(' · ', filter([ pl.city, pl.org ], (x) => x)) : null;
|
||||||
|
};
|
||||||
|
|
||||||
export function clear() {
|
export function clear() {
|
||||||
save({ ips: {}, home: null });
|
save({ ips: {}, home: null });
|
||||||
ensure_dir(DATA_DIR, 0o700);
|
ensure_dir(DATA_DIR, 0o700);
|
||||||
|
|||||||
@@ -233,23 +233,77 @@ function reply_check(id, title, proto, port, r) {
|
|||||||
|
|
||||||
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
const PRIVATE = map([ '100.64.0.0/10', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16' ], parse_cidr);
|
||||||
|
|
||||||
|
/** What 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). */
|
/** What a public address resolves to and whether that reaches this router (for a core's protocol). */
|
||||||
function endpoint_check(id, title, srv, host, proto_note) {
|
function endpoint_check(id, title, srv, host, proto_note) {
|
||||||
if (!host)
|
let w = endpoint_words(endpoint_facts(srv, host), proto_note);
|
||||||
return check(id, title, 'error', 'No public address: devices will not know where to connect.');
|
return check(id, title, w.status, w.text);
|
||||||
let ips = lookup.resolve(host);
|
}
|
||||||
let wan = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
|
||||||
let wc = wan ? ip2int(wan) : null;
|
/**
|
||||||
let cgnat = wc != null && length(filter(PRIVATE, (c) => in_cidr(wc, c))) > 0;
|
* Policy routing by another package (mwan3, pbr): an fwmark rule ahead of
|
||||||
if (!length(ips))
|
* Dawnline's (pref < 5205) whose table has a default route of its own sends
|
||||||
return check(id, title, 'error', `${host} does not resolve.`);
|
* marked tunnel traffic straight out, past "like a home device". Reported,
|
||||||
if (cgnat)
|
* since those marks belong to that package. [] when none.
|
||||||
return check(id, title, 'warn', `WAN address ${wan} is private: forward ${proto_note} on the upstream router, or devices cannot connect.`);
|
*/
|
||||||
if (length(filter(ips, (a) => cloudflare_ip(a))))
|
function policy_routing() {
|
||||||
return check(id, title, 'error', `${host} → ${join(', ', ips)} (Cloudflare). ${proto_note} reaches the router only if this name is DNS-only there, or use the router's IP.`);
|
let out = [];
|
||||||
if (wan && index(ips, wan) < 0)
|
for (let line in split(sh_out('ip -4 rule show 2>/dev/null') ?? '', '\n')) {
|
||||||
return check(id, title, 'warn', `${host} resolves to ${join(', ', ips)}, but the WAN address is ${wan}. Check your DNS / DDNS.`);
|
let mm = match(line, /^(\d+):.*fwmark 0x([0-9a-f]+)(\/0x[0-9a-f]+)?.* lookup (\S+)/);
|
||||||
return check(id, title, 'ok', `${host} → ${join(', ', ips)}`);
|
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).";
|
const NO_PROTO = "netifd doesn't know the amneziawg protocol (AmneziaWG missing, or the network wasn't restarted after installing it).";
|
||||||
@@ -301,19 +355,30 @@ function awg_checks(m, id, srv, label, fwc, dmp, rep) {
|
|||||||
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
|
(st ? `${srv.ifname} is down${length(codes) ? ': ' + join(', ', codes) : ''}.` : `${srv.ifname} does not exist.`),
|
||||||
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
up ? null : (st ? 'ifup:' + srv.ifname : 'apply')));
|
||||||
if (up) {
|
if (up) {
|
||||||
let expected = 0;
|
// By key, not by count: a stale peer standing in for a missing one would
|
||||||
|
// make the numbers match.
|
||||||
let states = apply.states_for(m, core.load_usage());
|
let states = apply.states_for(m, core.load_usage());
|
||||||
|
let wanted = {}, expected = 0;
|
||||||
for (let did, d in m.devices) {
|
for (let did, d in m.devices) {
|
||||||
let p = m.people[d.person];
|
let p = m.people[d.person];
|
||||||
if (p?.server == id && !d.disabled && states[d.person] == 'active')
|
if (p?.server == id && !d.disabled && index(awg.SOFT_STATES, states[d.person]) >= 0) {
|
||||||
|
wanted[d.public_key] = true;
|
||||||
expected++;
|
expected++;
|
||||||
}
|
}
|
||||||
let actual = 0;
|
}
|
||||||
|
let loaded = {}, actual = 0;
|
||||||
for (let k, p in dmp.peers)
|
for (let k, p in dmp.peers)
|
||||||
if (p.ifname == srv.ifname)
|
if (p.ifname == srv.ifname) {
|
||||||
|
loaded[k] = true;
|
||||||
actual++;
|
actual++;
|
||||||
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, expected == actual ? 'ok' : 'warn',
|
}
|
||||||
`${actual} of ${expected} active devices are loaded in the tunnel.`, expected == actual ? null : 'sync'));
|
let missing = length(filter(keys(wanted), (k) => !loaded[k]));
|
||||||
|
let extra = length(filter(keys(loaded), (k) => !wanted[k]));
|
||||||
|
let same = !missing && !extra;
|
||||||
|
push(out, check(`peers_${id}`, `AmneziaWG devices loaded${label}`, same ? 'ok' : 'warn',
|
||||||
|
same ? `${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 rule = fwc.get('firewall', `dawnline_${id}_port`) == 'rule';
|
||||||
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
let zone = fwc.get('firewall', `dawnline_${id}_zone`) == 'zone';
|
||||||
@@ -431,6 +496,14 @@ export function health(m) {
|
|||||||
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.',
|
: 'Table inet dawnline is missing: no device is loaded into the tunnels until it is back.',
|
||||||
nft_ok ? null : 'apply'));
|
nft_ok ? null : 'apply'));
|
||||||
|
|
||||||
|
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).
|
// A device the sync has to leave out (a merged import, a hand-edited config).
|
||||||
let data = core.model_errors(m);
|
let data = core.model_errors(m);
|
||||||
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok',
|
push(out, check('data', 'People and devices consistent', length(data) ? 'error' : 'ok',
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export const CATEGORY = {
|
|||||||
device_added: 'people', device_removed: 'people', devices_removed: 'people',
|
device_added: 'people', device_removed: 'people', devices_removed: 'people',
|
||||||
device_changed: 'people', device_keys: 'people', link_changed: 'people',
|
device_changed: 'people', device_keys: 'people', link_changed: 'people',
|
||||||
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
person_added: 'people', person_removed: 'people', person_changed: 'people',
|
||||||
paused: 'people', resumed: 'people',
|
paused: 'people', resumed: 'people', expiring: 'people', expired_kept: 'people',
|
||||||
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
server_down: 'problems', server_up: 'problems', portal_blocked: 'problems',
|
||||||
};
|
};
|
||||||
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
export const CATEGORIES = [ 'connections', 'people', 'problems' ];
|
||||||
@@ -395,6 +395,35 @@ export function add_event_merged(e, window) {
|
|||||||
unlock(l);
|
unlock(l);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Places for connections logged before their address was located (the
|
||||||
|
* lookup finishes after the event): connect events since `since` from an
|
||||||
|
* address in `where` ({ ip: "City · ISP" }) that have no place yet get it.
|
||||||
|
* Returns true when `ev` changed.
|
||||||
|
*/
|
||||||
|
export function fill_places(ev, where, since) {
|
||||||
|
let changed = false;
|
||||||
|
for (let i = length(ev) - 1; i >= 0 && ev[i].ts >= since; i--) {
|
||||||
|
let e = ev[i];
|
||||||
|
if (e.type == 'connect' && !e.where && where[e.detail]) {
|
||||||
|
e.where = where[e.detail];
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** fill_places() on the live log, written only when something changed. */
|
||||||
|
export function set_places(where, since) {
|
||||||
|
let l = lock('events');
|
||||||
|
let ev = load_events();
|
||||||
|
if (fill_places(ev, where, since)) {
|
||||||
|
ensure_dir(RUN_DIR);
|
||||||
|
write_json(`${RUN_DIR}/events.json`, ev, 0o600);
|
||||||
|
}
|
||||||
|
unlock(l);
|
||||||
|
};
|
||||||
|
|
||||||
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
/** Save the log to flash, or drop the flash copy when it is kept in RAM only. */
|
||||||
export function persist_events(pol) {
|
export function persist_events(pol) {
|
||||||
pol ??= policy();
|
pol ??= policy();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
// time, so a slow DNS server must not hold up the whole admin UI.
|
// time, so a slow DNS server must not hold up the whole admin UI.
|
||||||
|
|
||||||
import { readfile } from 'fs';
|
import { readfile } from 'fs';
|
||||||
import { q, sh, ensure_dir, read_json, write_json, ip2int, rand_hex, RUN_DIR } from 'dawnline.util';
|
import { q, sh, ensure_dir, read_json, write_json, ip2int, is_ip6, rand_hex, RUN_DIR } from 'dawnline.util';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
|
|
||||||
@@ -23,9 +23,10 @@ function valid_name(h) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IPv4 addresses of each name: { host: [ ip, … ] } (empty when it does not
|
* Addresses of each name, IPv4 and IPv6: { host: [ ip, … ] } (empty when it
|
||||||
* resolve). IP addresses map to themselves. Every uncached name is asked of
|
* does not resolve). IP addresses map to themselves. Every uncached name is
|
||||||
* every server at once; the first server (in SERVERS order) that answers wins.
|
* asked of every server at once, A and AAAA; the first server (in SERVERS
|
||||||
|
* order) that answers wins.
|
||||||
*/
|
*/
|
||||||
export function resolve_all(hosts) {
|
export function resolve_all(hosts) {
|
||||||
let out = {}, now = time(), todo = [];
|
let out = {}, now = time(), todo = [];
|
||||||
@@ -33,7 +34,7 @@ export function resolve_all(hosts) {
|
|||||||
for (let h in hosts) {
|
for (let h in hosts) {
|
||||||
if (h == null || out[h] != null)
|
if (h == null || out[h] != null)
|
||||||
continue;
|
continue;
|
||||||
if (ip2int(h) != null) {
|
if (ip2int(h) != null || is_ip6(h)) {
|
||||||
out[h] = [ h ];
|
out[h] = [ h ];
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -55,14 +56,16 @@ export function resolve_all(hosts) {
|
|||||||
let cmds = [];
|
let cmds = [];
|
||||||
for (let i = 0; i < length(todo); i++)
|
for (let i = 0; i < length(todo); i++)
|
||||||
for (let j = 0; j < length(SERVERS); j++)
|
for (let j = 0; j < length(SERVERS); j++)
|
||||||
|
for (let t in [ 'a', 'aaaa' ])
|
||||||
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
|
// nslookup's own timeout: some firmware builds BusyBox without `timeout`.
|
||||||
push(cmds, `( nslookup -type=a -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j} ) &`);
|
push(cmds, `( nslookup -type=${t} -timeout=${TIMEOUT} -retry=1 ${q(todo[i])} ${SERVERS[j]} 2>/dev/null | awk '/^Address/ && NR>2 {print $NF}' > ${dir}/${i}.${j}.${t} ) &`);
|
||||||
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
|
sh(`mkdir -p ${dir}; ${join(' ', cmds)} wait`);
|
||||||
for (let i = 0; i < length(todo); i++) {
|
for (let i = 0; i < length(todo); i++) {
|
||||||
let ips = [];
|
let ips = [];
|
||||||
for (let j = 0; j < length(SERVERS) && !length(ips); j++) {
|
for (let j = 0; j < length(SERVERS) && !length(ips); j++)
|
||||||
let r = readfile(`${dir}/${i}.${j}`) ?? '';
|
for (let t in [ 'a', 'aaaa' ]) {
|
||||||
ips = filter(split(trim(r), '\n'), (x) => ip2int(x) != null);
|
let r = readfile(`${dir}/${i}.${j}.${t}`) ?? '';
|
||||||
|
push(ips, ...filter(split(trim(r), '\n'), (x) => ip2int(x) != null || is_ip6(x)));
|
||||||
}
|
}
|
||||||
out[todo[i]] = ips;
|
out[todo[i]] = ips;
|
||||||
cache[todo[i]] = { ts: now, ips };
|
cache[todo[i]] = { ts: now, ips };
|
||||||
|
|||||||
@@ -57,6 +57,14 @@ export function uhttpd() {
|
|||||||
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
|
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_443'));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The portal names itself after the server now (the breadcrumb, the tab): its own title setting is gone. */
|
||||||
|
function portal_title() {
|
||||||
|
let c = cursor();
|
||||||
|
c.load('dawnline');
|
||||||
|
if (c.get('dawnline', 'settings', 'portal_title') != null)
|
||||||
|
store.transact((w, m) => w.delete('dawnline', 'settings', 'portal_title'));
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Steps that cannot tell from the config whether they ran are recorded in
|
* Steps that cannot tell from the config whether they ran are recorded in
|
||||||
* `settings.migrated` (a list), so they run exactly once.
|
* `settings.migrated` (a list), so they run exactly once.
|
||||||
@@ -101,4 +109,5 @@ export function run() {
|
|||||||
word_codes();
|
word_codes();
|
||||||
uhttpd();
|
uhttpd();
|
||||||
auto_mtu();
|
auto_mtu();
|
||||||
|
portal_title();
|
||||||
};
|
};
|
||||||
@@ -64,8 +64,8 @@ const NOT_READY = "Adding devices isn't available right now: the VPN server isn'
|
|||||||
|
|
||||||
// States the admin stopped the person in: the portal only shows, it changes nothing.
|
// States the admin stopped the person in: the portal only shows, it changes nothing.
|
||||||
const LOCKED = {
|
const LOCKED = {
|
||||||
paused: 'Your access is paused by the admin.',
|
paused: 'Your access is paused.',
|
||||||
expired: 'Your access has ended. Ask the admin to extend it.',
|
expired: 'Your access has ended.',
|
||||||
};
|
};
|
||||||
|
|
||||||
function html_escape(s) {
|
function html_escape(s) {
|
||||||
@@ -241,11 +241,16 @@ function rate_action(r) {
|
|||||||
|
|
||||||
/* ---------- pages ---------- */
|
/* ---------- pages ---------- */
|
||||||
|
|
||||||
|
/** What the page is called (the tab, the first crumb): the person's server, or Dawnline. */
|
||||||
|
function place(r) {
|
||||||
|
return r.person ? r.m.servers[r.person.server]?.name || 'Dawnline' : 'Dawnline';
|
||||||
|
}
|
||||||
|
|
||||||
/** The app shell; it reads the code from its own URL and sends it along. */
|
/** The app shell; it reads the code from its own URL and sends it along. */
|
||||||
function shell(r) {
|
function shell(r) {
|
||||||
// The build's time joins the version so every update busts the hour-long asset cache.
|
// The build's time joins the version so every update busts the hour-long asset cache.
|
||||||
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
|
||||||
let base = r.base, title = r.title;
|
let base = r.base, title = place(r);
|
||||||
headers(r, '200 OK', {
|
headers(r, '200 OK', {
|
||||||
'Content-Type': 'text/html; charset=utf-8',
|
'Content-Type': 'text/html; charset=utf-8',
|
||||||
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
|
||||||
@@ -338,26 +343,32 @@ function need_https(r) {
|
|||||||
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u });
|
send_json(r, '403 Forbidden', { error: 'Open this link over HTTPS to get the connection settings.', https_url: u });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The router's offset from UTC in minutes: the admin sets hours in its time, the page shows the visitor's. */
|
||||||
|
function tz_offset() {
|
||||||
|
let t = time();
|
||||||
|
return int((timegm(localtime(t)) - t) / 60);
|
||||||
|
}
|
||||||
|
|
||||||
/** Everything the page shows. */
|
/** Everything the page shows. */
|
||||||
function state(r) {
|
function state(r) {
|
||||||
let m = r.m, person = r.person;
|
let m = r.m, person = r.person;
|
||||||
let usage = core.load_usage();
|
let usage = core.load_usage();
|
||||||
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
|
||||||
v.state = person_state(m, person, usage);
|
v.state = person_state(m, person, usage);
|
||||||
|
// Day by day this month, for the page's chart (the admin's views have no use for it).
|
||||||
|
v.month_days = view.month_days(usage.people?.[person.id]);
|
||||||
let srv = m.servers[person.server];
|
let srv = m.servers[person.server];
|
||||||
// The device this page was opened from, when it came through the tunnel.
|
// The device this page was opened from, through the tunnel or beside it.
|
||||||
let here = null;
|
let here = view.device_here(v.devices, r.peer);
|
||||||
for (let id, d in m.devices)
|
|
||||||
if (d.person == person.id && d.address == r.peer)
|
|
||||||
here = id;
|
|
||||||
return {
|
return {
|
||||||
title: r.title,
|
|
||||||
person: v,
|
person: v,
|
||||||
here,
|
here,
|
||||||
server: {
|
server: {
|
||||||
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
|
name: srv?.name, endpoint: srv ? core.endpoint_host(m, srv) : '', device_mesh: !!srv?.device_mesh,
|
||||||
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
|
// AmneziaWG with the disguise off is plain WireGuard (any WireGuard app).
|
||||||
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
awg_disguise: srv ? !awg.obf_neutral(srv.obf) : false,
|
||||||
|
// Which apps (and versions) connect: off, balanced (2.0), max (3.1); legacy = the old junk-only presets.
|
||||||
|
preset: !srv || awg.obf_neutral(srv.obf) ? 'off' : index([ 'balanced', 'max' ], srv.preset) >= 0 ? srv.preset : 'legacy',
|
||||||
},
|
},
|
||||||
can_add: length(person.devices) < person.device_limit,
|
can_add: length(person.devices) < person.device_limit,
|
||||||
locked: LOCKED[v.state] != null,
|
locked: LOCKED[v.state] != null,
|
||||||
@@ -366,6 +377,10 @@ function state(r) {
|
|||||||
kinds: core.KINDS,
|
kinds: core.KINDS,
|
||||||
// The router's day: access ends and usage days follow its clock, not the browser's.
|
// The router's day: access ends and usage days follow its clock, not the browser's.
|
||||||
today: today(),
|
today: today(),
|
||||||
|
// Its clock too: "last connected 3 min ago" is measured against it, not the phone's.
|
||||||
|
now: time(),
|
||||||
|
// And its time zone: hours are set in the router's time, shown in the visitor's.
|
||||||
|
tz_offset: tz_offset(),
|
||||||
version: VERSION,
|
version: VERSION,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -408,11 +423,12 @@ const ACTIONS = {
|
|||||||
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
|
guard(r, () => devices.update(d.id, { name: b.name }, { by: 'portal', person: r.person.id }));
|
||||||
return {};
|
return {};
|
||||||
},
|
},
|
||||||
rotate: (r, d, b) => {
|
// Set up from scratch: new keys and the new configuration, which the set-up sheet takes in.
|
||||||
|
reconnect: (r, d, b) => {
|
||||||
need_https(r);
|
need_https(r);
|
||||||
if (!devices.ready())
|
if (!devices.ready())
|
||||||
fail(r, '503 Service Unavailable', NOT_READY);
|
fail(r, '503 Service Unavailable', NOT_READY);
|
||||||
let config = guard(r, () => devices.rotate(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
|
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
|
||||||
return { config };
|
return { config };
|
||||||
},
|
},
|
||||||
'delete': (r, d, b) => {
|
'delete': (r, d, b) => {
|
||||||
@@ -479,7 +495,6 @@ export function handle(io) {
|
|||||||
method: env.REQUEST_METHOD ?? 'GET',
|
method: env.REQUEST_METHOD ?? 'GET',
|
||||||
peer: env.REMOTE_ADDR ?? '',
|
peer: env.REMOTE_ADDR ?? '',
|
||||||
buckets: buckets(env),
|
buckets: buckets(env),
|
||||||
title: m.settings.portal_title || 'Dawnline',
|
|
||||||
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
|
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
|
||||||
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
|
||||||
person: null,
|
person: null,
|
||||||
|
|||||||
@@ -34,7 +34,13 @@ export function clamp_days(v) {
|
|||||||
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
|
return n >= 1 ? (n > 400 ? 400 : int(n)) : 30;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const METHODS = [ 'off', 'standard', 'strong', 'balanced', 'max' ];
|
export const METHODS = [ 'off', 'balanced', 'max' ];
|
||||||
|
|
||||||
|
/** The disguise a new server gets: the strongest this router can run. */
|
||||||
|
export function default_method() {
|
||||||
|
let c = awg.caps();
|
||||||
|
return c.v3 ? 'max' : c.v2 ? 'balanced' : 'off';
|
||||||
|
};
|
||||||
|
|
||||||
/** A disguise method the installed AmneziaWG can run. */
|
/** A disguise method the installed AmneziaWG can run. */
|
||||||
export function check_method(name) {
|
export function check_method(name) {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
import { readfile } from 'fs';
|
import { readfile } from 'fs';
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import { sh_out, ip2int, rand_int, rand_hex, admin_log } from 'dawnline.util';
|
import { sh_out, ip2int, rand_int, rand_hex, admin_log, valid_name, ulength, NAME_RULE } from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as apply from 'dawnline.apply';
|
import * as apply from 'dawnline.apply';
|
||||||
import * as net from 'dawnline.net';
|
import * as net from 'dawnline.net';
|
||||||
@@ -27,8 +27,8 @@ function new_id(m, make) {
|
|||||||
|
|
||||||
function service_set(a) {
|
function service_set(a) {
|
||||||
let name = str(a.name);
|
let name = str(a.name);
|
||||||
if (name == '' || length(name) > 48)
|
if (!valid_name(name))
|
||||||
die('Enter a service name.');
|
die(`Service: ${NAME_RULE}`);
|
||||||
let address = str(a.address);
|
let address = str(a.address);
|
||||||
if (!schema.ipv4(address))
|
if (!schema.ipv4(address))
|
||||||
die('Address must be an IPv4 address.');
|
die('Address must be an IPv4 address.');
|
||||||
@@ -81,8 +81,8 @@ function service_delete(a) {
|
|||||||
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
/** Create or edit a circle; `members` (person ids) replaces who is in it. */
|
||||||
function circle_set(a) {
|
function circle_set(a) {
|
||||||
let name = str(a.name);
|
let name = str(a.name);
|
||||||
if (name == '' || length(name) > 32)
|
if (!valid_name(name) || ulength(name) > 32)
|
||||||
die('Enter a circle name (up to 32 characters).');
|
die('Enter a circle name: up to 32 characters, without < > " or \\.');
|
||||||
let res = store.transact((c, m) => {
|
let res = store.transact((c, m) => {
|
||||||
let ci = a.id ? m.circles[a.id] : null;
|
let ci = a.id ? m.circles[a.id] : null;
|
||||||
if (a.id && !ci)
|
if (a.id && !ci)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import * as devices from 'dawnline.devices';
|
|||||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
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',
|
const PERSON_FIELDS = [ 'name', 'access', 'device_limit', 'expires', 'expire_action', 'expire_warn', 'quota_gb', 'quota_period',
|
||||||
'bonus_gb', 'hours', 'note', 'dns_mode' ];
|
'bonus_gb', 'hours', 'note', 'dns_mode', 'server' ];
|
||||||
|
|
||||||
/* ---------- people ---------- */
|
/* ---------- people ---------- */
|
||||||
|
|
||||||
@@ -39,12 +39,16 @@ function person_update(a) {
|
|||||||
fields.circle = a.circle;
|
fields.circle = a.circle;
|
||||||
if (type(a.home_nets) == 'array')
|
if (type(a.home_nets) == 'array')
|
||||||
fields.home_nets = a.home_nets;
|
fields.home_nets = a.home_nets;
|
||||||
|
let m0 = null;
|
||||||
let before = store.transact((c, m) => {
|
let before = store.transact((c, m) => {
|
||||||
let p = m.people[a.id];
|
let p = m.people[a.id];
|
||||||
|
m0 = m;
|
||||||
core.update_person(c, m, a.id, fields);
|
core.update_person(c, m, a.id, fields);
|
||||||
return p;
|
return p;
|
||||||
});
|
});
|
||||||
let changes = join(', ', filter(keys(fields), (k) => k != 'note'));
|
// "moved to Test" says more than "server".
|
||||||
|
let changes = join(', ', map(filter(keys(fields), (k) => k != 'note'),
|
||||||
|
(k) => k == 'server' && m0?.servers[fields.server] ? `moved to ${m0.servers[fields.server].name}` : k));
|
||||||
if (changes)
|
if (changes)
|
||||||
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
|
live.add_event_merged({ type: 'person_changed', person: a.id, detail: changes, by: 'admin' }, 120);
|
||||||
// Access changes affect the nft sets and client AllowedIPs.
|
// Access changes affect the nft sets and client AllowedIPs.
|
||||||
@@ -156,7 +160,7 @@ export const methods = {
|
|||||||
},
|
},
|
||||||
person_update: {
|
person_update: {
|
||||||
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
|
args: { id: '', name: '', access: '', device_limit: '', expires: '', expire_action: '', expire_warn: '', quota_gb: '',
|
||||||
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [] },
|
quota_period: '', bonus_gb: '', hours: '', note: '', dns_mode: '', paused: false, services: [], circle: '', home_nets: [], server: '' },
|
||||||
call: wrap(person_update),
|
call: wrap(person_update),
|
||||||
},
|
},
|
||||||
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
|
person_pause: { args: { id: '', paused: false }, call: wrap(person_pause) },
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
// Interfaces settings, its disguise, and removing it.
|
// Interfaces settings, its disguise, and removing it.
|
||||||
|
|
||||||
import { cursor } from 'uci';
|
import { cursor } from 'uci';
|
||||||
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, rand_int, uniq, admin_log } from 'dawnline.util';
|
import { sh_out, sh_bg, parse_cidr, cidr_str, cidr_overlaps, valid_host, valid_name, NAME_RULE, rand_int, uniq, admin_log } from 'dawnline.util';
|
||||||
import * as core from 'dawnline.core';
|
import * as core from 'dawnline.core';
|
||||||
import * as live from 'dawnline.live';
|
import * as live from 'dawnline.live';
|
||||||
import * as apply from 'dawnline.apply';
|
import * as apply from 'dawnline.apply';
|
||||||
@@ -14,7 +14,7 @@ import * as schema from 'dawnline.schema';
|
|||||||
import * as health from 'dawnline.health';
|
import * as health from 'dawnline.health';
|
||||||
import * as backup from 'dawnline.backup';
|
import * as backup from 'dawnline.backup';
|
||||||
import * as devices from 'dawnline.devices';
|
import * as devices from 'dawnline.devices';
|
||||||
import { wrap, str, check_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
|
import { wrap, str, check_method, default_method, check_portal, tcp_taken } from 'dawnline.rpc.common';
|
||||||
|
|
||||||
/** Server ids that would shadow a portal path. */
|
/** Server ids that would shadow a portal path. */
|
||||||
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
|
const PORTAL_PATHS = [ 'api', 'assets', 'cgi-bin' ];
|
||||||
@@ -77,8 +77,9 @@ function free_port(taken) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function free_subnet(taken) {
|
function free_subnet(taken) {
|
||||||
for (let i = 0; i < 200; i++) {
|
for (let i = 0; i < 300; i++) {
|
||||||
let cand = parse_cidr(sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)));
|
// 10.x first; past 200 tries (a 10/8 LAN) the 172.16-31 range.
|
||||||
|
let cand = parse_cidr(i < 200 ? sprintf('10.%d.%d.0/24', rand_int(60, 250), rand_int(0, 250)) : sprintf('172.%d.%d.0/24', rand_int(16, 31), rand_int(0, 250)));
|
||||||
let bad = false;
|
let bad = false;
|
||||||
for (let t in taken) {
|
for (let t in taken) {
|
||||||
let tc = parse_cidr(t);
|
let tc = parse_cidr(t);
|
||||||
@@ -164,21 +165,33 @@ function setup_defaults(a) {
|
|||||||
let fc = cursor();
|
let fc = cursor();
|
||||||
fc.load('firewall');
|
fc.load('firewall');
|
||||||
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
|
fc.foreach('firewall', 'zone', (z) => push(zones, z.name));
|
||||||
let host = m.settings.portal_host;
|
let snap = net.snapshot(true);
|
||||||
|
let wan_ip = snap.wan ? split(snap.devices[snap.wan]?.addrs?.[0] ?? '', '/')[0] : '';
|
||||||
|
let kind = health.wan_kind(wan_ip || null);
|
||||||
|
let host = m.settings.portal_host, from = host ? 'portal' : '';
|
||||||
if (!host) {
|
if (!host) {
|
||||||
// Prefer a DDNS name, then an ACME certificate's, then the WAN address.
|
// Prefer a DDNS name, then an ACME certificate's, then the WAN address —
|
||||||
|
// but never a private or CGNAT one: nobody on the internet reaches it.
|
||||||
let dc = cursor();
|
let dc = cursor();
|
||||||
if (dc.load('ddns'))
|
if (dc.load('ddns'))
|
||||||
dc.foreach('ddns', 'service', (s) => {
|
dc.foreach('ddns', 'service', (s) => {
|
||||||
if (!host && s.lookup_host && s.enabled == '1')
|
if (!host && s.lookup_host && s.enabled == '1') {
|
||||||
host = s.lookup_host;
|
host = s.lookup_host;
|
||||||
});
|
from = 'ddns';
|
||||||
if (!host)
|
|
||||||
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
|
|
||||||
if (!host)
|
|
||||||
host = live.iface_status('wan')?.['ipv4-address']?.[0]?.address ?? '';
|
|
||||||
}
|
}
|
||||||
let wan_zone = index(zones, 'wan') >= 0 ? 'wan' : zones[1];
|
});
|
||||||
|
if (!host) {
|
||||||
|
host = sh_out("ls /etc/ssl/acme/ 2>/dev/null | sed -n 's/\\.fullchain\\.crt$//p' | head -n1") || '';
|
||||||
|
from = host ? 'cert' : '';
|
||||||
|
}
|
||||||
|
if (!host && kind == 'public') {
|
||||||
|
host = wan_ip;
|
||||||
|
from = 'wan';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The zones the WAN and LAN devices are in, whatever they are called.
|
||||||
|
let wan_zone = snap.devices[snap.wan]?.zone ?? (index(zones, 'wan') >= 0 ? 'wan' : zones[1]);
|
||||||
|
let lan_zone = snap.devices[snap.lan]?.zone ?? (index(zones, 'lan') >= 0 ? 'lan' : zones[0]);
|
||||||
let udp = udp_taken(m, null, wan_zone);
|
let udp = udp_taken(m, null, wan_zone);
|
||||||
let tcp = tcp_taken(m);
|
let tcp = tcp_taken(m);
|
||||||
let port = free_port(udp);
|
let port = free_port(udp);
|
||||||
@@ -189,10 +202,14 @@ function setup_defaults(a) {
|
|||||||
port,
|
port,
|
||||||
subnet: free_subnet(map(networks, (n) => n.cidr)),
|
subnet: free_subnet(map(networks, (n) => n.cidr)),
|
||||||
endpoint: host,
|
endpoint: host,
|
||||||
|
// Where the address came from (ddns, cert, wan, portal) and what the WAN is (public, private, cgnat, none).
|
||||||
|
endpoint_from: from,
|
||||||
|
wan_kind: kind,
|
||||||
|
wan_ip: wan_ip || null,
|
||||||
// Automatic.
|
// Automatic.
|
||||||
mtu: 0,
|
mtu: 0,
|
||||||
zones,
|
zones,
|
||||||
lan_zone: index(zones, 'lan') >= 0 ? 'lan' : zones[0],
|
lan_zone,
|
||||||
wan_zone,
|
wan_zone,
|
||||||
// A portal already on keeps its port; a new one takes the server's number when it can.
|
// A portal already on keeps its port; a new one takes the server's number when it can.
|
||||||
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
|
portal_port: m.settings.portal_enabled ? m.settings.portal_port : free_portal_port(port, m.settings.portal_port, tcp),
|
||||||
@@ -204,6 +221,22 @@ function setup_defaults(a) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a public address points, as the admin types it (debounced in the
|
||||||
|
* UI): the same facts Health uses, in words. `id` names the server whose WAN
|
||||||
|
* to compare with (a new one: the default WAN).
|
||||||
|
*/
|
||||||
|
function endpoint_probe(a) {
|
||||||
|
let host = str(a.host);
|
||||||
|
if (host != '' && !valid_host(host))
|
||||||
|
die('Public address must be a hostname or IP address.');
|
||||||
|
let m = core.load();
|
||||||
|
let srv = m.servers[str(a.id)] ?? null;
|
||||||
|
let f = health.endpoint_facts(srv, host);
|
||||||
|
let w = health.endpoint_words(f, `UDP ${srv?.port ?? +a.port || 4500}`);
|
||||||
|
return { ...f, status: w.status, text: w.text };
|
||||||
|
}
|
||||||
|
|
||||||
/** AmneziaWG can run a server: installed, and its kernel module loads. */
|
/** AmneziaWG can run a server: installed, and its kernel module loads. */
|
||||||
function need_awg_loaded() {
|
function need_awg_loaded() {
|
||||||
devices.need_awg();
|
devices.need_awg();
|
||||||
@@ -244,7 +277,7 @@ function server_create(a) {
|
|||||||
}
|
}
|
||||||
check_udp_port(port, udp);
|
check_udp_port(port, udp);
|
||||||
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
|
let mtu = check_mtu(a.mtu == 0 ? '' : a.mtu);
|
||||||
let preset = str(a.preset) || 'standard';
|
let preset = str(a.preset) || default_method();
|
||||||
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
|
let srv = { id, ifname, port, subnet: str(a.subnet), endpoint: str(a.endpoint), obf: awg.obf_preset(check_method(preset)) };
|
||||||
let pc = parse_cidr(srv.subnet);
|
let pc = parse_cidr(srv.subnet);
|
||||||
if (pc)
|
if (pc)
|
||||||
@@ -264,6 +297,8 @@ function server_create(a) {
|
|||||||
let set = (k, v) => c.set(core.CONFIG, id, k, v);
|
let set = (k, v) => c.set(core.CONFIG, id, k, v);
|
||||||
c.set(core.CONFIG, 'settings', 'settings');
|
c.set(core.CONFIG, 'settings', 'settings');
|
||||||
c.set(core.CONFIG, id, 'server');
|
c.set(core.CONFIG, id, 'server');
|
||||||
|
if (!valid_name(str(a.name) || 'Home'))
|
||||||
|
die(`Server: ${NAME_RULE}`);
|
||||||
set('name', str(a.name) || 'Home');
|
set('name', str(a.name) || 'Home');
|
||||||
set('ifname', ifname);
|
set('ifname', ifname);
|
||||||
set('port', `${port}`);
|
set('port', `${port}`);
|
||||||
@@ -465,12 +500,13 @@ function server_update(a) {
|
|||||||
die('Unknown server.');
|
die('Unknown server.');
|
||||||
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
|
let set = (k, val) => (val == null || val == '') ? c.delete(core.CONFIG, srv.id, k) : c.set(core.CONFIG, srv.id, k, val);
|
||||||
if (v.name != null) {
|
if (v.name != null) {
|
||||||
if (str(v.name) == '')
|
if (!valid_name(str(v.name)))
|
||||||
die('Name cannot be empty.');
|
die(`Server: ${NAME_RULE}`);
|
||||||
set('name', str(v.name));
|
set('name', str(v.name));
|
||||||
}
|
}
|
||||||
|
// Empty = the portal's address (core.endpoint_host), as at creation.
|
||||||
if (v.endpoint != null) {
|
if (v.endpoint != null) {
|
||||||
if (str(v.endpoint) == '' || !valid_host(str(v.endpoint)))
|
if (str(v.endpoint) != '' && !valid_host(str(v.endpoint)))
|
||||||
die('Public address must be a hostname or IP address.');
|
die('Public address must be a hostname or IP address.');
|
||||||
set('endpoint', str(v.endpoint));
|
set('endpoint', str(v.endpoint));
|
||||||
}
|
}
|
||||||
@@ -504,10 +540,23 @@ function server_update(a) {
|
|||||||
else
|
else
|
||||||
c.delete(core.CONFIG, srv.id, 'dns');
|
c.delete(core.CONFIG, srv.id, 'dns');
|
||||||
}
|
}
|
||||||
|
// A new tunnel network: private, free, and every device renumbered into it.
|
||||||
|
if (v.subnet != null && str(v.subnet) != '' && str(v.subnet) != srv.subnet) {
|
||||||
|
let pc = parse_cidr(str(v.subnet));
|
||||||
|
if (!pc)
|
||||||
|
die('Subnet must look like 10.77.0.0/24.');
|
||||||
|
if (!core.private_cidr(pc))
|
||||||
|
die('Use a private range: 10.x.x.x, 172.16–31.x.x or 192.168.x.x.');
|
||||||
|
let taken = map(filter(taken_networks(m), (n) => n.cidr != srv.subnet && n.name != srv.name), (n) => n.cidr);
|
||||||
|
for (let t in taken)
|
||||||
|
if (cidr_overlaps(pc, parse_cidr(t)))
|
||||||
|
die(`Subnet overlaps ${t}.`);
|
||||||
|
core.renumber_server(c, m, srv, cidr_str(pc));
|
||||||
|
}
|
||||||
return srv;
|
return srv;
|
||||||
});
|
});
|
||||||
// For the log: what changed, in words. Turning on or off is its own line.
|
// For the log: what changed, in words. Turning on or off is its own line.
|
||||||
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS' };
|
let labels = { name: 'name', endpoint: 'public address', port: 'AmneziaWG port', mtu: 'MTU', keepalive: 'keep-alive', dns: 'DNS', subnet: 'tunnel network' };
|
||||||
let what = [];
|
let what = [];
|
||||||
for (let k, label in labels) {
|
for (let k, label in labels) {
|
||||||
if (v[k] == null)
|
if (v[k] == null)
|
||||||
@@ -529,8 +578,19 @@ function server_update(a) {
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What the ports of an existing server must avoid (the AmneziaWG card checks as you type). */
|
||||||
|
function server_ports(a) {
|
||||||
|
let m = core.load();
|
||||||
|
let srv = m.servers[a.id];
|
||||||
|
if (!srv)
|
||||||
|
die('Unknown server.');
|
||||||
|
// `networks`: what a new tunnel network must not overlap (everything but this server's own).
|
||||||
|
return { udp_taken: udp_taken(m, srv, srv.wan_zone), tcp_taken: tcp_taken(m),
|
||||||
|
networks: filter(taken_networks(m), (n) => n.cidr != srv.subnet) };
|
||||||
|
}
|
||||||
|
|
||||||
function server_obfuscation(a) {
|
function server_obfuscation(a) {
|
||||||
let preset = str(a.preset) || 'standard';
|
let preset = str(a.preset) || default_method();
|
||||||
let o = awg.obf_preset(check_method(preset));
|
let o = awg.obf_preset(check_method(preset));
|
||||||
let srv = store.transact((c, m) => {
|
let srv = store.transact((c, m) => {
|
||||||
let srv = m.servers[a.id];
|
let srv = m.servers[a.id];
|
||||||
@@ -581,6 +641,8 @@ export const methods = {
|
|||||||
lan_like: true, portal_enabled: false, portal_port: 0 },
|
lan_like: true, portal_enabled: false, portal_port: 0 },
|
||||||
call: wrap(server_create),
|
call: wrap(server_create),
|
||||||
},
|
},
|
||||||
|
server_ports: { args: { id: '' }, call: wrap(server_ports) },
|
||||||
|
endpoint_probe: { args: { host: '', id: '', port: 0 }, call: wrap(endpoint_probe) },
|
||||||
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
|
server_obfuscation: { args: { id: '', preset: '' }, call: wrap(server_obfuscation) },
|
||||||
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
|
server_update: { args: { id: '', values: {} }, call: wrap(server_update) },
|
||||||
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
|
interfaces: { args: { id: '' }, call: wrap(interfaces_get) },
|
||||||
|
|||||||
@@ -11,8 +11,29 @@ import * as net from 'dawnline.net';
|
|||||||
import * as loop from 'dawnline.loop';
|
import * as loop from 'dawnline.loop';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
import * as lookup from 'dawnline.lookup';
|
import * as lookup from 'dawnline.lookup';
|
||||||
|
import * as health from 'dawnline.health';
|
||||||
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
import { wrap, str, clamp_days } from 'dawnline.rpc.common';
|
||||||
|
|
||||||
|
/** The router's public IPv4 (null when none or private). */
|
||||||
|
function wan_public(m) {
|
||||||
|
let w = lookup.router_wan(m);
|
||||||
|
return w && health.wan_kind(w) == 'public' ? w : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The router's own public addresses: a device at home that reaches the server through the WAN address (NAT loopback) is not "outside". */
|
||||||
|
function own_addresses(m) {
|
||||||
|
let own = {};
|
||||||
|
for (let id, srv in m.servers) {
|
||||||
|
let a = net.wan_address(srv) ?? lookup.wan_ipv4(srv.wan_zone);
|
||||||
|
if (a)
|
||||||
|
own[a] = true;
|
||||||
|
}
|
||||||
|
let wan = lookup.wan_ipv4('wan');
|
||||||
|
if (wan)
|
||||||
|
own[wan] = true;
|
||||||
|
return own;
|
||||||
|
}
|
||||||
|
|
||||||
/** Router location plus one point per (device, recent client address). */
|
/** Router location plus one point per (device, recent client address). */
|
||||||
function geo_view(m, usage, dmp) {
|
function geo_view(m, usage, dmp) {
|
||||||
if (!m.settings.geo_enabled)
|
if (!m.settings.geo_enabled)
|
||||||
@@ -84,8 +105,17 @@ function server_view(m, srv, usage, dmp, rates, days) {
|
|||||||
online++;
|
online++;
|
||||||
}
|
}
|
||||||
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
let st = srv.private_key ? awg.server_state(srv) : { up: false, uptime: 0 };
|
||||||
|
// The newest handshake from a public address that is not the router's own:
|
||||||
|
// proof that the port is reachable from the internet.
|
||||||
|
let own = own_addresses(m);
|
||||||
|
let reached = 0;
|
||||||
|
for (let id, d in m.devices)
|
||||||
|
if (m.people[d.person]?.server == srv.id)
|
||||||
|
for (let ip, ts in usage.devices?.[id]?.ips ?? {})
|
||||||
|
if (geo.is_public(ip) && !own[ip] && ts > reached)
|
||||||
|
reached = ts;
|
||||||
return {
|
return {
|
||||||
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet,
|
id: srv.id, name: srv.name, ifname: srv.ifname, port: srv.port, subnet: srv.subnet, reached,
|
||||||
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
|
endpoint: core.endpoint_host(m, srv), public_key: srv.public_key, enabled: srv.enabled,
|
||||||
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
|
lan_like: srv.lan_like, device_mesh: srv.device_mesh, mesh: srv.mesh, preset: srv.preset, mtu: srv.mtu, keepalive: srv.keepalive, dns: srv.dns,
|
||||||
// What devices get now, by kind (mtu 0 = automatic).
|
// What devices get now, by kind (mtu 0 = automatic).
|
||||||
@@ -169,9 +199,12 @@ function status(a) {
|
|||||||
like_home: loop.status(),
|
like_home: loop.status(),
|
||||||
awg: awg.caps(),
|
awg: awg.caps(),
|
||||||
awg_state: awg.state(),
|
awg_state: awg.state(),
|
||||||
|
// The router's public IPv4 (null when none or private): a server whose public address is an old one is told so.
|
||||||
|
wan: wan_public(m),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
|
/** The newest `limit` events; `person` keeps one person's only, `since` only those after a time. */
|
||||||
function events_list(a) {
|
function events_list(a) {
|
||||||
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
|
// Tunnel down/up events of older versions: the service log tells it better (names, reasons).
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
// config_get_bool does, so the service and the code never disagree.
|
// config_get_bool does, so the service and the code never disagree.
|
||||||
|
|
||||||
import { stat } from 'fs';
|
import { stat } from 'fs';
|
||||||
import { ip2int, valid_host } from 'dawnline.util';
|
import { ip2int, valid_host, ulength } from 'dawnline.util';
|
||||||
import { INTERVALS, TARGETS } from 'dawnline.updates';
|
import { INTERVALS, TARGETS } from 'dawnline.updates';
|
||||||
|
|
||||||
/* ---------- addresses ---------- */
|
/* ---------- addresses ---------- */
|
||||||
@@ -107,17 +107,16 @@ export function to_int(v, dflt, lo, hi) {
|
|||||||
/* ---------- the settings section ---------- */
|
/* ---------- the settings section ---------- */
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | text | targets
|
* type: bool | int | enum | host | hosts | url | file | domain | ipv4 | time | targets
|
||||||
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
|
* dflt: the parsed default; restart: the portal (uhttpd) must restart when it changes;
|
||||||
* min/max: ints and text length; values: enums; msg: the error for a bad value.
|
* min/max: ints; values: enums; msg: the error for a bad value.
|
||||||
*/
|
*/
|
||||||
export const SETTINGS = {
|
export const SETTINGS = {
|
||||||
portal_enabled: { type: 'bool', dflt: false, restart: true },
|
portal_enabled: { type: 'bool', dflt: false, restart: true },
|
||||||
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
|
portal_host: { type: 'host', dflt: '', restart: true, msg: 'Public address must be a hostname or IP address.' },
|
||||||
portal_alt: { type: 'hosts', dflt: [], restart: true },
|
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,
|
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).' },
|
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_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
|
||||||
portal_cert: { type: 'file', dflt: '', restart: true },
|
portal_cert: { type: 'file', dflt: '', restart: true },
|
||||||
portal_key: { type: 'file', dflt: '', restart: true },
|
portal_key: { type: 'file', dflt: '', restart: true },
|
||||||
@@ -165,9 +164,13 @@ export function validate(key, val) {
|
|||||||
let t = spec.type;
|
let t = spec.type;
|
||||||
if (t == 'hosts') {
|
if (t == 'hosts') {
|
||||||
let lst = [];
|
let lst = [];
|
||||||
for (let x in (type(val) == 'array' ? val : []))
|
for (let x in (type(val) == 'array' ? val : [])) {
|
||||||
if (type(x) == 'string' && valid_host(trim(x)) && index(lst, trim(x)) < 0)
|
// A typo must not vanish on Save: refused, like the main address.
|
||||||
|
if (type(x) != 'string' || (trim(x) != '' && !valid_host(trim(x))))
|
||||||
|
bad(spec, key);
|
||||||
|
if (trim(x) != '' && index(lst, trim(x)) < 0)
|
||||||
push(lst, trim(x));
|
push(lst, trim(x));
|
||||||
|
}
|
||||||
return length(lst) ? lst : null;
|
return length(lst) ? lst : null;
|
||||||
}
|
}
|
||||||
if (t == 'targets') {
|
if (t == 'targets') {
|
||||||
@@ -222,10 +225,6 @@ export function validate(key, val) {
|
|||||||
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
|
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
|
||||||
bad(spec, key);
|
bad(spec, key);
|
||||||
}
|
}
|
||||||
else if (t == 'text') {
|
|
||||||
if (length(val) > spec.max || match(val, /[[:cntrl:]]/))
|
|
||||||
bad(spec, key);
|
|
||||||
}
|
|
||||||
return val;
|
return val;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
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.7.0';
|
export const VERSION = '0.10.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';
|
||||||
@@ -455,38 +455,151 @@ 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';
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A server's name as a tunnel name ("Outline Home" → "Outline-Home"): the
|
||||||
|
* AmneziaWG and WireGuard apps name the tunnel after the file, and Android and
|
||||||
|
* wg-quick refuse anything but [a-zA-Z0-9_=+.-] up to 15 characters; Windows
|
||||||
|
* refuses its device names (CON, NUL, COM1…). "dawnline" when nothing is left.
|
||||||
|
*/
|
||||||
|
export function tunnel_name(s) {
|
||||||
|
let l = replace(translit(`${s ?? ''}`), /[^A-Za-z0-9]+/g, '-');
|
||||||
|
l = replace(substr(replace(l, /^-+|-+$/g, ''), 0, 15), /-+$/g, '');
|
||||||
|
return l && !match(l, /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i) ? l : 'dawnline';
|
||||||
|
};
|
||||||
|
|
||||||
/* ---------- time ---------- */
|
/* ---------- time ---------- */
|
||||||
|
|
||||||
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
/** "YYYY-MM-DD" → epoch of the end of that local day (23:59:59). */
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ export function spark(rec, n) {
|
|||||||
return out;
|
return out;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Daily totals (rx+tx) from the 1st of this month to today, oldest first (the portal's month chart). */
|
||||||
|
export function month_days(rec) {
|
||||||
|
return spark(rec, +substr(day_key_ago(0), 8, 2));
|
||||||
|
};
|
||||||
|
|
||||||
/** The device holds an older configuration than the one it would get now. */
|
/** The device holds an older configuration than the one it would get now. */
|
||||||
function config_stale(m, d) {
|
function config_stale(m, d) {
|
||||||
m._issued ??= awg.issued();
|
m._issued ??= awg.issued();
|
||||||
@@ -23,12 +28,43 @@ function config_stale(m, d) {
|
|||||||
return was != null && was != awg.config_fingerprint(m, d);
|
return was != null && was != awg.config_fingerprint(m, d);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The device a page request came from (`devs`: one person's device views):
|
||||||
|
* through the tunnel, by its tunnel address; outside it, the one online device
|
||||||
|
* whose tunnel comes from the request's address. The apps route the VPN's own
|
||||||
|
* address around their tunnel, and the portal shares it, so a device on the VPN
|
||||||
|
* opens the page from where its tunnel comes from. Two such devices behind one
|
||||||
|
* address (one NAT): neither.
|
||||||
|
*/
|
||||||
|
export function device_here(devs, peer) {
|
||||||
|
peer = replace(peer ?? '', /^::ffff:/, '');
|
||||||
|
if (!peer)
|
||||||
|
return null;
|
||||||
|
let near = [];
|
||||||
|
for (let d in devs) {
|
||||||
|
if (d.address == peer)
|
||||||
|
return d.id;
|
||||||
|
if (d.online && d.endpoint == peer)
|
||||||
|
push(near, d.id);
|
||||||
|
}
|
||||||
|
return length(near) == 1 ? near[0] : null;
|
||||||
|
};
|
||||||
|
|
||||||
export function device_view(m, d, usage, dmp) {
|
export function device_view(m, d, usage, dmp) {
|
||||||
let u = usage.devices?.[d.id];
|
let u = usage.devices?.[d.id];
|
||||||
let peer = dmp.peers[d.public_key];
|
let peer = dmp.peers[d.public_key];
|
||||||
let ts = time();
|
let ts = time();
|
||||||
let hs = peer?.handshake || u?.handshake || 0;
|
// Set up again (Reconnect): a handshake from before it does not count.
|
||||||
|
m._reconnect ??= awg.reconnects();
|
||||||
|
let hs = awg.handshake_since(peer?.handshake || u?.handshake || 0, m._reconnect[d.id]);
|
||||||
let p = m.people[d.person];
|
let p = m.people[d.person];
|
||||||
|
// The same label /tmp/hosts carries (core.device_labels), so what is shown resolves.
|
||||||
|
let label = '';
|
||||||
|
if (m.settings.hostnames && p) {
|
||||||
|
m._labels ??= {};
|
||||||
|
m._labels[p.id] ??= core.device_labels(m, p);
|
||||||
|
label = m._labels[p.id][d.id] ?? 'device';
|
||||||
|
}
|
||||||
let v = {
|
let v = {
|
||||||
id: d.id,
|
id: d.id,
|
||||||
name: d.name,
|
name: d.name,
|
||||||
@@ -37,14 +73,14 @@ export function device_view(m, d, usage, dmp) {
|
|||||||
disabled: d.disabled,
|
disabled: d.disabled,
|
||||||
created: d.created,
|
created: d.created,
|
||||||
created_by: d.created_by,
|
created_by: d.created_by,
|
||||||
online: live.online(dmp, d.id, peer),
|
online: hs > 0 && live.online(dmp, d.id, peer),
|
||||||
handshake: hs,
|
handshake: hs,
|
||||||
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
endpoint: live.endpoint_ip(peer?.endpoint) || u?.endpoint || '',
|
||||||
active: !!peer,
|
active: !!peer,
|
||||||
month: live.month(u),
|
month: live.month(u),
|
||||||
total: u?.total ?? [ 0, 0 ],
|
total: u?.total ?? [ 0, 0 ],
|
||||||
spark: spark(u, 7),
|
spark: spark(u, 7),
|
||||||
hostname: m.settings.hostnames && p ? `${replace(replace(lc(d.name), /[^a-z0-9]+/g, '-'), /^-+|-+$/g, '') || 'device'}.${p.id}.${m.settings.domain}` : '',
|
hostname: label ? `${label}.${p.id}.${m.settings.domain}` : '',
|
||||||
browser_key: d.private_key == '',
|
browser_key: d.private_key == '',
|
||||||
// Its configuration changed since it was last shown or downloaded.
|
// Its configuration changed since it was last shown or downloaded.
|
||||||
config_stale: config_stale(m, d),
|
config_stale: config_stale(m, d),
|
||||||
|
|||||||
@@ -10,11 +10,13 @@
|
|||||||
//
|
//
|
||||||
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
|
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
|
||||||
// [--mask real=shown ...] [--name real=shown ...]
|
// [--mask real=shown ...] [--name real=shown ...]
|
||||||
// [--only overview,people]
|
// [--only overview,people] [--demo]
|
||||||
//
|
//
|
||||||
// --mask replaces text on every page before the capture (a domain, a name);
|
// --mask replaces text on every page before the capture (a domain, a name);
|
||||||
// --name does the same for a person's name in any case, and for their initials.
|
// --name does the same for a person's name in any case, and for their initials.
|
||||||
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
|
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
|
||||||
|
// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
|
||||||
|
// the router's answers are rewritten in the headless browser on their way to the page.
|
||||||
|
|
||||||
import { execFileSync, spawn } from 'node:child_process';
|
import { execFileSync, spawn } from 'node:child_process';
|
||||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
@@ -22,12 +24,20 @@ import { tmpdir } from 'node:os';
|
|||||||
import { dirname, join, resolve } from 'node:path';
|
import { dirname, join, resolve } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { createInterface } from 'node:readline';
|
import { createInterface } from 'node:readline';
|
||||||
|
import { demoRpc } from './screenshot-demo.mjs';
|
||||||
|
|
||||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
|
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
|
||||||
const SCALE = 2;
|
const SCALE = 2;
|
||||||
|
|
||||||
const args = { router: 'https://outline.lan', person: '', mask: [], names: [], only: [] };
|
const args = {
|
||||||
|
router: 'https://outline.lan',
|
||||||
|
person: '',
|
||||||
|
mask: [],
|
||||||
|
names: [],
|
||||||
|
only: [],
|
||||||
|
demo: false,
|
||||||
|
};
|
||||||
for (let i = 2; i < process.argv.length; i++) {
|
for (let i = 2; i < process.argv.length; i++) {
|
||||||
const a = process.argv[i];
|
const a = process.argv[i];
|
||||||
const v = () => process.argv[++i] ?? die(`${a} needs a value`);
|
const v = () => process.argv[++i] ?? die(`${a} needs a value`);
|
||||||
@@ -36,6 +46,7 @@ for (let i = 2; i < process.argv.length; i++) {
|
|||||||
else if (a === '--mask') args.mask.push(v().split('=', 2));
|
else if (a === '--mask') args.mask.push(v().split('=', 2));
|
||||||
else if (a === '--name') args.names.push(v().split('=', 2));
|
else if (a === '--name') args.names.push(v().split('=', 2));
|
||||||
else if (a === '--only') args.only = v().split(',');
|
else if (a === '--only') args.only = v().split(',');
|
||||||
|
else if (a === '--demo') args.demo = true;
|
||||||
else die(`unknown argument ${a}`);
|
else die(`unknown argument ${a}`);
|
||||||
}
|
}
|
||||||
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
|
if ([...args.mask, ...args.names].some((m) => m.length !== 2 || !m[0])) die('--mask and --name take real=shown');
|
||||||
@@ -100,31 +111,26 @@ const SHOTS = [
|
|||||||
url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`,
|
url: (s) => `${LUCI}/person?id=${encodeURIComponent(s.person)}`,
|
||||||
width: 1400,
|
width: 1400,
|
||||||
ready: '.dl-grid-person .dl-row',
|
ready: '.dl-grid-person .dl-row',
|
||||||
// Down to the end of Access & limits; activity rows that would be cut are hidden.
|
// Where they connected from, on the map.
|
||||||
|
prep: `(() => {
|
||||||
|
const b = [...document.querySelectorAll('.dl-grid-person button')].find((x) => x.textContent.trim() === 'Show map');
|
||||||
|
b?.click();
|
||||||
|
})()`,
|
||||||
|
settle: 6000,
|
||||||
|
// Down to the end of Access & limits or of the map, whichever is lower; activity rows that would be cut are hidden.
|
||||||
clip: `(() => {
|
clip: `(() => {
|
||||||
const c = ${column}, cut = document.querySelector('.dl-grid-person > .dl-col:last-child').getBoundingClientRect().bottom + 40;
|
const c = ${column}, cols = document.querySelectorAll('.dl-grid-person > .dl-col');
|
||||||
|
const places = cols[0].children[2];
|
||||||
|
const cut = Math.max(cols[1].getBoundingClientRect().bottom, places ? places.getBoundingClientRect().bottom : 0) + 40;
|
||||||
document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => {
|
document.querySelectorAll('.dl-grid-person .dl-row').forEach((r) => {
|
||||||
if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden';
|
if (r.getBoundingClientRect().bottom > cut - 8) r.style.visibility = 'hidden';
|
||||||
});
|
});
|
||||||
|
// Activity that would start right at the cut goes too, its heading with it.
|
||||||
|
const act = cols[0].children[3];
|
||||||
|
if (act && act.getBoundingClientRect().top > cut - 120) act.style.visibility = 'hidden';
|
||||||
return { x: c.x, y: 0, width: c.w, height: cut };
|
return { x: c.x, y: 0, width: c.w, height: cut };
|
||||||
})()`,
|
})()`,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
name: 'access',
|
|
||||||
url: () => `${LUCI}/server?section=access`,
|
|
||||||
width: 1400,
|
|
||||||
ready: 'section.dl-ifcard details',
|
|
||||||
// The home network card alone, its folded lists closed.
|
|
||||||
prep: `(() => {
|
|
||||||
const card = [...document.querySelectorAll('section.dl-ifcard')].find((s) => s.querySelector('details'));
|
|
||||||
card.querySelectorAll('details[open]').forEach((d) => (d.open = false));
|
|
||||||
card.setAttribute('data-shot', '');
|
|
||||||
})()`,
|
|
||||||
clip: `(() => {
|
|
||||||
const r = document.querySelector('[data-shot]').getBoundingClientRect();
|
|
||||||
return { x: r.left - 12, y: r.top - 12, width: r.width + 24, height: r.height + 24 };
|
|
||||||
})()`,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: 'portal',
|
name: 'portal',
|
||||||
url: (s) => s.portal,
|
url: (s) => s.portal,
|
||||||
@@ -156,7 +162,17 @@ const MASK = `((pairs, inits) => {
|
|||||||
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
|
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
|
||||||
return doc.get(m);
|
return doc.get(m);
|
||||||
};
|
};
|
||||||
const swap = (s) => pairs.reduce((t, [a, b]) => t.split(a).join(b), s).replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip);
|
// IPv6 too, unless link-local or private (fe80::, fc00::/7).
|
||||||
|
const ip6 = (m) => {
|
||||||
|
if (/^(fe8|fe9|fea|feb|fc|fd)/i.test(m)) return m;
|
||||||
|
if (!doc.has(m)) doc.set(m, '2001:db8::' + (24 + doc.size));
|
||||||
|
return doc.get(m);
|
||||||
|
};
|
||||||
|
const swap = (s) =>
|
||||||
|
pairs
|
||||||
|
.reduce((t, [a, b]) => t.split(a).join(b), s)
|
||||||
|
.replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip)
|
||||||
|
.replace(/\\b(?:[0-9a-f]{1,4}:){3,7}[0-9a-f]{1,4}\\b/gi, ip6);
|
||||||
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
const w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||||
for (let n; (n = w.nextNode()); ) {
|
for (let n; (n = w.nextNode()); ) {
|
||||||
const ini = inits.find(([a]) => n.nodeValue.trim() === a);
|
const ini = inits.find(([a]) => n.nodeValue.trim() === a);
|
||||||
@@ -203,6 +219,7 @@ async function connect(wsUrl) {
|
|||||||
let id = 0;
|
let id = 0;
|
||||||
const pending = new Map();
|
const pending = new Map();
|
||||||
const waiters = [];
|
const waiters = [];
|
||||||
|
const listeners = [];
|
||||||
ws.onmessage = (m) => {
|
ws.onmessage = (m) => {
|
||||||
const msg = JSON.parse(m.data);
|
const msg = JSON.parse(m.data);
|
||||||
if (msg.id && pending.has(msg.id)) {
|
if (msg.id && pending.has(msg.id)) {
|
||||||
@@ -210,6 +227,7 @@ async function connect(wsUrl) {
|
|||||||
pending.delete(msg.id);
|
pending.delete(msg.id);
|
||||||
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
|
||||||
} else if (msg.method) {
|
} else if (msg.method) {
|
||||||
|
for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
|
||||||
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
for (const w of waiters.filter((x) => x.method === msg.method)) {
|
||||||
waiters.splice(waiters.indexOf(w), 1);
|
waiters.splice(waiters.indexOf(w), 1);
|
||||||
w.ok(msg.params);
|
w.ok(msg.params);
|
||||||
@@ -222,7 +240,8 @@ async function connect(wsUrl) {
|
|||||||
ws.send(JSON.stringify({ id, method, params }));
|
ws.send(JSON.stringify({ id, method, params }));
|
||||||
});
|
});
|
||||||
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
const waitFor = (method) => new Promise((ok) => waiters.push({ method, ok }));
|
||||||
return { send, waitFor, close: () => ws.close() };
|
const on = (method, fn) => listeners.push({ method, fn });
|
||||||
|
return { send, waitFor, on, close: () => ws.close() };
|
||||||
}
|
}
|
||||||
|
|
||||||
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
|
||||||
@@ -255,10 +274,40 @@ async function main() {
|
|||||||
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||||
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
|
||||||
await page.send('Page.enable');
|
await page.send('Page.enable');
|
||||||
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
|
await page.send('Emulation.setEmulatedMedia', {
|
||||||
|
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
|
||||||
|
});
|
||||||
|
// The person shown on the Person page; known once People has loaded (or from --person).
|
||||||
|
const s = { person: args.person, portal: '' };
|
||||||
|
if (args.demo) {
|
||||||
|
page.on('Fetch.requestPaused', async (e) => {
|
||||||
|
try {
|
||||||
|
const r = await page.send('Fetch.getResponseBody', {
|
||||||
|
requestId: e.requestId,
|
||||||
|
});
|
||||||
|
const body = r.base64Encoded ? Buffer.from(r.body, 'base64').toString('utf8') : r.body;
|
||||||
|
const out = demoRpc(e.request.postData ?? '', body, s.person);
|
||||||
|
await page.send('Fetch.fulfillRequest', {
|
||||||
|
requestId: e.requestId,
|
||||||
|
responseCode: e.responseStatusCode ?? 200,
|
||||||
|
responseHeaders: e.responseHeaders ?? [],
|
||||||
|
body: Buffer.from(out, 'utf8').toString('base64'),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
await page.send('Fetch.continueRequest', { requestId: e.requestId }).catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await page.send('Fetch.enable', {
|
||||||
|
patterns: [{ urlPattern: '*ubus*', requestStage: 'Response' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const evaluate = async (expression) => {
|
const evaluate = async (expression) => {
|
||||||
const r = await page.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
const r = await page.send('Runtime.evaluate', {
|
||||||
|
expression,
|
||||||
|
awaitPromise: true,
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description ?? r.exceptionDetails.text);
|
||||||
return r.result.value;
|
return r.result.value;
|
||||||
};
|
};
|
||||||
@@ -276,7 +325,12 @@ async function main() {
|
|||||||
};
|
};
|
||||||
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
|
// A tall window: Outline scrolls #maincontent, not the page, so it must hold everything.
|
||||||
const viewport = (width, height = 2600) =>
|
const viewport = (width, height = 2600) =>
|
||||||
page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: SCALE, mobile: false });
|
page.send('Emulation.setDeviceMetricsOverride', {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
deviceScaleFactor: SCALE,
|
||||||
|
mobile: false,
|
||||||
|
});
|
||||||
|
|
||||||
await viewport(1400);
|
await viewport(1400);
|
||||||
await go(`${args.router}/cgi-bin/luci/`);
|
await go(`${args.router}/cgi-bin/luci/`);
|
||||||
@@ -297,13 +351,10 @@ async function main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The person to show (the first one on People unless --person) and their personal link.
|
// The person to show (the first one on People unless --person) and their personal link.
|
||||||
const s = { person: args.person, portal: '' };
|
|
||||||
await go(`${LUCI}/server?section=people`);
|
await go(`${LUCI}/server?section=people`);
|
||||||
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
|
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
|
||||||
if (!s.person)
|
if (!s.person)
|
||||||
s.person = await evaluate(
|
s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
|
||||||
`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`,
|
|
||||||
);
|
|
||||||
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
|
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
|
||||||
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
|
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
|
||||||
.then((r) => r.link ?? r.links?.[0] ?? '')`);
|
.then((r) => r.link ?? r.links?.[0] ?? '')`);
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Put the README screenshots into a browser window on a dawn gradient.
|
"""Frame the README screenshots the way the portal draws its own surfaces.
|
||||||
|
|
||||||
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
|
Raw captures live in docs/screenshots/raw/<name>.png at SCALE device pixels
|
||||||
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
|
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
|
||||||
are written to docs/screenshots/<name>.png at the same scale. Needs a
|
are written to docs/screenshots/<name>.png at the same scale. Each page sits on
|
||||||
|
a panel like the portal's sheets (#121212, radius 36, 16px around it, the page
|
||||||
|
inside at radius 20) on the portal's own black. A shot in FLOWS gets its steps
|
||||||
|
in a row in front of the page's lower edge, numbered: sheets captured alone on
|
||||||
|
a transparent page (raw/<step>.png, FLOW_MARGIN around each). Needs a
|
||||||
Chromium-based browser for the headless render (BROWSER=/path/to/chrome,
|
Chromium-based browser for the headless render (BROWSER=/path/to/chrome,
|
||||||
default: Brave or Chrome on macOS).
|
default: Brave or Chrome on macOS).
|
||||||
Run: scripts/frame-screenshots.py
|
Run: scripts/frame-screenshots.py [name ...] (all of them when no name is given)
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
@@ -18,16 +22,18 @@ import tempfile
|
|||||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
||||||
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
|
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
|
||||||
OUT = os.path.join(ROOT, 'docs', 'screenshots')
|
OUT = os.path.join(ROOT, 'docs', 'screenshots')
|
||||||
|
FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
|
||||||
|
'geist-latin-wght-normal.woff2')
|
||||||
|
|
||||||
# name -> what the address bar shows
|
SHOTS = ['overview', 'people', 'person', 'portal']
|
||||||
SHOTS = {
|
# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
|
||||||
'overview': 'router.lan · Dawnline',
|
# adding a device there would add one.
|
||||||
'people': 'router.lan · Dawnline · People',
|
FLOWS = {
|
||||||
'person': 'router.lan · Dawnline · Myata',
|
'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
|
||||||
'portal': 'vpn.example.com/kamiro-telosu-bavine',
|
|
||||||
'access': 'router.lan · Dawnline · Home · Access',
|
|
||||||
}
|
}
|
||||||
PAD_X, PAD_Y, BAR = 120, 96, 40
|
PAD_X, PAD_Y, INSET = 96, 80, 16 # canvas around the panel; panel around the page
|
||||||
|
FLOW_MARGIN = (56, 40, 56, 72) # around a step's sheet in its capture: left, top, right, bottom
|
||||||
|
STEP_GAP, STEP_OVER, STEP_PAD = 28, 150, 120 # between steps; how far they reach over the page; canvas beside them
|
||||||
SCALE = 2
|
SCALE = 2
|
||||||
|
|
||||||
CANDIDATES = [
|
CANDIDATES = [
|
||||||
@@ -39,26 +45,18 @@ CANDIDATES = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
|
TEMPLATE = """<!doctype html><html><head><meta charset="utf-8"><style>
|
||||||
|
@font-face{{font-family:Geist;src:url('file://{font}') format('woff2');font-weight:100 900}}
|
||||||
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
|
html,body{{margin:0;width:{w}px;height:{h}px;overflow:hidden}}
|
||||||
body{{display:flex;align-items:center;justify-content:center;
|
body{{position:relative;background:#080808}}
|
||||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
|
.panel{{position:absolute;left:{px}px;top:{py}px;width:{pw}px;height:{ph}px;
|
||||||
background:
|
border-radius:36px;background:#121212;box-shadow:inset 0 0 0 1px rgba(255,255,255,.05),0 30px 80px rgba(0,0,0,.5)}}
|
||||||
radial-gradient({gw}px {gh}px at 50% 118%, rgba(255,140,70,.55), rgba(255,140,70,0) 70%),
|
.page{{position:absolute;left:{x}px;top:{y}px;width:{iw}px;height:{ih}px;display:block;border-radius:20px;
|
||||||
radial-gradient({gw2}px {gh2}px at 50% 100%, rgba(250,90,120,.30), rgba(250,90,120,0) 70%),
|
box-shadow:0 0 0 1px rgba(255,255,255,.04)}}
|
||||||
linear-gradient(180deg,#070a14 0%,#0c1226 55%,#1a1430 100%)}}
|
.sheet{{position:absolute;display:block;filter:drop-shadow(0 24px 48px rgba(0,0,0,.6))}}
|
||||||
.win{{width:{iw}px;border-radius:14px;overflow:hidden;background:#000;
|
.n{{position:absolute;width:34px;height:34px;border-radius:50%;display:grid;place-items:center;
|
||||||
box-shadow:0 0 0 1px rgba(255,255,255,.08),0 40px 120px rgba(0,0,0,.65),0 10px 30px rgba(0,0,0,.4)}}
|
font:600 16px Geist,sans-serif;color:#ededed;background:#232323;
|
||||||
.bar{{height:{bar}px;background:#15171c;display:flex;align-items:center;gap:8px;padding:0 16px;
|
box-shadow:0 0 0 1px rgba(255,255,255,.12),0 6px 16px rgba(0,0,0,.5)}}
|
||||||
border-bottom:1px solid rgba(255,255,255,.06);position:relative}}
|
</style></head><body><div class="panel"></div><img class="page" src="file://{src}">{steps}</body></html>"""
|
||||||
.dot{{width:12px;height:12px;border-radius:50%}}
|
|
||||||
.url{{position:absolute;left:50%;transform:translateX(-50%);height:24px;padding:0 14px;border-radius:7px;
|
|
||||||
background:#0d0f13;color:#8b8f98;font-size:13px;display:flex;align-items:center;gap:6px;white-space:nowrap}}
|
|
||||||
.url svg{{width:11px;height:11px;fill:none;stroke:#8b8f98;stroke-width:2}}
|
|
||||||
img{{display:block;width:{iw}px;height:{ih}px}}
|
|
||||||
</style></head><body><div class="win"><div class="bar">
|
|
||||||
<span class="dot" style="background:#ff5f57"></span><span class="dot" style="background:#febc2e"></span><span class="dot" style="background:#28c840"></span>
|
|
||||||
<span class="url"><svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>{url}</span>
|
|
||||||
</div><img src="file://{src}"></div></body></html>"""
|
|
||||||
|
|
||||||
|
|
||||||
def png_size(path):
|
def png_size(path):
|
||||||
@@ -67,22 +65,53 @@ def png_size(path):
|
|||||||
return struct.unpack('>II', head[16:24])
|
return struct.unpack('>II', head[16:24])
|
||||||
|
|
||||||
|
|
||||||
|
def layout(iw, ih, flow):
|
||||||
|
"""Where the page goes and its steps in a row in front of its lower edge: (width, height, page x, page y, steps)."""
|
||||||
|
w, h = iw + 2 * (INSET + PAD_X), ih + 2 * (INSET + PAD_Y)
|
||||||
|
x, y = PAD_X + INSET, PAD_Y + INSET
|
||||||
|
if not flow:
|
||||||
|
return w, h, x, y, ''
|
||||||
|
ml, mt, mr, mb = FLOW_MARGIN
|
||||||
|
sizes = [tuple(v // SCALE for v in png_size(src)) for src in flow]
|
||||||
|
row = sum(pw - ml - mr for pw, _ in sizes) + STEP_GAP * (len(sizes) - 1)
|
||||||
|
w = max(w, row + 2 * STEP_PAD)
|
||||||
|
x = (w - iw) // 2
|
||||||
|
top = y + ih - STEP_OVER
|
||||||
|
h = top + max(ph - mt - mb for _, ph in sizes) + PAD_Y
|
||||||
|
out, sx = [], (w - row) // 2
|
||||||
|
for i, (src, (pw, ph)) in enumerate(zip(flow, sizes)):
|
||||||
|
out.append(f'<img class="sheet" src="file://{src}" style="left:{sx - ml}px;top:{top - mt}px;width:{pw}px;height:{ph}px">')
|
||||||
|
out.append(f'<span class="n" style="left:{sx - 14}px;top:{top - 14}px">{i + 1}</span>')
|
||||||
|
sx += pw - ml - mr + STEP_GAP
|
||||||
|
return w, h, x, y, ''.join(out)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None)
|
browser = next((b for b in CANDIDATES if b and os.path.exists(b)), None)
|
||||||
if not browser:
|
if not browser:
|
||||||
sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome')
|
sys.exit('No Chromium-based browser found; set BROWSER=/path/to/chrome')
|
||||||
|
only = sys.argv[1:]
|
||||||
|
unknown = [n for n in only if n not in SHOTS]
|
||||||
|
if unknown:
|
||||||
|
sys.exit(f'unknown screenshot {", ".join(unknown)} (one of {", ".join(SHOTS)})')
|
||||||
tmp = tempfile.mkdtemp()
|
tmp = tempfile.mkdtemp()
|
||||||
for name, url in SHOTS.items():
|
for name in SHOTS:
|
||||||
|
if only and name not in only:
|
||||||
|
continue
|
||||||
src = os.path.join(RAW, f'{name}.png')
|
src = os.path.join(RAW, f'{name}.png')
|
||||||
if not os.path.exists(src):
|
if not os.path.exists(src):
|
||||||
print(f'skip {name}: no raw capture')
|
print(f'skip {name}: no raw capture')
|
||||||
continue
|
continue
|
||||||
iw, ih = (v // SCALE for v in png_size(src))
|
iw, ih = (v // SCALE for v in png_size(src))
|
||||||
w, h = iw + 2 * PAD_X, ih + BAR + 2 * PAD_Y
|
flow = [os.path.join(RAW, f'{step}.png') for step in FLOWS.get(name, [])]
|
||||||
|
if not all(os.path.exists(p) for p in flow):
|
||||||
|
print(f'{name}: a step is missing, the page alone')
|
||||||
|
flow = []
|
||||||
|
w, h, x, y, steps = layout(iw, ih, flow)
|
||||||
html = os.path.join(tmp, f'{name}.html')
|
html = os.path.join(tmp, f'{name}.html')
|
||||||
with open(html, 'w', encoding='utf-8') as f:
|
with open(html, 'w', encoding='utf-8') as f:
|
||||||
f.write(TEMPLATE.format(w=w, h=h, iw=iw, ih=ih, bar=BAR, url=url, src=src,
|
f.write(TEMPLATE.format(w=w, h=h, x=x, y=y, iw=iw, ih=ih, px=x - INSET, py=y - INSET, pw=iw + 2 * INSET,
|
||||||
gw=int(w * .8), gh=int(h * .5), gw2=int(w * .6), gh2=int(h * .45)))
|
ph=ih + 2 * INSET, src=src, font=FONT, steps=steps))
|
||||||
out = os.path.join(OUT, f'{name}.png')
|
out = os.path.join(OUT, f'{name}.png')
|
||||||
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
|
subprocess.run([browser, '--headless=new', '--disable-gpu', '--hide-scrollbars', '--allow-file-access-from-files',
|
||||||
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
|
f'--force-device-scale-factor={SCALE}', f'--window-size={w},{h}', f'--screenshot={out}', f'file://{html}'],
|
||||||
|
|||||||
@@ -0,0 +1,397 @@
|
|||||||
|
// Demo data for the README screenshots (scripts/capture-screenshots.mjs --demo):
|
||||||
|
// the router's own answers (luci.dawnline status, events) with a made-up cast in
|
||||||
|
// place of its people, devices, places and activity, in the states the
|
||||||
|
// screenshots should show (online, ending soon, over the limit, paused, ended,
|
||||||
|
// outside their hours). The router's ids stay, so every page keeps working; it
|
||||||
|
// is only ever read.
|
||||||
|
|
||||||
|
// The admin counts in binary units: "100 GB" is 100 GiB.
|
||||||
|
const GB = 2 ** 30;
|
||||||
|
const MIN = 60;
|
||||||
|
const HOUR = 3600;
|
||||||
|
const DAY = 86400;
|
||||||
|
|
||||||
|
/** Where the cast connects from: [lat, lon, country, cc, network]. */
|
||||||
|
const CITIES = {
|
||||||
|
Lisbon: [38.7223, -9.1393, 'Portugal', 'PT', 'MEO'],
|
||||||
|
Porto: [41.1579, -8.6291, 'Portugal', 'PT', 'NOS'],
|
||||||
|
Sintra: [38.8029, -9.3817, 'Portugal', 'PT', 'Vodafone Portugal'],
|
||||||
|
Madrid: [40.4168, -3.7038, 'Spain', 'ES', 'Telefonica de Espana'],
|
||||||
|
Barcelona: [41.3874, 2.1686, 'Spain', 'ES', 'Orange Espagne'],
|
||||||
|
Berlin: [52.52, 13.405, 'Germany', 'DE', 'Deutsche Telekom'],
|
||||||
|
Milan: [45.4642, 9.19, 'Italy', 'IT', 'TIM'],
|
||||||
|
Amsterdam: [52.3676, 4.9041, 'Netherlands', 'NL', 'KPN'],
|
||||||
|
Paris: [48.8566, 2.3522, 'France', 'FR', 'Orange'],
|
||||||
|
London: [51.5072, -0.1276, 'United Kingdom', 'GB', 'BT'],
|
||||||
|
Stockholm: [59.3293, 18.0686, 'Sweden', 'SE', 'Telia'],
|
||||||
|
};
|
||||||
|
/** The router's own place. */
|
||||||
|
const HOME = 'Lisbon';
|
||||||
|
/** Shared at home (Access): what a Home-only person can be limited to. */
|
||||||
|
const SERVICES = [
|
||||||
|
{ id: 'demo-nas', name: 'NAS', address: '10.0.1.20', ports: ['445', '5000'] },
|
||||||
|
{
|
||||||
|
id: 'demo-ha',
|
||||||
|
name: 'Home Assistant',
|
||||||
|
address: '10.0.1.30',
|
||||||
|
ports: ['8123'],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
/** How busy each day of the week is, Monday first. */
|
||||||
|
const WEEK = [0.9, 1.15, 0.8, 1.05, 1.3, 0.75, 1.1];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Who the screenshots show, the --person first (the Person page), each with
|
||||||
|
* their city. A device: [name, kind, when it was last seen, GB this month,
|
||||||
|
* earlier places as 'City:days ago']; when: 'online', 'mins:N', 'hours:N',
|
||||||
|
* 'days:N', 'never', 'stale' (settings changed since), 'disabled'. Its last
|
||||||
|
* place is the person's city unless `at` names another.
|
||||||
|
*/
|
||||||
|
export const CAST = [
|
||||||
|
{
|
||||||
|
name: 'Lena Ortiz',
|
||||||
|
city: 'Lisbon',
|
||||||
|
limit: 4,
|
||||||
|
quota: 100,
|
||||||
|
used: 38.6,
|
||||||
|
note: 'Family',
|
||||||
|
devices: [
|
||||||
|
['iPhone 16', 'phone', 'online', 14.2, ['Sintra:3', 'Porto:9', 'Madrid:16']],
|
||||||
|
['MacBook Pro', 'computer', 'hours:3', 21.9, ['Berlin:12']],
|
||||||
|
['iPad Air', 'tablet', 'never', 0],
|
||||||
|
],
|
||||||
|
added: [['iPad Air', 2, 'portal']],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Marco Rossi',
|
||||||
|
city: 'Milan',
|
||||||
|
ends: 4,
|
||||||
|
devices: [
|
||||||
|
['Pixel 9', 'phone', 'online', 6.4, ['Barcelona:8']],
|
||||||
|
['ThinkPad X1', 'computer', 'days:1', 12.8],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Yuki Tanaka',
|
||||||
|
city: 'Amsterdam',
|
||||||
|
state: 'quota',
|
||||||
|
quota: 20,
|
||||||
|
used: 20.4,
|
||||||
|
devices: [
|
||||||
|
['Galaxy S24', 'phone', 'hours:6', 14.1, ['Paris:5']],
|
||||||
|
['Living room TV', 'other', 'stale', 6.3],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Sam Okafor',
|
||||||
|
city: 'London',
|
||||||
|
state: 'paused',
|
||||||
|
paused: 3,
|
||||||
|
devices: [
|
||||||
|
['Gaming PC', 'computer', 'days:9', 3.1],
|
||||||
|
['Steam Deck', 'other', 'disabled', 0],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Nora Lindqvist',
|
||||||
|
city: 'Stockholm',
|
||||||
|
state: 'expired',
|
||||||
|
ends: -3,
|
||||||
|
devices: [['iPhone 13 mini', 'phone', 'days:4', 1.2]],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Mia Ortiz',
|
||||||
|
city: 'Lisbon',
|
||||||
|
state: 'hours',
|
||||||
|
hours: '07:00-21:00',
|
||||||
|
limit: 1,
|
||||||
|
devices: [['Fire HD 10', 'tablet', 'hours:11', 2.6]],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const slug = (s) =>
|
||||||
|
s
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, '-')
|
||||||
|
.replace(/^-|-$/g, '');
|
||||||
|
const date = (t) => new Date(t * 1000).toISOString().slice(0, 10);
|
||||||
|
const seen = (when, now) => {
|
||||||
|
const [k, n] = when.split(':');
|
||||||
|
const v = +n || 0;
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
online: now - 40,
|
||||||
|
mins: now - v * MIN,
|
||||||
|
hours: now - v * HOUR,
|
||||||
|
days: now - v * DAY,
|
||||||
|
stale: now - 2 * DAY,
|
||||||
|
disabled: now - 41 * DAY,
|
||||||
|
}[k] ?? 0
|
||||||
|
);
|
||||||
|
};
|
||||||
|
/** A week of daily totals that adds up to about a quarter of the month, today last (nothing before it was first seen). */
|
||||||
|
const week = (gb, last, now) =>
|
||||||
|
[0.8, 1.3, 0.6, 1.1, 1.6, 0.9, 1].map((f, i) => (!gb || now - (6 - i) * DAY < last - DAY ? 0 : Math.round(((gb / 4) * f * GB) / 7)));
|
||||||
|
let ipN = 10;
|
||||||
|
/** A documentation address (the capture swaps public addresses for these anyway). */
|
||||||
|
const ip = () => `203.0.113.${ipN++}`;
|
||||||
|
const where = (city) => `${city} · ${CITIES[city][4]}`;
|
||||||
|
|
||||||
|
/** What the last status made of the router's ids, for the calls that come after it (events, usage). */
|
||||||
|
const demo = { events: [], people: new Map(), days: [], now: 0 };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Daily traffic over `days` (oldest first) for `gb` this month: busier some days of the week, today
|
||||||
|
* only partly gone. Each day's [rx, tx] in bytes, rx (from the devices) about an eighth.
|
||||||
|
*/
|
||||||
|
function daily(days, gb, now) {
|
||||||
|
const month = days[days.length - 1].slice(0, 7);
|
||||||
|
const w = days.map((d, i) => {
|
||||||
|
const wd = (new Date(`${d}T12:00:00Z`).getUTCDay() + 6) % 7;
|
||||||
|
const today = i === days.length - 1 ? ((now % DAY) / DAY) * 0.9 + 0.1 : 1;
|
||||||
|
return WEEK[wd] * (0.85 + ((i * 37) % 11) / 30) * today;
|
||||||
|
});
|
||||||
|
const inMonth = w.reduce((s, x, i) => s + (days[i].startsWith(month) ? x : 0), 0) || 1;
|
||||||
|
return w.map((x) => {
|
||||||
|
const b = (x / inMonth) * gb * GB;
|
||||||
|
return [Math.round(b * 0.12), Math.round(b * 0.88)];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const usage = (days, pairs) => days.map((day, i) => ({ day, rx: pairs[i][0], tx: pairs[i][1] }));
|
||||||
|
|
||||||
|
/** The places a device was at, oldest first: [city, ts, ip]. */
|
||||||
|
function trail(c, d, hs, now) {
|
||||||
|
if (!hs) return [];
|
||||||
|
const earlier = (d[4] ?? []).map((s) => {
|
||||||
|
const [city, ago] = s.split(':');
|
||||||
|
return [city, now - +ago * DAY - 5 * HOUR, ip()];
|
||||||
|
});
|
||||||
|
return [...earlier.reverse(), [c.city, hs, ip()]];
|
||||||
|
}
|
||||||
|
|
||||||
|
function demoStatus(st, first) {
|
||||||
|
const now = st.now;
|
||||||
|
ipN = 10;
|
||||||
|
const real = [...st.people].sort((a, b) => (a.id === first ? -1 : b.id === first ? 1 : a.id < b.id ? -1 : 1));
|
||||||
|
const spare = real.flatMap((p) => p.devices);
|
||||||
|
const points = [];
|
||||||
|
const events = [];
|
||||||
|
const people = CAST.map((c, i) => {
|
||||||
|
const base = real[i] ?? {
|
||||||
|
...real[real.length - 1],
|
||||||
|
id: `demo-${i}`,
|
||||||
|
devices: [],
|
||||||
|
};
|
||||||
|
const state = c.state ?? 'active';
|
||||||
|
const devices = c.devices.map((cd, j) => {
|
||||||
|
const [name, kind, when, gb] = cd;
|
||||||
|
const tpl = base.devices[j] ?? {
|
||||||
|
...spare[j % spare.length],
|
||||||
|
id: `${base.id}-demo-${j}`,
|
||||||
|
address: `10.8.0.${200 + i * 8 + j}`,
|
||||||
|
};
|
||||||
|
const hs = when === 'never' ? 0 : seen(when, now);
|
||||||
|
const online = when === 'online' && !['paused', 'expired', 'hours'].includes(state);
|
||||||
|
const places = trail(c, cd, hs, now);
|
||||||
|
places.forEach(([city, ts, addr], k) => {
|
||||||
|
const [lat, lon, country, cc, org] = CITIES[city];
|
||||||
|
const current = online && k === places.length - 1;
|
||||||
|
points.push({
|
||||||
|
person: base.id,
|
||||||
|
device: tpl.id,
|
||||||
|
ip: addr,
|
||||||
|
ts,
|
||||||
|
online: current,
|
||||||
|
lat,
|
||||||
|
lon,
|
||||||
|
city,
|
||||||
|
country,
|
||||||
|
cc,
|
||||||
|
asn: 0,
|
||||||
|
org,
|
||||||
|
});
|
||||||
|
const ev = {
|
||||||
|
person: base.id,
|
||||||
|
device: tpl.id,
|
||||||
|
pname: c.name,
|
||||||
|
dname: name,
|
||||||
|
dkind: kind,
|
||||||
|
};
|
||||||
|
// Online now: connected a while ago (the handshake renews every few minutes); otherwise on for a couple of hours.
|
||||||
|
events.push({
|
||||||
|
...ev,
|
||||||
|
type: 'connect',
|
||||||
|
detail: addr,
|
||||||
|
where: where(city),
|
||||||
|
ts: current ? now - 95 * MIN - j * 13 * MIN : ts - 2 * HOUR,
|
||||||
|
});
|
||||||
|
if (!current) events.push({ ...ev, type: 'disconnect', ts });
|
||||||
|
});
|
||||||
|
// A phone in hand switches between Wi-Fi and mobile data.
|
||||||
|
if (online && kind === 'phone') {
|
||||||
|
const [, , addr] = places[places.length - 1];
|
||||||
|
events.push({
|
||||||
|
person: base.id,
|
||||||
|
device: tpl.id,
|
||||||
|
pname: c.name,
|
||||||
|
dname: name,
|
||||||
|
dkind: kind,
|
||||||
|
type: 'roam',
|
||||||
|
detail: `${ip()} → ${addr}`,
|
||||||
|
ts: now - 25 * MIN,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...tpl,
|
||||||
|
name,
|
||||||
|
kind,
|
||||||
|
online,
|
||||||
|
active: online,
|
||||||
|
handshake: hs,
|
||||||
|
endpoint: places.length ? places[places.length - 1][2] : '',
|
||||||
|
config_stale: when === 'stale',
|
||||||
|
disabled: when === 'disabled',
|
||||||
|
month: [Math.round(gb * 0.12 * GB), Math.round(gb * 0.88 * GB)],
|
||||||
|
total: [Math.round(gb * 0.3 * GB), Math.round(gb * 2.2 * GB)],
|
||||||
|
spark: week(gb, hs, now),
|
||||||
|
hostname: hs ? `${slug(name)}.${slug(c.name.split(' ')[0])}.lan` : '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
for (const [name, ago, by] of c.added ?? []) {
|
||||||
|
const d = devices.find((x) => x.name === name);
|
||||||
|
if (d)
|
||||||
|
events.push({
|
||||||
|
person: base.id,
|
||||||
|
device: d.id,
|
||||||
|
pname: c.name,
|
||||||
|
dname: name,
|
||||||
|
dkind: d.kind,
|
||||||
|
type: 'device_added',
|
||||||
|
detail: name,
|
||||||
|
by,
|
||||||
|
ts: now - ago * DAY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (c.paused)
|
||||||
|
events.push({
|
||||||
|
person: base.id,
|
||||||
|
pname: c.name,
|
||||||
|
type: 'paused',
|
||||||
|
by: 'admin',
|
||||||
|
ts: now - c.paused * DAY,
|
||||||
|
});
|
||||||
|
const month = devices.reduce((s, d) => [s[0] + d.month[0], s[1] + d.month[1]], [0, 0]);
|
||||||
|
const live = devices.some((d) => d.online);
|
||||||
|
demo.people.set(base.id, {
|
||||||
|
devices: devices.map((d, j) => [d.id, c.devices[j][3]]),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
name: c.name,
|
||||||
|
state,
|
||||||
|
paused: state === 'paused',
|
||||||
|
hours: c.hours ?? '',
|
||||||
|
note: c.note ?? '',
|
||||||
|
expires: c.ends !== undefined ? date(now + c.ends * DAY) : '',
|
||||||
|
device_limit: c.limit ?? Math.max(3, devices.length),
|
||||||
|
quota_gb: c.quota ?? 0,
|
||||||
|
quota_period: 'month',
|
||||||
|
quota_limit: (c.quota ?? 0) * GB,
|
||||||
|
quota_used: Math.round((c.used ?? (month[0] + month[1]) / GB) * GB),
|
||||||
|
bonus_gb: 0,
|
||||||
|
month,
|
||||||
|
total: [month[0] * 3, month[1] * 3],
|
||||||
|
online: devices.filter((d) => d.online).length,
|
||||||
|
last_seen: Math.max(0, ...devices.map((d) => d.handshake)),
|
||||||
|
rate: (base.rate ?? []).map(([t], k) => [t, live ? 12000 + ((k * 7919) % 9000) : 0, live ? 120000 + ((k * 104729) % 90000) : 0]),
|
||||||
|
devices,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const devices = people.flatMap((p) => p.devices);
|
||||||
|
const month = people.reduce((s, p) => [s[0] + p.month[0], s[1] + p.month[1]], [0, 0]);
|
||||||
|
events.sort((a, b) => a.ts - b.ts);
|
||||||
|
demo.events = events;
|
||||||
|
points.sort((a, b) => b.ts - a.ts);
|
||||||
|
demo.now = now;
|
||||||
|
demo.days = (st.series ?? []).map((x) => x.day);
|
||||||
|
if (!demo.days.length) for (let k = 29; k >= 0; k--) demo.days.push(date(now - k * DAY));
|
||||||
|
const all = CAST.reduce((s, c) => s + c.devices.reduce((t, d) => t + d[3], 0), 0);
|
||||||
|
const series = usage(demo.days, daily(demo.days, all, now));
|
||||||
|
const today = series[series.length - 1];
|
||||||
|
const [lat, lon, country, cc, org] = CITIES[HOME];
|
||||||
|
return {
|
||||||
|
...st,
|
||||||
|
people,
|
||||||
|
totals: {
|
||||||
|
...st.totals,
|
||||||
|
people: people.length,
|
||||||
|
devices: devices.length,
|
||||||
|
online: devices.filter((d) => d.online).length,
|
||||||
|
active: people.filter((p) => p.state === 'active').length,
|
||||||
|
today: [today.rx, today.tx],
|
||||||
|
month,
|
||||||
|
},
|
||||||
|
series,
|
||||||
|
servers: st.servers.map((x) => ({ ...x, series })),
|
||||||
|
services: st.services?.length ? st.services : SERVICES,
|
||||||
|
geo: st.geo && {
|
||||||
|
...st.geo,
|
||||||
|
home: { lat, lon, city: HOME, country, cc, asn: 0, org },
|
||||||
|
points,
|
||||||
|
},
|
||||||
|
events: events.slice(-60),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A ubus JSON-RPC exchange (LuCI batches calls into one request) with the
|
||||||
|
* luci.dawnline answers made into the demo; anything else as it came.
|
||||||
|
*/
|
||||||
|
export function demoRpc(request, response, first) {
|
||||||
|
let req;
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
req = JSON.parse(request);
|
||||||
|
res = JSON.parse(response);
|
||||||
|
} catch {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
const calls = new Map((Array.isArray(req) ? req : [req]).map((c) => [c.id, c.params ?? []]));
|
||||||
|
const fix = (r) => {
|
||||||
|
const [, object, method, args] = calls.get(r?.id) ?? [];
|
||||||
|
const data = r?.result?.[1];
|
||||||
|
if (object !== 'luci.dawnline' || !data || typeof data !== 'object') return r;
|
||||||
|
if (method === 'status' && Array.isArray(data.people)) return { ...r, result: [r.result[0], demoStatus(data, first)] };
|
||||||
|
if (method === 'person_usage' && demo.people.has(args?.id) && demo.days.length) {
|
||||||
|
const devs = demo.people.get(args.id).devices ?? [];
|
||||||
|
const per = Object.fromEntries(devs.map(([id, gb]) => [id, daily(demo.days, gb, demo.now)]));
|
||||||
|
const sum = demo.days.map((_, i) => devs.reduce((s, [id]) => [s[0] + per[id][i][0], s[1] + per[id][i][1]], [0, 0]));
|
||||||
|
const devices = Object.fromEntries(devs.map(([id]) => [id, usage(demo.days, per[id])]));
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
result: [r.result[0], { ...data, person: usage(demo.days, sum), devices }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Every check passes: the screenshots show Dawnline, not this router's own setup.
|
||||||
|
if (method === 'health' && Array.isArray(data.checks))
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
result: [
|
||||||
|
r.result[0],
|
||||||
|
{
|
||||||
|
...data,
|
||||||
|
checks: data.checks.map((c) => (c.status === 'warn' || c.status === 'error' ? { ...c, status: 'ok', problem: null } : c)),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
if (method === 'events' && Array.isArray(data.events)) {
|
||||||
|
const mine = demo.events.filter((e) => !args?.person || e.person === args.person);
|
||||||
|
return {
|
||||||
|
...r,
|
||||||
|
result: [r.result[0], { ...data, events: mine, total: mine.length }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
return JSON.stringify(Array.isArray(res) ? res.map(fix) : fix(res));
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// dawnline.awg: disguise presets against their own validation, and the parser
|
// dawnline.awg: disguise presets against their own validation, the parser
|
||||||
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
|
// of `awg show all dump` on the output formats of AmneziaWG 1.0, 2.0 and 3.1
|
||||||
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP).
|
// (the stand-in awg in fixtures/bin prints the fixture put at AWG_DUMP), and Reconnect.
|
||||||
import { readfile, writefile, unlink } from 'fs';
|
import { readfile, writefile, unlink } from 'fs';
|
||||||
import * as awg from 'dawnline.awg';
|
import * as awg from 'dawnline.awg';
|
||||||
|
|
||||||
@@ -13,27 +13,17 @@ test('obf_preset off', () => {
|
|||||||
eq(awg.obf_errors(o), [], 'valid');
|
eq(awg.obf_errors(o), [], 'valid');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('obf_preset standard and strong', () => {
|
|
||||||
for (let name in [ 'standard', 'strong' ])
|
|
||||||
for (let i = 0; i < 25; i++) {
|
|
||||||
let o = awg.obf_preset(name);
|
|
||||||
eq(awg.obf_errors(o), [], `${name} is valid`);
|
|
||||||
let jc = +o.jc, jmin = +o.jmin, jmax = +o.jmax;
|
|
||||||
ok(name == 'strong' ? jc >= 6 && jc <= 10 : jc >= 3 && jc <= 6, `${name} jc=${o.jc}`);
|
|
||||||
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `${name} junk sizes ${o.jmin}-${o.jmax}`);
|
|
||||||
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
|
|
||||||
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
|
|
||||||
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
|
||||||
ok(+o[k] >= 5, `${k} above the reserved values`);
|
|
||||||
eq(o.s3, null, 'no 2.0 values');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('obf_preset balanced', () => {
|
test('obf_preset balanced', () => {
|
||||||
for (let i = 0; i < 25; i++) {
|
for (let i = 0; i < 25; i++) {
|
||||||
let o = awg.obf_preset('balanced');
|
let o = awg.obf_preset('balanced');
|
||||||
eq(awg.obf_errors(o), [], 'balanced is valid');
|
eq(awg.obf_errors(o), [], 'balanced is valid');
|
||||||
ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`);
|
ok(+o.jc >= 4 && +o.jc <= 8, `jc=${o.jc}`);
|
||||||
|
let jmin = +o.jmin, jmax = +o.jmax;
|
||||||
|
ok(jmin >= 64 && jmax > jmin && jmax <= 1024, `junk sizes ${o.jmin}-${o.jmax}`);
|
||||||
|
ok(+o.s1 + 56 != +o.s2, 's1 + 56 != s2');
|
||||||
|
eq(length(uniq([ o.h1, o.h2, o.h3, o.h4 ])), 4, 'distinct headers');
|
||||||
|
for (let k in [ 'h1', 'h2', 'h3', 'h4' ])
|
||||||
|
ok(+o[k] >= 5, `${k} above the reserved values`);
|
||||||
ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`);
|
ok(+o.s3 >= 8 && +o.s3 <= 48 && +o.s4 >= 4 && +o.s4 <= 16, `padding ${o.s3}/${o.s4}`);
|
||||||
ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets');
|
ok(substr(o.i1, 0, 3) == '<r ' && substr(o.i2, 0, 3) == '<r ', 'DNS-shaped signature packets');
|
||||||
eq(o.header_protection_key, null, 'no 3.1 values');
|
eq(o.header_protection_key, null, 'no 3.1 values');
|
||||||
@@ -104,3 +94,12 @@ test('dump: the tool fails', () => {
|
|||||||
let d = awg.dump();
|
let d = awg.dump();
|
||||||
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
|
eq(d, { ok: false, ifaces: {}, peers: {} }, 'nothing known');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('handshake_since: Reconnect hides older handshakes', () => {
|
||||||
|
eq(awg.handshake_since(1000, null), 1000, 'never set up again');
|
||||||
|
eq(awg.handshake_since(1000, 0), 1000, 'no time');
|
||||||
|
eq(awg.handshake_since(1000, 1500), 0, 'connected before: not set up yet');
|
||||||
|
eq(awg.handshake_since(1500, 1500), 0, 'the same second does not count');
|
||||||
|
eq(awg.handshake_since(1600, 1500), 1600, 'connected after');
|
||||||
|
eq(awg.handshake_since(0, 1500), 0, 'never connected');
|
||||||
|
});
|
||||||
@@ -136,3 +136,31 @@ test('names and codes', () => {
|
|||||||
for (let i = 0; i < 20; i++)
|
for (let i = 0; i < 20; i++)
|
||||||
ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code');
|
ok(match(core.new_code(), core.WORD_CODE), 'new_code is a word code');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('renumber_server', () => {
|
||||||
|
let srv = { id: 'main', name: 'Main', subnet: '10.9.0.0/29' };
|
||||||
|
let mm = {
|
||||||
|
servers: { main: srv, other: { id: 'other', subnet: '10.9.1.0/29' } },
|
||||||
|
people: { a: { server: 'main', devices: [ 'a1', 'a2' ] }, o: { server: 'other', devices: [ 'o1' ] } },
|
||||||
|
devices: { a1: { person: 'a', address: '10.9.0.5' }, a2: { person: 'a', address: '10.9.0.3' }, o1: { person: 'o', address: '10.9.1.2' } },
|
||||||
|
};
|
||||||
|
let set = {};
|
||||||
|
let c = { set: (cfg, s, k, v) => { set[`${s}.${k}`] = v; }, delete: () => {} };
|
||||||
|
core.renumber_server(c, mm, srv, '10.77.0.0/24');
|
||||||
|
eq(srv.subnet, '10.77.0.0/24', 'the server moves');
|
||||||
|
eq([ mm.devices.a1.address, mm.devices.a2.address ], [ '10.77.0.2', '10.77.0.3' ], 'devices renumbered lowest first');
|
||||||
|
eq(mm.devices.o1.address, '10.9.1.2', 'another server untouched');
|
||||||
|
eq(set, { 'a1.address': '10.77.0.2', 'a2.address': '10.77.0.3', 'main.subnet': '10.77.0.0/24' }, 'written to uci');
|
||||||
|
let err = null;
|
||||||
|
try { core.renumber_server(c, mm, srv, '10.9.2.0/30'); } catch (e) { err = e; }
|
||||||
|
ok(err != null, 'refuses a subnet too small for the devices');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('device_labels', () => {
|
||||||
|
let mm = { devices: {
|
||||||
|
a: { id: 'a', name: 'iPhone', created: 1 }, b: { id: 'b', name: 'iPhone!', created: 2 },
|
||||||
|
c: { id: 'c', name: 'Телефон', created: 3 }, d: { id: 'd', name: 'телефон', created: 4 },
|
||||||
|
} };
|
||||||
|
let p = { id: 'p', devices: [ 'd', 'c', 'b', 'a' ] };
|
||||||
|
eq(core.device_labels(mm, p), { a: 'iphone', b: 'iphone-2', c: 'telefon', d: 'telefon-2' }, 'unique by age');
|
||||||
|
});
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
# Test fixture: a small installation (one server, two people, one device).
|
# Test fixture: a small installation (one server, two people, one device).
|
||||||
# migrate.test.uc expects bob's random code, the server's stored MTU 1380 and
|
# migrate.test.uc expects bob's random code, the server's stored MTU 1380,
|
||||||
# uhttpd's error_page: the one-time steps remove them.
|
# the old portal title and uhttpd's error_page: the one-time steps remove them.
|
||||||
|
|
||||||
config settings 'settings'
|
config settings 'settings'
|
||||||
option portal_enabled '1'
|
option portal_enabled '1'
|
||||||
option portal_port '8443'
|
option portal_port '8443'
|
||||||
option portal_host 'vpn.example.com'
|
option portal_host 'vpn.example.com'
|
||||||
|
option portal_title 'My VPN'
|
||||||
option log_connections '0'
|
option log_connections '0'
|
||||||
option update_interval '7d'
|
option update_interval '7d'
|
||||||
list update_targets 'app'
|
list update_targets 'app'
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// dawnline.geo: which addresses need a lookup, how results go into the cache
|
||||||
|
// (bounded, never pushing out what is still shown) and the activity-log label.
|
||||||
|
import * as geo from 'dawnline.geo';
|
||||||
|
|
||||||
|
const NOW = 1790000000;
|
||||||
|
const PLACE = { lat: 45.04, lon: 38.98, city: 'Krasnodar', country: 'Russia', cc: 'RU', asn: 12389, org: 'Rostelecom' };
|
||||||
|
|
||||||
|
test('stale', () => {
|
||||||
|
let cache = { ips: {
|
||||||
|
'37.78.36.76': { ...PLACE, ts: NOW - 86400 },
|
||||||
|
'212.233.85.1': { ...PLACE, ts: NOW - 31 * 86400 },
|
||||||
|
'185.135.150.35': { fail: NOW - 3600 },
|
||||||
|
'185.135.150.28': { fail: NOW - 2 * 86400 },
|
||||||
|
'83.239.111.148': { lat: 1, lon: 2, city: 'Old', ts: NOW },
|
||||||
|
}, home: null };
|
||||||
|
eq(geo.stale(cache, [ '37.78.36.76' ], NOW), [], 'fresh: known');
|
||||||
|
eq(geo.stale(cache, [ '212.233.85.1' ], NOW), [ '212.233.85.1' ], 'older than the TTL');
|
||||||
|
eq(geo.stale(cache, [ '185.135.150.35' ], NOW), [], 'failed today: not again yet');
|
||||||
|
eq(geo.stale(cache, [ '185.135.150.28' ], NOW), [ '185.135.150.28' ], 'failed two days ago: retried');
|
||||||
|
eq(geo.stale(cache, [ '83.239.111.148' ], NOW), [ '83.239.111.148' ], 'an entry from before ASNs were kept');
|
||||||
|
eq(geo.stale(cache, [ '10.0.1.164', '100.64.1.1', '', null, 'fe80::1' ], NOW), [], 'local addresses never');
|
||||||
|
eq(geo.stale(cache, [ '1.1.1.1', '8.8.8.8', '1.1.1.1' ], NOW), [ '1.1.1.1', '8.8.8.8' ], 'once each, in order');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('merge', () => {
|
||||||
|
let cache = { ips: {}, home: null };
|
||||||
|
ok(geo.merge(cache, { '1.1.1.1': { ...PLACE }, '8.8.8.8': false }, [], NOW), 'changed');
|
||||||
|
eq(cache.ips['1.1.1.1'], { ...PLACE, ts: NOW }, 'a place, stamped');
|
||||||
|
eq(cache.ips['8.8.8.8'], { fail: NOW }, 'nothing found: a failure, retried later');
|
||||||
|
ok(!geo.merge(cache, {}, [], NOW), 'no results: unchanged');
|
||||||
|
ok(!geo.merge(cache, { '10.0.0.1': PLACE }, [], NOW) && !cache.ips['10.0.0.1'], 'a local address is not kept');
|
||||||
|
eq(geo.place(cache, '1.1.1.1')?.city, 'Krasnodar', 'place');
|
||||||
|
eq(geo.place(cache, '8.8.8.8'), null, 'no place for a failure');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('merge keeps the cache bounded, what is shown stays', () => {
|
||||||
|
let cache = { ips: {}, home: null };
|
||||||
|
for (let i = 0; i < 500; i++)
|
||||||
|
cache.ips[`1.0.${int(i / 250)}.${i % 250 + 1}`] = { ...PLACE, ts: NOW - 1000 + i };
|
||||||
|
let oldest = '1.0.0.1', second = '1.0.0.2';
|
||||||
|
ok(geo.merge(cache, { '9.9.9.9': PLACE }, [ oldest ], NOW), 'changed');
|
||||||
|
eq(length(keys(cache.ips)), 500, 'back to the cap');
|
||||||
|
ok(cache.ips[oldest] != null, 'the oldest is still shown: kept');
|
||||||
|
ok(cache.ips[second] == null, 'the oldest not shown went');
|
||||||
|
ok(cache.ips['9.9.9.9'] != null, 'the new one is in');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('label', () => {
|
||||||
|
eq(geo.label(PLACE), 'Krasnodar · Rostelecom', 'city and ISP');
|
||||||
|
eq(geo.label({ city: '', org: 'Rostelecom' }), 'Rostelecom', 'no city');
|
||||||
|
eq(geo.label(null), null, 'no place');
|
||||||
|
});
|
||||||
@@ -48,3 +48,21 @@ test('endpoint_ip', () => {
|
|||||||
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
|
eq(live.endpoint_ip('[2001:db8::1]:41821'), '2001:db8::1', 'v6');
|
||||||
eq(live.endpoint_ip(''), '', 'none');
|
eq(live.endpoint_ip(''), '', 'none');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// A connect is logged before its new address is located; the place comes later.
|
||||||
|
test('fill_places', () => {
|
||||||
|
let ev = [
|
||||||
|
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 100 },
|
||||||
|
{ type: 'connect', detail: '1.1.1.1', where: null, ts: 200 },
|
||||||
|
{ type: 'disconnect', detail: null, ts: 210 },
|
||||||
|
{ type: 'connect', detail: '8.8.8.8', where: 'Mountain View · Google', ts: 220 },
|
||||||
|
{ type: 'connect', detail: '9.9.9.9', where: null, ts: 230 },
|
||||||
|
];
|
||||||
|
ok(live.fill_places(ev, { '1.1.1.1': 'Sydney · Cloudflare', '8.8.8.8': 'Elsewhere' }, 150), 'changed');
|
||||||
|
eq(ev[1].where, 'Sydney · Cloudflare', 'the waiting connect gets its place');
|
||||||
|
eq(ev[0].where, null, 'older than `since`: left alone');
|
||||||
|
eq(ev[3].where, 'Mountain View · Google', 'a place already there stays');
|
||||||
|
eq(ev[4].where, null, 'another address');
|
||||||
|
ok(!live.fill_places(ev, { '7.7.7.7': 'X' }, 0), 'nothing to fill: unchanged');
|
||||||
|
ok(!live.fill_places([], { '1.1.1.1': 'X' }, 0), 'empty log');
|
||||||
|
});
|
||||||
@@ -16,6 +16,7 @@ test('before: the fixture holds the old state', () => {
|
|||||||
let c = conf('dawnline');
|
let c = conf('dawnline');
|
||||||
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
|
eq(c.get('dawnline', 'bob', 'code'), 'XyZ12345', 'random code');
|
||||||
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
|
eq(c.get('dawnline', 'main', 'mtu'), '1380', 'stored MTU');
|
||||||
|
eq(c.get('dawnline', 'settings', 'portal_title'), 'My VPN', 'a portal title');
|
||||||
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
|
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), '/cgi-bin/dawnline-portal', 'portal as error page');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -27,6 +28,7 @@ test('run: the steps change what they must', () => {
|
|||||||
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
|
eq(c.get('dawnline', 'main', 'mtu'), null, 'MTU is automatic');
|
||||||
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
|
eq(c.get('dawnline', 'main', 'subnet'), '10.9.0.0/29', 'the rest of the server stays');
|
||||||
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
|
eq(c.get('dawnline', 'settings', 'portal_443'), null, 'no portal_443');
|
||||||
|
eq(c.get('dawnline', 'settings', 'portal_title'), null, 'no portal title');
|
||||||
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
|
eq(conf('uhttpd').get('uhttpd', 'main', 'error_page'), null, 'error page gone');
|
||||||
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
|
eq(conf('uhttpd').get('uhttpd', 'main', 'home'), '/www', 'the rest of uhttpd stays');
|
||||||
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
|
eq(stat('/etc/config/dawnline').perm, { setuid: false, setgid: false, sticky: false,
|
||||||
|
|||||||
@@ -34,8 +34,9 @@ test('validate: host and hosts', () => {
|
|||||||
eq(schema.validate('portal_host', 'vpn.example.com'), 'vpn.example.com', 'name');
|
eq(schema.validate('portal_host', 'vpn.example.com'), 'vpn.example.com', 'name');
|
||||||
eq(schema.validate('portal_host', '203.0.113.7'), '203.0.113.7', 'address');
|
eq(schema.validate('portal_host', '203.0.113.7'), '203.0.113.7', 'address');
|
||||||
throws(() => schema.validate('portal_host', 'bad host!'), /hostname or IP/, 'bad');
|
throws(() => schema.validate('portal_host', 'bad host!'), /hostname or IP/, 'bad');
|
||||||
eq(schema.validate('portal_alt', [ 'a.example.com', ' a.example.com ', 'bad host', 'b.example.com' ]),
|
eq(schema.validate('portal_alt', [ 'a.example.com', ' a.example.com ', '', 'b.example.com' ]),
|
||||||
[ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, bad ones dropped');
|
[ 'a.example.com', 'b.example.com' ], 'trimmed, deduplicated, empty ones dropped');
|
||||||
|
throws(() => schema.validate('portal_alt', [ 'a.example.com', 'bad host' ]), /hostnames or IP/, 'a typo is refused, not dropped');
|
||||||
eq(schema.validate('portal_alt', []), null, 'empty list removes the option');
|
eq(schema.validate('portal_alt', []), null, 'empty list removes the option');
|
||||||
eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list');
|
eq(schema.validate('portal_alt', 'a.example.com'), null, 'not a list');
|
||||||
});
|
});
|
||||||
@@ -76,13 +77,6 @@ test('validate: time', () => {
|
|||||||
throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60');
|
throws(() => schema.validate('update_time', '23:60'), /HH:MM/, 'minute 60');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('validate: text', () => {
|
|
||||||
eq(schema.validate('portal_title', 'My VPN'), 'My VPN', 'plain');
|
|
||||||
eq(schema.validate('portal_title', replace(sprintf('%64s', ''), ' ', 'a')), replace(sprintf('%64s', ''), ' ', 'a'), '64 characters');
|
|
||||||
throws(() => schema.validate('portal_title', replace(sprintf('%65s', ''), ' ', 'a')), /64 characters/, '65 characters');
|
|
||||||
throws(() => schema.validate('portal_title', 'a\nb'), /64 characters/, 'control character');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('validate: targets', () => {
|
test('validate: targets', () => {
|
||||||
eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once');
|
eq(schema.validate('update_targets', [ 'app', 'bogus', 'app', 'amneziawg' ]), [ 'app', 'amneziawg' ], 'known ones, once');
|
||||||
eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice');
|
eq(schema.validate('update_targets', []), [ 'none' ], 'empty is a choice');
|
||||||
@@ -109,8 +103,6 @@ test('get', () => {
|
|||||||
eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty');
|
eq(schema.get({ home_dns_fallback: 'none' }, 'home_dns_fallback'), '', 'none reads as empty');
|
||||||
eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4');
|
eq(schema.get({}, 'home_dns_fallback'), '1.1.1.1', 'missing ipv4');
|
||||||
eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4');
|
eq(schema.get({ home_dns_fallback: '300.1.1.1' }, 'home_dns_fallback'), '1.1.1.1', 'bad ipv4');
|
||||||
eq(schema.get({}, 'portal_title'), 'Dawnline', 'missing text');
|
|
||||||
eq(schema.get({ portal_title: '' }, 'portal_title'), 'Dawnline', 'empty text');
|
|
||||||
eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through');
|
eq(schema.get({ portal_host: 'vpn.example.com' }, 'portal_host'), 'vpn.example.com', 'host passes through');
|
||||||
eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value');
|
eq(schema.get({ other: 'raw' }, 'other'), 'raw', 'unknown key is the raw value');
|
||||||
eq(schema.get(null, 'portal_port'), 8443, 'no section');
|
eq(schema.get(null, 'portal_port'), 8443, 'no section');
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ test('valid_name', () => {
|
|||||||
ok(!util.valid_name(' '), 'blank');
|
ok(!util.valid_name(' '), 'blank');
|
||||||
ok(!util.valid_name(null), 'null');
|
ok(!util.valid_name(null), 'null');
|
||||||
ok(!util.valid_name(42), 'number');
|
ok(!util.valid_name(42), 'number');
|
||||||
ok(util.valid_name('a' + replace(sprintf('%47s', ''), ' ', 'b')), '48 bytes');
|
ok(util.valid_name('a' + replace(sprintf('%47s', ''), ' ', 'b')), '48 characters');
|
||||||
ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 bytes');
|
ok(!util.valid_name('a' + replace(sprintf('%48s', ''), ' ', 'b')), '49 characters');
|
||||||
|
ok(util.valid_name('ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧ'), '25 Cyrillic letters (50 bytes) are 25 characters');
|
||||||
|
ok(!util.valid_name('Bob "B"'), 'quotes');
|
||||||
ok(!util.valid_name('a<b'), 'angle bracket');
|
ok(!util.valid_name('a<b'), 'angle bracket');
|
||||||
ok(!util.valid_name('a"b'), 'quote');
|
ok(!util.valid_name('a"b'), 'quote');
|
||||||
ok(!util.valid_name('a\\b'), 'backslash');
|
ok(!util.valid_name('a\\b'), 'backslash');
|
||||||
@@ -96,7 +98,9 @@ test('slugify', () => {
|
|||||||
eq(util.slugify(' --Bob!! '), 'bob', 'trimmed dashes');
|
eq(util.slugify(' --Bob!! '), 'bob', 'trimmed dashes');
|
||||||
eq(util.slugify(''), 'user', 'empty');
|
eq(util.slugify(''), 'user', 'empty');
|
||||||
eq(util.slugify(null), 'user', 'null');
|
eq(util.slugify(null), 'user', 'null');
|
||||||
eq(util.slugify('Мама'), 'user', 'nothing left');
|
eq(util.slugify('Мама'), 'mama', 'Cyrillic written in Latin');
|
||||||
|
eq(util.slugify('Юля Щукина'), 'yulya-shchukina', 'Cyrillic words');
|
||||||
|
eq(util.slugify('日本'), 'user', 'nothing left');
|
||||||
eq(length(util.slugify(replace(sprintf('%40s', ''), ' ', 'x'))), 32, 'cut at 32');
|
eq(length(util.slugify(replace(sprintf('%40s', ''), ' ', 'x'))), 32, 'cut at 32');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -112,3 +116,27 @@ test('dates', () => {
|
|||||||
eq(util.day_key_ago(0, noon), '2026-03-01', 'zero days');
|
eq(util.day_key_ago(0, noon), '2026-03-01', 'zero days');
|
||||||
eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq');
|
eq(util.uniq([ 'a', 'b', 'a', 'c', 'b' ]), [ 'a', 'b', 'c' ], 'uniq');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('text: ulength, ucut, translit, host_label, tunnel_name', () => {
|
||||||
|
eq(util.ulength('Мама'), 4, 'characters, not bytes');
|
||||||
|
eq(util.ulength('abc'), 3, 'ascii');
|
||||||
|
eq(util.ucut('Привет', 3), 'При', 'cut by characters');
|
||||||
|
eq(util.ucut('ab', 5), 'ab', 'shorter than the cut');
|
||||||
|
eq(util.translit('Мама Таня'), 'mama tanya', 'Russian');
|
||||||
|
eq(util.translit('Їжак Ґава ёж'), 'yizhak gava yozh', 'Ukrainian letters and ё');
|
||||||
|
eq(util.translit('Mixed Текст 1'), 'Mixed tekst 1', 'Latin and digits pass');
|
||||||
|
eq(util.host_label('Galaxy S24'), 'galaxy-s24', 'label');
|
||||||
|
eq(util.host_label('Телефон Ёжика'), 'telefon-yozhika', 'Cyrillic label');
|
||||||
|
eq(util.tunnel_name('Outline Home'), 'Outline-Home', 'tunnel name keeps the case');
|
||||||
|
eq(util.tunnel_name('Дом у моря'), 'dom-u-morya', 'Cyrillic tunnel name');
|
||||||
|
eq(util.tunnel_name(' My VPN (home)! '), 'My-VPN-home', 'tunnel name: runs of other characters are one dash');
|
||||||
|
eq(util.tunnel_name('A very long server name'), 'A-very-long-ser', 'tunnel name: 15 characters at most');
|
||||||
|
eq(util.tunnel_name('Home server 12345'), 'Home-server-123', 'tunnel name: cut');
|
||||||
|
eq(util.tunnel_name('Lakeside house x'), 'Lakeside-house', 'tunnel name: no dash left at the cut');
|
||||||
|
eq(util.tunnel_name('nul'), 'dawnline', 'tunnel name: a Windows device name');
|
||||||
|
eq(util.tunnel_name('COM1'), 'dawnline', 'tunnel name: a Windows device name, any case');
|
||||||
|
eq(util.tunnel_name('???'), 'dawnline', 'tunnel name: nothing left');
|
||||||
|
eq(util.tunnel_name(null), 'dawnline', 'tunnel name: null');
|
||||||
|
eq(util.host_label('!!!'), 'device', 'nothing left');
|
||||||
|
eq(length(util.host_label(replace(sprintf('%50s', ''), ' ', 'x'))), 40, 'cut at 40');
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// dawnline.view: which device a portal page was opened from, and the usage series it draws.
|
||||||
|
import * as view from 'dawnline.view';
|
||||||
|
import { day_key_ago } from 'dawnline.util';
|
||||||
|
|
||||||
|
const devs = [
|
||||||
|
{ id: 'd_1', address: '10.0.0.2', online: true, endpoint: '203.0.113.7' },
|
||||||
|
{ id: 'd_2', address: '10.0.0.3', online: false, endpoint: '198.51.100.4' },
|
||||||
|
{ id: 'd_3', address: '10.0.0.4', online: true, endpoint: '192.0.2.9' },
|
||||||
|
];
|
||||||
|
|
||||||
|
test('device_here', () => {
|
||||||
|
eq(view.device_here(devs, '10.0.0.3'), 'd_2', 'through the tunnel: its address, online or not');
|
||||||
|
eq(view.device_here(devs, '203.0.113.7'), 'd_1', 'beside the tunnel: where its tunnel comes from');
|
||||||
|
eq(view.device_here(devs, '::ffff:203.0.113.7'), 'd_1', 'an IPv4 request on a dual-stack socket');
|
||||||
|
eq(view.device_here(devs, '198.51.100.4'), null, 'a device that is not online does not count');
|
||||||
|
eq(view.device_here(devs, '233.252.0.1'), null, 'from elsewhere');
|
||||||
|
eq(view.device_here([ ...devs, { id: 'd_4', address: '10.0.0.5', online: true, endpoint: '203.0.113.7' } ], '203.0.113.7'), null,
|
||||||
|
'two devices behind one address: neither');
|
||||||
|
eq(view.device_here(devs, ''), null, 'no address');
|
||||||
|
eq(view.device_here([ { id: 'd_5', address: '10.0.0.6', online: true, endpoint: '' } ], ''), null, 'no address, no endpoint');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('month_days', () => {
|
||||||
|
let n = +substr(day_key_ago(0), 8, 2);
|
||||||
|
let days = {};
|
||||||
|
// On the 1st, today is the 1st: then only today's own value.
|
||||||
|
if (n > 1)
|
||||||
|
days[day_key_ago(n - 1)] = [ 1, 2 ];
|
||||||
|
days[day_key_ago(0)] = [ 5, 7 ];
|
||||||
|
// Last month's last day stays out of this month's chart.
|
||||||
|
days[day_key_ago(n)] = [ 100, 100 ];
|
||||||
|
let s = view.month_days({ days });
|
||||||
|
eq(length(s), n, 'one bar a day, from the 1st to today');
|
||||||
|
eq(s[n - 1], 12, 'today last, received and sent together');
|
||||||
|
eq(s[0], n > 1 ? 3 : 12, 'the 1st first');
|
||||||
|
eq(length(view.month_days(null)), n, 'no usage yet: zeros');
|
||||||
|
eq(view.month_days(null)[0], 0, 'a day without traffic is zero');
|
||||||
|
});
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.7.0",
|
"version": "0.10.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.7.0",
|
"version": "0.10.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"qrcode-generator": "1.4.4"
|
"qrcode-generator": "1.4.4"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "dawnline-web",
|
"name": "dawnline-web",
|
||||||
"version": "0.7.0",
|
"version": "0.10.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import { E } from './e';
|
|||||||
import { api, type HomeHost } from './api';
|
import { api, type HomeHost } from './api';
|
||||||
import { button } from './ui/button';
|
import { button } from './ui/button';
|
||||||
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
|
import { cancelButton, closeModal, confirmDialog, modal } from './ui/modal';
|
||||||
import { attempt } from './ui/toast';
|
import { attempt, notify } from './ui/toast';
|
||||||
import { chipToggle, input } from './ui/controls';
|
import { chipToggle, input } from './ui/controls';
|
||||||
|
import { firstBad, liveField } from './ui/layout';
|
||||||
|
import { circleNameHelp, ipv4Help, nameHelp, portsHelp } from './netcheck';
|
||||||
import { icon } from '../shared/icons';
|
import { icon } from '../shared/icons';
|
||||||
|
|
||||||
type Service = Status['services'][number];
|
type Service = Status['services'][number];
|
||||||
@@ -30,17 +32,23 @@ export function serviceDialog(sv: Service | null, prefill: Partial<Service>, onS
|
|||||||
placeholder: 'All ports, or e.g. 445, 5000',
|
placeholder: 'All ports, or e.g. 445, 5000',
|
||||||
class: 'cbi-input-text dl-mono',
|
class: 'cbi-input-text dl-mono',
|
||||||
});
|
});
|
||||||
const field = (label: string, el: Node) =>
|
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown to people who may reach it.'));
|
||||||
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
const addrRow = liveField('Address', addr, () => ipv4Help(addr.value));
|
||||||
|
const portsRow = liveField('Ports', ports, () => portsHelp(ports.value));
|
||||||
modal(
|
modal(
|
||||||
sv ? `Edit ${sv.name}` : 'Add service',
|
sv ? `Edit ${sv.name}` : 'Add service',
|
||||||
[field('Name', name), field('Address', addr), field('Ports', ports)],
|
[nameRow, addrRow, portsRow],
|
||||||
[
|
[
|
||||||
cancelButton(),
|
cancelButton(),
|
||||||
' ',
|
' ',
|
||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
async () => {
|
async () => {
|
||||||
|
const bad = firstBad([nameRow, addrRow, portsRow]);
|
||||||
|
if (bad) {
|
||||||
|
notify(bad, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
const list = ports.value.split(/[ ,]+/).filter(Boolean);
|
||||||
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
|
if (await attempt(() => api.serviceSet(sv?.id ?? '', name.value, addr.value, list), 'Saved')) {
|
||||||
closeModal();
|
closeModal();
|
||||||
@@ -316,11 +324,13 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
|||||||
);
|
);
|
||||||
const field = (label: string, el: Node) =>
|
const field = (label: string, el: Node) =>
|
||||||
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, label), E('div', { class: 'cbi-value-field' }, el)]);
|
||||||
|
const others = st.circles.filter((c) => c.server === serverId && c.id !== ci?.id).map((c) => c.name);
|
||||||
|
const nameRow = liveField('Name', name, () => circleNameHelp(name.value, others));
|
||||||
|
|
||||||
modal(
|
modal(
|
||||||
ci ? `Edit ${ci.name}` : 'New circle',
|
ci ? `Edit ${ci.name}` : 'New circle',
|
||||||
[
|
[
|
||||||
field('Name', name),
|
nameRow,
|
||||||
field('Colour', swatches),
|
field('Colour', swatches),
|
||||||
field('People', chips),
|
field('People', chips),
|
||||||
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
|
E('p', { class: 'dl-sub' }, 'Devices of people in one circle reach each other. A person is in one circle at a time.'),
|
||||||
@@ -344,6 +354,11 @@ export function circleDialog(st: Status, serverId: string, ci: Circle | null, on
|
|||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
async () => {
|
async () => {
|
||||||
|
const h = nameRow.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
|
if (await attempt(() => api.circleSet(ci?.id ?? '', serverId, name.value, color, [...members]), 'Saved')) {
|
||||||
closeModal();
|
closeModal();
|
||||||
onDone();
|
onDone();
|
||||||
|
|||||||
@@ -39,6 +39,24 @@ export interface SetupDefaults {
|
|||||||
tcp_taken: PortHold[];
|
tcp_taken: PortHold[];
|
||||||
awg: AwgCaps;
|
awg: AwgCaps;
|
||||||
awg_state?: AwgState;
|
awg_state?: AwgState;
|
||||||
|
/** Where the suggested address came from: ddns, cert, wan, portal ('' = nothing found). */
|
||||||
|
endpoint_from?: string;
|
||||||
|
/** What the WAN's IPv4 is: public, private (behind another router), cgnat, none. */
|
||||||
|
wan_kind?: 'public' | 'private' | 'cgnat' | 'none';
|
||||||
|
wan_ip?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a public address points (rpc endpoint_probe): the facts and their verdict in words. */
|
||||||
|
export interface EndpointProbe {
|
||||||
|
host: string;
|
||||||
|
ips: string[];
|
||||||
|
wan: string | null;
|
||||||
|
kind: 'public' | 'private' | 'cgnat' | 'none';
|
||||||
|
cloudflare: boolean;
|
||||||
|
here: boolean;
|
||||||
|
v6_only: boolean;
|
||||||
|
status: 'ok' | 'warn' | 'error';
|
||||||
|
text: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Backup {
|
export interface Backup {
|
||||||
@@ -323,7 +341,8 @@ export type PersonPatch = Partial<
|
|||||||
| 'bonus_gb'
|
| 'bonus_gb'
|
||||||
| 'hours'
|
| 'hours'
|
||||||
| 'note'
|
| 'note'
|
||||||
| 'dns_mode',
|
| 'dns_mode'
|
||||||
|
| 'server',
|
||||||
string
|
string
|
||||||
>
|
>
|
||||||
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
|
> & { paused?: boolean; services?: string[]; circle?: string; home_nets?: string[] };
|
||||||
@@ -349,6 +368,7 @@ const personUpdateRaw = rpc.declare<any>({
|
|||||||
'services',
|
'services',
|
||||||
'circle',
|
'circle',
|
||||||
'home_nets',
|
'home_nets',
|
||||||
|
'server',
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -367,7 +387,7 @@ async function personUpdate(id: string, patch: PersonPatch): Promise<{ person: P
|
|||||||
'note',
|
'note',
|
||||||
'dns_mode',
|
'dns_mode',
|
||||||
] as const;
|
] as const;
|
||||||
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets];
|
const args: unknown[] = [id, ...keys.map((k) => patch[k]), patch.paused, patch.services, patch.circle, patch.home_nets, patch.server];
|
||||||
return settle(await personUpdateRaw(...args));
|
return settle(await personUpdateRaw(...args));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,6 +472,10 @@ export const api = {
|
|||||||
]),
|
]),
|
||||||
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
|
serverObfuscation: call<unknown>('server_obfuscation', ['id', 'preset']),
|
||||||
serverUpdate: call<unknown>('server_update', ['id', 'values']),
|
serverUpdate: call<unknown>('server_update', ['id', 'values']),
|
||||||
|
/** What an existing server's ports and a new tunnel network must avoid (checked as you type). */
|
||||||
|
serverPorts: call<{ udp_taken: PortHold[]; tcp_taken: PortHold[]; networks?: Network[] }>('server_ports', ['id']),
|
||||||
|
/** Where a public address points, for the live help under the field (debounced by the caller). */
|
||||||
|
endpointProbe: call<EndpointProbe>('endpoint_probe', ['host', 'id', 'port']),
|
||||||
serverDelete: call<unknown>('server_delete', ['id']),
|
serverDelete: call<unknown>('server_delete', ['id']),
|
||||||
/** The personal link, its code and every address it works on (main first); not part of the status. */
|
/** The personal link, its code and every address it works on (main first); not part of the status. */
|
||||||
personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']),
|
personLinks: call<{ code: string; link: string | null; links: string[] }>('person_links', ['id']),
|
||||||
|
|||||||
@@ -10,11 +10,12 @@ import { confirmDialog } from '../ui/modal';
|
|||||||
import { copyText, downloadFile } from '../ui/files';
|
import { copyText, downloadFile } from '../ui/files';
|
||||||
import { attempt, notify } from '../ui/toast';
|
import { attempt, notify } from '../ui/toast';
|
||||||
import { input } from '../ui/controls';
|
import { input } from '../ui/controls';
|
||||||
import { callout, card, group, row, svg } from '../ui/layout';
|
import { callout, card, firstBad, group, liveRow, row } from '../ui/layout';
|
||||||
import { qrSvg } from '../../shared/qr';
|
import { qrCode } from '../ui/qr';
|
||||||
|
import { keepaliveHelp, mtuHelp, portHelp, type PortHold } from '../netcheck';
|
||||||
import { vpnKey } from '../../shared/vpnkey';
|
import { vpnKey } from '../../shared/vpnkey';
|
||||||
import { icon } from '../../shared/icons';
|
import { icon } from '../../shared/icons';
|
||||||
import { methodInfo, methodPicker, type Method } from '../disguise';
|
import { methodInfo, methodPicker, type Method, defaultMethod, legacyTitle } from '../disguise';
|
||||||
import { coreHead, type Core, type CoreCtx } from './common';
|
import { coreHead, type Core, type CoreCtx } from './common';
|
||||||
|
|
||||||
/** `.conf` names of the disguise parameters, in file order. */
|
/** `.conf` names of the disguise parameters, in file order. */
|
||||||
@@ -170,7 +171,7 @@ function fileCard(cfg: AwgConfig): HTMLElement {
|
|||||||
E('span', { class: 'dl-filecard-ic' }, '.conf'),
|
E('span', { class: 'dl-filecard-ic' }, '.conf'),
|
||||||
E('span', { class: 'dl-stack' }, [
|
E('span', { class: 'dl-stack' }, [
|
||||||
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
|
E('span', { class: 'dl-mono dl-ellipsis' }, cfg.filename),
|
||||||
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes · import it in the app`),
|
E('span', { class: 'dl-sub' }, `AmneziaWG · ${size} bytes`),
|
||||||
]),
|
]),
|
||||||
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
|
button([icon('download'), ' Download'], () => downloadFile(cfg.filename, cfg.conf, 'application/octet-stream'), 'positive'),
|
||||||
]),
|
]),
|
||||||
@@ -198,6 +199,13 @@ function fileCard(cfg: AwgConfig): HTMLElement {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The configuration carries no disguise values: plain WireGuard, any WireGuard app takes it. */
|
||||||
|
export function plainWg(cfg: AwgConfig): boolean {
|
||||||
|
const o = (cfg.amnezia.obfuscation ?? {}) as Record<string, string | undefined>;
|
||||||
|
const neutral: Record<string, string> = { h1: '1', h2: '2', h3: '3', h4: '4' };
|
||||||
|
return Object.entries(o).every(([k, v]) => v == null || v === '' || v === (neutral[k] ?? '0'));
|
||||||
|
}
|
||||||
|
|
||||||
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
|
/** File / key / QR switcher for a client configuration; opens on the file unless asked otherwise. */
|
||||||
export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
|
export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr' = 'file'): Promise<HTMLElement> {
|
||||||
if (!cfg.has_private_key)
|
if (!cfg.has_private_key)
|
||||||
@@ -206,12 +214,16 @@ export async function connectBlock(cfg: AwgConfig, initial: 'file' | 'key' | 'qr
|
|||||||
{ class: 'dl-hint' },
|
{ class: 'dl-hint' },
|
||||||
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
|
'This device generated its own keys in the browser, so its full configuration only exists on that device.',
|
||||||
);
|
);
|
||||||
const key = await vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`);
|
const key = await vpnKey(cfg, cfg.server);
|
||||||
const panes: Record<string, () => Node> = {
|
const panes: Record<string, () => Node> = {
|
||||||
qr: () =>
|
qr: () =>
|
||||||
E('div', { class: 'dl-qr-pane' }, [
|
E('div', { class: 'dl-qr-pane' }, [
|
||||||
svg(qrSvg(cfg.conf), 'dl-qr'),
|
qrCode(cfg.conf),
|
||||||
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
|
E(
|
||||||
|
'span',
|
||||||
|
{ class: 'dl-sub' },
|
||||||
|
plainWg(cfg) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
|
||||||
|
),
|
||||||
]),
|
]),
|
||||||
key: () =>
|
key: () =>
|
||||||
E('div', { class: 'dl-stack gap8' }, [
|
E('div', { class: 'dl-stack gap8' }, [
|
||||||
@@ -243,7 +255,7 @@ async function applyDisguise(ctx: CoreCtx, srv: Server, m: Method, same: boolean
|
|||||||
const devices = people.reduce((n, p) => n + p.devices.length, 0);
|
const devices = people.reduce((n, p) => n + p.devices.length, 0);
|
||||||
const ok = await confirmDialog(
|
const ok = await confirmDialog(
|
||||||
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
|
same ? 'Generate new disguise values?' : `Switch to ${info.title}?`,
|
||||||
`${devices} AmneziaWG device${devices === 1 ? '' : 's'} stop connecting until they import their configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : m === 'balanced' ? ' They need an app with AmneziaWG 2.0 or newer.' : ''}`,
|
`${devices} AmneziaWG device${devices === 1 ? ' stops' : 's stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).${m === 'max' ? ' They need an app with AmneziaWG 3.1.' : m === 'balanced' ? ' They need an app with AmneziaWG 2.0 or newer.' : ''}${ctx.st.servers.length === 1 && devices ? ' To keep the old disguise for some people, add a second server and move them there.' : ''}`,
|
||||||
same ? 'Generate and apply' : 'Switch and apply',
|
same ? 'Generate and apply' : 'Switch and apply',
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
@@ -263,30 +275,54 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
|||||||
inputmode: 'numeric',
|
inputmode: 'numeric',
|
||||||
class: 'cbi-input-text dl-w-port dl-mono',
|
class: 'cbi-input-text dl-w-port dl-mono',
|
||||||
});
|
});
|
||||||
const now = `${srv.mtus.computer} for computers and routers, ${srv.mtus.phone} for phones and tablets`;
|
|
||||||
const mtuHint = srv.mtu
|
|
||||||
? `Now ${now}. Empty = automatic.`
|
|
||||||
: `Automatic by device type and disguise: now ${now}. Lower it if some sites hang.`;
|
|
||||||
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
const ka = input(String(srv.keepalive ?? ''), { placeholder: '25', inputmode: 'numeric', class: 'cbi-input-text dl-w-port dl-mono' });
|
||||||
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
|
const current = methodInfo(srv.preset) ? (srv.preset as Method) : undefined;
|
||||||
let selected: Method = current ?? 'standard';
|
let selected: Method = current ?? defaultMethod(st.awg);
|
||||||
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
|
const apply = button('', () => applyDisguise(ctx, srv, selected, selected === current), 'neutral');
|
||||||
const label = () =>
|
const label = () =>
|
||||||
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
|
dom.content(apply, selected === current ? [icon('reset'), ' Generate new values'] : [`Switch to ${methodInfo(selected)!.title}`]);
|
||||||
label();
|
label();
|
||||||
const tools = st.awg_state?.tools !== false;
|
const tools = st.awg_state?.tools !== false;
|
||||||
|
// Who holds which port arrives once the card is built (netstat on the
|
||||||
|
// router); until then the port is only checked for its range.
|
||||||
|
let holds: PortHold[] = [];
|
||||||
|
const portRow = liveRow('UDP port', port, () =>
|
||||||
|
portHelp(
|
||||||
|
Number(port.value),
|
||||||
|
holds,
|
||||||
|
`Opened on the WAN firewall automatically.${Number(port.value) === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
api
|
||||||
|
.serverPorts(srv.id)
|
||||||
|
.then((r) => {
|
||||||
|
holds = r.udp_taken ?? [];
|
||||||
|
portRow.refresh();
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
const mtuRow = liveRow('MTU', mtu, () => mtuHelp(mtu.value, srv.mtus));
|
||||||
|
const kaRow = liveRow('Keep-alive', ka, () => keepaliveHelp(ka.value));
|
||||||
return card(
|
return card(
|
||||||
'',
|
'',
|
||||||
[
|
[
|
||||||
coreHead('AmneziaWG', srv.ifname),
|
coreHead('AmneziaWG', srv.ifname),
|
||||||
group('globe', 'Listening', 'Where devices reach this core from the internet', [
|
group('globe', 'Listening', 'Where devices reach this core from the internet', [portRow]),
|
||||||
row('UDP port', port, 'Opened on the WAN firewall automatically.'),
|
|
||||||
]),
|
|
||||||
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
|
group('file', 'In every device configuration', 'Changing these marks devices “Update config” until they import again', [
|
||||||
row('MTU', mtu, mtuHint),
|
mtuRow,
|
||||||
row('Keep-alive', ka, 'Seconds between packets devices send to keep NAT open. 0 = off.'),
|
kaRow,
|
||||||
]),
|
]),
|
||||||
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
|
group('shield', 'Disguise', 'So networks that block VPNs do not recognise the tunnel. Off = plain WireGuard', [
|
||||||
|
// A server from before 0.8 on the old junk-only disguise: it runs, but is no longer offered.
|
||||||
|
legacyTitle(srv.preset)
|
||||||
|
? callout('warn', [
|
||||||
|
E('b', {}, legacyTitle(srv.preset)!),
|
||||||
|
' is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ',
|
||||||
|
E('b', {}, 'Balanced'),
|
||||||
|
' or ',
|
||||||
|
E('b', {}, 'Maximum'),
|
||||||
|
': devices import their configuration again.',
|
||||||
|
])
|
||||||
|
: '',
|
||||||
methodPicker(
|
methodPicker(
|
||||||
st.awg,
|
st.awg,
|
||||||
selected,
|
selected,
|
||||||
@@ -331,7 +367,19 @@ export function settingsCard(ctx: CoreCtx, srv: Server): HTMLElement {
|
|||||||
],
|
],
|
||||||
[
|
[
|
||||||
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
|
E('span', { class: 'dl-sub' }, 'Port, MTU and keep-alive apply at once.'),
|
||||||
button('Save', () => ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved'), 'positive'),
|
button(
|
||||||
|
'Save',
|
||||||
|
() => {
|
||||||
|
// The help lines already say what is wrong: do not send it anyway.
|
||||||
|
const bad = firstBad([portRow, mtuRow, kaRow]);
|
||||||
|
if (bad) {
|
||||||
|
notify(bad, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return ctx.save({ port: port.value, mtu: mtu.value, keepalive: ka.value }, 'AmneziaWG saved');
|
||||||
|
},
|
||||||
|
'positive',
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -360,8 +408,11 @@ function overviewTile(srv: Server): HTMLElement {
|
|||||||
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}§ion=awg` }, 'Change'),
|
E('a', { href: `${L.url('admin/network/dawnline/server')}?server=${encodeURIComponent(srv.id)}§ion=awg` }, 'Change'),
|
||||||
]),
|
]),
|
||||||
E('div', { class: 'dl-disg-id' }, [
|
E('div', { class: 'dl-disg-id' }, [
|
||||||
E('span', { class: 'dl-disg-ic' }, icon(m?.ic ?? 'shield')),
|
E('span', { class: `dl-disg-ic${m?.id === 'off' ? ' off' : ''}` }, icon(m?.ic ?? 'shield')),
|
||||||
E('span', { class: 'dl-stack' }, [E('b', {}, m ? m.title : 'Custom'), E('span', { class: 'dl-sub' }, m ? m.short : 'Set by hand')]),
|
E('span', { class: 'dl-stack' }, [
|
||||||
|
E('b', {}, m ? m.title : (legacyTitle(srv.preset) ?? 'Custom')),
|
||||||
|
E('span', { class: 'dl-sub' }, m ? m.short : legacyTitle(srv.preset) ? 'Switch to Balanced or Maximum' : 'Set by hand'),
|
||||||
|
]),
|
||||||
]),
|
]),
|
||||||
m
|
m
|
||||||
? E('div', { class: 'dl-disg-meters' }, [
|
? E('div', { class: 'dl-disg-meters' }, [
|
||||||
@@ -386,6 +437,6 @@ export const awg: Core = {
|
|||||||
overviewTile,
|
overviewTile,
|
||||||
connectBlock,
|
connectBlock,
|
||||||
qrText: (cfg) => cfg.conf,
|
qrText: (cfg) => cfg.conf,
|
||||||
appKey: { label: 'Copy AmneziaVPN key', make: (cfg) => vpnKey(cfg, `${cfg.server} · ${cfg.person} · ${cfg.name}`) },
|
appKey: { label: 'Copy AmneziaVPN config', make: (cfg) => vpnKey(cfg, cfg.server) },
|
||||||
file: { label: 'Download .conf', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) },
|
file: { label: 'Download AmneziaWG config', make: (cfg) => ({ name: cfg.filename, text: cfg.conf }) },
|
||||||
};
|
};
|
||||||
@@ -11,17 +11,20 @@ import { copyText, downloadFile } from './ui/files';
|
|||||||
import { dropdown, type MenuItem } from './ui/menu';
|
import { dropdown, type MenuItem } from './ui/menu';
|
||||||
import { drawer } from './ui/drawer';
|
import { drawer } from './ui/drawer';
|
||||||
import { attempt, notify } from './ui/toast';
|
import { attempt, notify } from './ui/toast';
|
||||||
import { svg } from './ui/layout';
|
import { liveField } from './ui/layout';
|
||||||
|
import { qrCode } from './ui/qr';
|
||||||
|
import { nameHelp } from './netcheck';
|
||||||
import { deviceStatus } from './ui/badges';
|
import { deviceStatus } from './ui/badges';
|
||||||
import { qrSvg } from '../shared/qr';
|
|
||||||
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
|
import { ago, bytes, isoDay, KIND_LABEL, KINDS, todayOf } from '../shared/format';
|
||||||
import { icon } from '../shared/icons';
|
import { icon } from '../shared/icons';
|
||||||
import { eventBy } from './events/model';
|
import { eventBy } from './events/model';
|
||||||
import { spark } from './widgets/spark';
|
import { spark } from './widgets/spark';
|
||||||
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
import { clearLogDialog, exportEvents, resetUsageDialog } from './logs';
|
||||||
import { coreFor, coreOf, type Core } from './cores';
|
import { coreFor, coreOf, type Core } from './cores';
|
||||||
|
import { plainWg } from './cores/awg';
|
||||||
import { onLiveChange } from './state/live';
|
import { onLiveChange } from './state/live';
|
||||||
import { ConnectionMap, devicePlaces, rangeControl, type MapData, type Range } from './map';
|
import { ConnectionMap, rangeControl, type Range } from './map';
|
||||||
|
import { PlacesView } from './places/render';
|
||||||
import { personUrl } from './urls';
|
import { personUrl } from './urls';
|
||||||
|
|
||||||
/** What the page that opens a device hands over. */
|
/** What the page that opens a device hands over. */
|
||||||
@@ -123,7 +126,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
let geo = o.geo;
|
let geo = o.geo;
|
||||||
let now = o.now;
|
let now = o.now;
|
||||||
let today = o.today ?? isoDay(new Date());
|
let today = o.today ?? isoDay(new Date());
|
||||||
const connect = await core.connectBlock(cfg);
|
// Phones and tablets are set up by scanning; computers and routers by a file.
|
||||||
|
const connect = await core.connectBlock(cfg, dev.kind === 'phone' || dev.kind === 'tablet' ? 'qr' : 'file');
|
||||||
const titleEl = E('div', { class: 'dl-drawer-title' });
|
const titleEl = E('div', { class: 'dl-drawer-title' });
|
||||||
const stats = E('div', {});
|
const stats = E('div', {});
|
||||||
const details = E('div', {});
|
const details = E('div', {});
|
||||||
@@ -132,6 +136,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
const showLog = (events: LogEvent[]) => {
|
const showLog = (events: LogEvent[]) => {
|
||||||
logEvents = events.filter((e) => e.device === d.id);
|
logEvents = events.filter((e) => e.device === d.id);
|
||||||
dom.content(log, deviceEvents(events, d.id, now));
|
dom.content(log, deviceEvents(events, d.id, now));
|
||||||
|
view?.update({ events });
|
||||||
};
|
};
|
||||||
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */
|
/** The page's events when it has them; otherwise a fetch (`force` after clearing). */
|
||||||
const loadLog = async (force = false) => {
|
const loadLog = async (force = false) => {
|
||||||
@@ -141,31 +146,11 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
if (ev) showLog(ev.events);
|
if (ev) showLog(ev.events);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Where this device connected from, in time order (option B): a map with its trail and the list.
|
// Where this device connected from: the map, a row per place with a strip of when it was
|
||||||
|
// there (from the log's connections), and a replay of the period on the map.
|
||||||
let range: Range = '30d';
|
let range: Range = '30d';
|
||||||
let map: ConnectionMap | null = null;
|
let map: ConnectionMap | null = null;
|
||||||
const places = E('div', { class: 'dl-dplaces' });
|
let view: PlacesView | null = null;
|
||||||
const mapData = (): MapData => ({ geo: geo!, people: [p], now: now ?? Date.now() / 1000, person: p.id, device: d.id });
|
|
||||||
const paintPlaces = () => {
|
|
||||||
if (!geo?.enabled) return;
|
|
||||||
const list = devicePlaces(mapData(), range);
|
|
||||||
dom.content(
|
|
||||||
places,
|
|
||||||
list.length
|
|
||||||
? list.map((x) =>
|
|
||||||
E('div', { class: 'dl-dplace-row' }, [
|
|
||||||
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.kind) : String(x.n)),
|
|
||||||
E('span', { class: 'dl-row-main dl-stack' }, [
|
|
||||||
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
|
|
||||||
E('span', { class: 'dl-mono dl-faint' }, x.ip),
|
|
||||||
]),
|
|
||||||
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, now)),
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const paint = () => {
|
const paint = () => {
|
||||||
dom.content(titleEl, [
|
dom.content(titleEl, [
|
||||||
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
|
E('span', { class: `dl-dcard-ic${d.online ? ' on' : ''}` }, icon(d.kind)),
|
||||||
@@ -183,7 +168,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
E('div', { class: 'dl-dstats' }, [
|
E('div', { class: 'dl-dstats' }, [
|
||||||
E('div', { class: 'dl-dstats-cell wide' }, [
|
E('div', { class: 'dl-dstats-cell wide' }, [
|
||||||
E('span', { class: 'dl-metric-label' }, 'Status'),
|
E('span', { class: 'dl-metric-label' }, 'Status'),
|
||||||
deviceStatus(d, now, 'Waiting for the first connection'),
|
deviceStatus(d, now, 'Waiting for the first connection', p),
|
||||||
]),
|
]),
|
||||||
E('div', { class: 'dl-dstats-cell' }, [
|
E('div', { class: 'dl-dstats-cell' }, [
|
||||||
E('span', { class: 'dl-metric-label' }, 'This month'),
|
E('span', { class: 'dl-metric-label' }, 'This month'),
|
||||||
@@ -221,10 +206,8 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
row('Added', `${when(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
|
row('Added', `${when(d.created)} · ${d.created_by === 'portal' ? 'from the portal' : 'by you'}`),
|
||||||
row(
|
// The whole key, copyable: it is what another WireGuard server needs to add this device by hand.
|
||||||
'Public key',
|
cfg.amnezia.client_pub_key ? copyRow('Public key', cfg.amnezia.client_pub_key) : row('Public key', '—'),
|
||||||
E('span', { class: 'dl-mono dl-faint' }, cfg.amnezia.client_pub_key ? `${cfg.amnezia.client_pub_key.slice(0, 16)}…` : '—'),
|
|
||||||
),
|
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
dom.content(foot, [
|
dom.content(foot, [
|
||||||
@@ -289,8 +272,7 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
now = st.now;
|
now = st.now;
|
||||||
today = todayOf(st.series);
|
today = todayOf(st.series);
|
||||||
paint();
|
paint();
|
||||||
map?.update(mapData());
|
view?.update({ geo: st.geo, now: st.now, person: p, device: d });
|
||||||
paintPlaces();
|
|
||||||
};
|
};
|
||||||
/** After a change made here: this drawer and the page. */
|
/** After a change made here: this drawer and the page. */
|
||||||
const changed = async () => {
|
const changed = async () => {
|
||||||
@@ -300,15 +282,22 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
|
|
||||||
const rename = () => {
|
const rename = () => {
|
||||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
|
const input = E('input', { type: 'text', class: 'cbi-input-text', value: d.name, maxlength: 48 }) as HTMLInputElement;
|
||||||
|
const taken = p.devices.filter((x) => x.id !== d.id).map((x) => x.name);
|
||||||
|
const nameRow = liveField('Name', input, () => nameHelp(input.value, taken, 'Shown in the portal and in the app.'));
|
||||||
modal(
|
modal(
|
||||||
`Rename ${d.name}`,
|
`Rename ${d.name}`,
|
||||||
[E('div', { class: 'cbi-value' }, [E('label', { class: 'cbi-value-title' }, 'Name'), E('div', { class: 'cbi-value-field' }, input)])],
|
[nameRow],
|
||||||
[
|
[
|
||||||
cancelButton(),
|
cancelButton(),
|
||||||
' ',
|
' ',
|
||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
async () => {
|
async () => {
|
||||||
|
const h = nameRow.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
|
if (await attempt(() => api.deviceUpdate(d.id, input.value, undefined), 'Renamed')) {
|
||||||
closeModal();
|
closeModal();
|
||||||
await changed();
|
await changed();
|
||||||
@@ -368,6 +357,13 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
range,
|
range,
|
||||||
220,
|
220,
|
||||||
);
|
);
|
||||||
|
const v = (view = new PlacesView(map, range, {
|
||||||
|
geo,
|
||||||
|
now: now ?? Date.now() / 1000,
|
||||||
|
person: p,
|
||||||
|
device: d,
|
||||||
|
events: o.events?.() ?? null,
|
||||||
|
}));
|
||||||
locationsSec = E('section', { class: 'dl-dsec' }, [
|
locationsSec = E('section', { class: 'dl-dsec' }, [
|
||||||
E('div', { class: 'dl-dsec-head' }, [
|
E('div', { class: 'dl-dsec-head' }, [
|
||||||
E('h4', {}, 'Locations'),
|
E('h4', {}, 'Locations'),
|
||||||
@@ -375,16 +371,14 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
range,
|
range,
|
||||||
(r) => {
|
(r) => {
|
||||||
range = r;
|
range = r;
|
||||||
map?.setRange(r);
|
v.setRange(r);
|
||||||
paintPlaces();
|
|
||||||
},
|
},
|
||||||
false,
|
false,
|
||||||
),
|
),
|
||||||
]),
|
]),
|
||||||
E('div', { class: 'dl-dmap' }, map.el),
|
E('div', { class: 'dl-dmap' }, [map.el, v.controls]),
|
||||||
places,
|
v.el,
|
||||||
]);
|
]);
|
||||||
paintPlaces();
|
|
||||||
}
|
}
|
||||||
// Connecting is what the drawer is for until the device is set up (or its configuration is old);
|
// Connecting is what the drawer is for until the device is set up (or its configuration is old);
|
||||||
// after that it goes to the bottom.
|
// after that it goes to the bottom.
|
||||||
@@ -405,10 +399,11 @@ export async function openDevice(person: Person, dev: Device, o: DeviceOpts) {
|
|||||||
const handle = drawer(titleEl, body, foot, () => {
|
const handle = drawer(titleEl, body, foot, () => {
|
||||||
clearInterval(watch);
|
clearInterval(watch);
|
||||||
off();
|
off();
|
||||||
|
view?.destroy();
|
||||||
map?.destroy();
|
map?.destroy();
|
||||||
});
|
});
|
||||||
paint();
|
paint();
|
||||||
if (map) requestAnimationFrame(() => map?.mount(mapData()));
|
if (map && view) requestAnimationFrame(() => view && map?.mount(view.mapData()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
|
/** ⋯ on a device card: quick actions (everything else is in the panel; click the card). */
|
||||||
@@ -425,8 +420,12 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
|
|||||||
modal(
|
modal(
|
||||||
`${d.name} · QR code`,
|
`${d.name} · QR code`,
|
||||||
E('div', { class: 'dl-qr-pane' }, [
|
E('div', { class: 'dl-qr-pane' }, [
|
||||||
svg(qrSvg(core.qrText(c)), 'dl-qr'),
|
qrCode(core.qrText(c)),
|
||||||
E('span', { class: 'dl-sub' }, 'Scan with AmneziaVPN or AmneziaWG on the device.'),
|
E(
|
||||||
|
'span',
|
||||||
|
{ class: 'dl-sub' },
|
||||||
|
plainWg(c) ? 'Scan with AmneziaVPN or any WireGuard app on the device.' : 'Scan with AmneziaVPN or AmneziaWG on the device.',
|
||||||
|
),
|
||||||
]),
|
]),
|
||||||
cancelButton('Close'),
|
cancelButton('Close'),
|
||||||
);
|
);
|
||||||
@@ -500,8 +499,22 @@ export function quickMenu(anchor: HTMLElement, p: Person, d: Device, o: DeviceOp
|
|||||||
|
|
||||||
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
|
/** Admin "Add device" dialog for a person; opens the new device's drawer. */
|
||||||
export function addDevice(person: Person, o: DeviceOpts) {
|
export function addDevice(person: Person, o: DeviceOpts) {
|
||||||
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: KIND_LABEL.phone, maxlength: 48 }) as HTMLInputElement;
|
const taken = person.devices.map((x) => x.name);
|
||||||
|
// The name a type gives when none is typed: "Phone", then "Phone 2" (as the portal does).
|
||||||
|
const suggest = (k: Kind) => {
|
||||||
|
const base = KIND_LABEL[k];
|
||||||
|
let n = 1;
|
||||||
|
let name = base;
|
||||||
|
while (taken.some((t) => t.toLowerCase() === name.toLowerCase())) name = `${base} ${++n}`;
|
||||||
|
return name;
|
||||||
|
};
|
||||||
let kind: Kind = 'phone';
|
let kind: Kind = 'phone';
|
||||||
|
const nameInput = E('input', { type: 'text', class: 'cbi-input-text', placeholder: suggest(kind), maxlength: 48 }) as HTMLInputElement;
|
||||||
|
const nameRow = liveField('Name', nameInput, () =>
|
||||||
|
nameInput.value.trim()
|
||||||
|
? nameHelp(nameInput.value, taken, 'Shown in the portal and in the app.')
|
||||||
|
: { text: `Named after its type: ${suggest(kind)}.`, bad: false },
|
||||||
|
);
|
||||||
const kinds = E(
|
const kinds = E(
|
||||||
'div',
|
'div',
|
||||||
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
|
{ class: 'dl-kinds', role: 'radiogroup', 'aria-label': 'Type' },
|
||||||
@@ -521,7 +534,8 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
|||||||
c.classList.toggle('on', on);
|
c.classList.toggle('on', on);
|
||||||
c.setAttribute('aria-checked', on ? 'true' : 'false');
|
c.setAttribute('aria-checked', on ? 'true' : 'false');
|
||||||
});
|
});
|
||||||
nameInput.placeholder = KIND_LABEL[k];
|
nameInput.placeholder = suggest(k);
|
||||||
|
nameRow.refresh();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
[icon(k), E('span', {}, KIND_LABEL[k])],
|
[icon(k), E('span', {}, KIND_LABEL[k])],
|
||||||
@@ -540,7 +554,7 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
|||||||
)
|
)
|
||||||
: '',
|
: '',
|
||||||
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Type'), kinds]),
|
E('div', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Type'), kinds]),
|
||||||
E('label', { class: 'dl-fld' }, [E('span', { class: 'dl-fld-label' }, 'Name'), nameInput]),
|
nameRow,
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
cancelButton(),
|
cancelButton(),
|
||||||
@@ -548,7 +562,12 @@ export function addDevice(person: Person, o: DeviceOpts) {
|
|||||||
button(
|
button(
|
||||||
'Add device',
|
'Add device',
|
||||||
async () => {
|
async () => {
|
||||||
const name = nameInput.value.trim() || nameInput.placeholder.replace(/^e\.g\. /, '');
|
const h = nameRow.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const name = nameInput.value.trim() || suggest(kind);
|
||||||
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
|
const r = await attempt(() => api.deviceCreate(person.id, name, kind));
|
||||||
if (!r) return;
|
if (!r) return;
|
||||||
closeModal();
|
closeModal();
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type { AwgCaps } from '../shared/types';
|
|||||||
import { E } from './e';
|
import { E } from './e';
|
||||||
import { icon } from '../shared/icons';
|
import { icon } from '../shared/icons';
|
||||||
|
|
||||||
export type Method = 'standard' | 'strong' | 'balanced' | 'max' | 'off';
|
export type Method = 'balanced' | 'max' | 'off';
|
||||||
/** The router features a method may need (the boolean ones of AwgCaps). */
|
/** The router features a method may need (the boolean ones of AwgCaps). */
|
||||||
export type AwgNeed = 'v2' | 'v3';
|
export type AwgNeed = 'v2' | 'v3';
|
||||||
|
|
||||||
@@ -35,32 +35,12 @@ export const METHODS: MethodInfo[] = [
|
|||||||
apps: 'Any WireGuard app',
|
apps: 'Any WireGuard app',
|
||||||
short: 'Any WireGuard app',
|
short: 'Any WireGuard app',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
id: 'standard',
|
|
||||||
title: 'Standard',
|
|
||||||
ic: 'shield',
|
|
||||||
stealth: 2,
|
|
||||||
speed: 4,
|
|
||||||
text: 'Junk packets and random headers. Gets through most VPN blocking with no speed cost.',
|
|
||||||
apps: 'Every AmneziaWG and AmneziaVPN app',
|
|
||||||
short: 'Any AmneziaWG app',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'strong',
|
|
||||||
title: 'Strong',
|
|
||||||
ic: 'shieldplus',
|
|
||||||
stealth: 3,
|
|
||||||
speed: 3,
|
|
||||||
text: 'More and larger junk packets for networks that block VPNs aggressively. Connects a little slower.',
|
|
||||||
apps: 'Every AmneziaWG and AmneziaVPN app',
|
|
||||||
short: 'Any AmneziaWG app',
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
id: 'balanced',
|
id: 'balanced',
|
||||||
title: 'Balanced',
|
title: 'Balanced',
|
||||||
ic: 'shieldplus',
|
ic: 'shield',
|
||||||
stealth: 3,
|
stealth: 3,
|
||||||
speed: 3,
|
speed: 4,
|
||||||
needs: 'v2',
|
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.',
|
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',
|
apps: 'AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps',
|
||||||
@@ -81,6 +61,17 @@ export const METHODS: MethodInfo[] = [
|
|||||||
|
|
||||||
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
|
export const methodInfo = (id: string): MethodInfo | undefined => METHODS.find((x) => x.id === id);
|
||||||
|
|
||||||
|
/** The disguise a new server gets: the strongest this router can run. */
|
||||||
|
export const defaultMethod = (caps: AwgCaps): Method => (caps.v3 ? 'max' : caps.v2 ? 'balanced' : 'off');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Servers made before 0.8 may carry the old Standard or Strong disguise
|
||||||
|
* (1.0-style junk only, which networks learned to spot). They keep running;
|
||||||
|
* the picker offers Balanced or Maximum instead. The title for such a server, or null.
|
||||||
|
*/
|
||||||
|
export const legacyTitle = (preset: string): string | null =>
|
||||||
|
preset === 'standard' ? 'Standard (old)' : preset === 'strong' ? 'Strong (old)' : null;
|
||||||
|
|
||||||
const NEEDS: Record<AwgNeed, string> = {
|
const NEEDS: Record<AwgNeed, string> = {
|
||||||
v2: 'Needs AmneziaWG 2.0 or newer on the router (kmod-amneziawg and amneziawg-tools from July 2025 on).',
|
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).',
|
v3: 'Needs AmneziaWG 3.1 on the router (kmod-amneziawg and amneziawg-tools 3.1).',
|
||||||
@@ -148,7 +139,9 @@ export function methodPicker(
|
|||||||
E(
|
E(
|
||||||
'div',
|
'div',
|
||||||
{ class: 'dl-method-foot' },
|
{ class: 'dl-method-foot' },
|
||||||
ok ? [icon('phone'), E('span', {}, m.apps)] : [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
|
ok
|
||||||
|
? [icon(m.id === 'off' ? 'wireguard' : 'amneziawg'), E('span', {}, m.apps)]
|
||||||
|
: [icon('alert'), E('span', {}, (installed ? NEEDS : NEEDS_NONE)[m.needs!])],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ const CATEGORY: Record<string, LogCategory> = {
|
|||||||
person_changed: 'people',
|
person_changed: 'people',
|
||||||
paused: 'people',
|
paused: 'people',
|
||||||
resumed: 'people',
|
resumed: 'people',
|
||||||
|
expiring: 'people',
|
||||||
|
expired_kept: 'people',
|
||||||
portal_blocked: 'problems',
|
portal_blocked: 'problems',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ const EVENT_TONE: Record<string, string> = {
|
|||||||
person_removed: '',
|
person_removed: '',
|
||||||
paused: 'warn',
|
paused: 'warn',
|
||||||
resumed: 'ok',
|
resumed: 'ok',
|
||||||
|
expiring: 'warn',
|
||||||
|
expired_kept: '',
|
||||||
portal_blocked: 'bad',
|
portal_blocked: 'bad',
|
||||||
person_changed: '',
|
person_changed: '',
|
||||||
devices_removed: 'warn',
|
devices_removed: 'warn',
|
||||||
@@ -35,6 +37,8 @@ const EVENT_ICON: Record<string, string> = {
|
|||||||
person_changed: 'edit',
|
person_changed: 'edit',
|
||||||
paused: 'pause',
|
paused: 'pause',
|
||||||
resumed: 'play',
|
resumed: 'play',
|
||||||
|
expiring: 'calendar',
|
||||||
|
expired_kept: 'calendar',
|
||||||
};
|
};
|
||||||
|
|
||||||
function eventIcon(st: Names, e: LogEvent): string {
|
function eventIcon(st: Names, e: LogEvent): string {
|
||||||
@@ -135,6 +139,10 @@ export function eventText(st: Pick<Status, 'people'>, e: LogEvent): Node[] {
|
|||||||
case 'person_changed':
|
case 'person_changed':
|
||||||
// The detail lists changed fields by their option names (device_limit, expire_action).
|
// The detail lists changed fields by their option names (device_limit, expire_action).
|
||||||
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
|
return [...you('changed'), kind('person'), b(who), ...(detail ? [m(` · ${detail.replace(/_/g, ' ')}`)] : [])];
|
||||||
|
case 'expiring':
|
||||||
|
return [kind('Person'), b(who), m(`’s access ends in ${e.detail ?? 'a few days'}`)];
|
||||||
|
case 'expired_kept':
|
||||||
|
return [kind('Person'), b(who), m(`’s end date passed (${e.detail ?? ''}) · access kept`)];
|
||||||
case 'paused':
|
case 'paused':
|
||||||
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
|
return [kind('Person'), b(who), m(` paused — ${e.detail ?? ''}`)];
|
||||||
case 'resumed':
|
case 'resumed':
|
||||||
|
|||||||
@@ -107,21 +107,27 @@ export async function inviteCard(p: Invitee, server: string, opts: { title?: str
|
|||||||
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
|
const file = new File([png], `${p.id}-invite.png`, { type: 'image/png' });
|
||||||
const url = URL.createObjectURL(png);
|
const url = URL.createObjectURL(png);
|
||||||
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
|
const nav = navigator as Navigator & { canShare?: (d: unknown) => boolean };
|
||||||
const canShare = !!nav.canShare?.({ files: [file] });
|
// Three tiers: the card as a file, the link through the share sheet (older
|
||||||
|
// Android, Firefox on phones), else a download of the card.
|
||||||
|
const canShareFile = !!nav.canShare?.({ files: [file] });
|
||||||
|
const canShareLink = !canShareFile && typeof nav.share === 'function' && (nav.canShare?.({ url: href }) ?? true);
|
||||||
const close = () => {
|
const close = () => {
|
||||||
URL.revokeObjectURL(url);
|
URL.revokeObjectURL(url);
|
||||||
closeModal();
|
closeModal();
|
||||||
};
|
};
|
||||||
const share = canShare
|
const shareIt = async (data: ShareData) => {
|
||||||
? button(
|
|
||||||
[icon('link'), ' Share card'],
|
|
||||||
async () => {
|
|
||||||
try {
|
try {
|
||||||
await nav.share({ files: [file], title: `Invite ${p.name}` });
|
await nav.share(data);
|
||||||
} catch {
|
} catch {
|
||||||
/* cancelled */
|
/* cancelled */
|
||||||
}
|
}
|
||||||
},
|
};
|
||||||
|
const share = canShareFile
|
||||||
|
? button([icon('link'), ' Share card'], () => shareIt({ files: [file], title: `Invite ${p.name}` }), 'positive')
|
||||||
|
: canShareLink
|
||||||
|
? button(
|
||||||
|
[icon('link'), ' Share link'],
|
||||||
|
() => shareIt({ url: href, title: `Invite ${p.name}`, text: `Your personal VPN link` }),
|
||||||
'positive',
|
'positive',
|
||||||
)
|
)
|
||||||
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
|
: button([icon('download'), ' Download card'], () => downloadFile(file.name, png), 'positive');
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import { E } from './e';
|
|||||||
import { ago, initials } from '../shared/format';
|
import { ago, initials } from '../shared/format';
|
||||||
import { icon, iconSvg } from '../shared/icons';
|
import { icon, iconSvg } from '../shared/icons';
|
||||||
import { onNavigate } from './ui/nav';
|
import { onNavigate } from './ui/nav';
|
||||||
|
import { isDark } from './ui/theme';
|
||||||
|
import { placeKey, shimmerOpacity } from './places/model';
|
||||||
|
|
||||||
// mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it.
|
// mapcn requires maplibre-gl ^6 (the globe projection came with 5): an ES module, its worker beside it.
|
||||||
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist';
|
const MAPLIBRE = 'https://unpkg.com/maplibre-gl@6.14.0/dist';
|
||||||
@@ -70,18 +72,14 @@ function loadMapLibre(host: HTMLElement): Promise<any> {
|
|||||||
return loading;
|
return loading;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isDark(): boolean {
|
|
||||||
const attr = document.documentElement.getAttribute('data-darkmode');
|
|
||||||
if (attr != null) return attr === 'true';
|
|
||||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A click on a marker brings the map at least this close (a city). */
|
/** A click on a marker brings the map at least this close (a city). */
|
||||||
const CLICK_ZOOM = 10;
|
const CLICK_ZOOM = 10;
|
||||||
/** Places closer than this are one city: a click shows them together at city level. */
|
/** Places closer than this are one city: a click shows them together at city level. */
|
||||||
const CITY_KM = 30;
|
const CITY_KM = 30;
|
||||||
/** Screen distance at which two markers stand clear of each other (the server's plate and an avatar, with room). */
|
/** Screen distance at which two markers stand clear of each other (the server's plate and an avatar, with room). */
|
||||||
const PART_PX = 62;
|
const PART_PX = 62;
|
||||||
|
/** The replay's dotted arc: a dot every this many screen pixels. */
|
||||||
|
const DOT_PX = 4;
|
||||||
/** Below these zooms plates turn compact (a continent) or mid-sized (a country). */
|
/** Below these zooms plates turn compact (a continent) or mid-sized (a country). */
|
||||||
const LOD_FAR = 4.5;
|
const LOD_FAR = 4.5;
|
||||||
const LOD_MID = 7;
|
const LOD_MID = 7;
|
||||||
@@ -146,7 +144,7 @@ export function visiblePoints(data: MapData, range: Range): GeoPoint[] {
|
|||||||
if (data.device && p.device !== data.device) continue;
|
if (data.device && p.device !== data.device) continue;
|
||||||
if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue;
|
if (range === 'online' ? !p.online : data.now - p.ts > WINDOW[range]) continue;
|
||||||
// Where people are: each device once. A person's page: every city each device was in.
|
// Where people are: each device once. A person's page: every city each device was in.
|
||||||
const key = data.device ? `${p.city}|${p.cc}` : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device;
|
const key = data.device ? placeKey(p) : data.person ? `${p.device}|${p.city}|${p.cc}` : p.device;
|
||||||
const cur = best.get(key);
|
const cur = best.get(key);
|
||||||
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(key, p);
|
if (!cur || (p.online && !cur.online) || (p.online === cur.online && p.ts > cur.ts)) best.set(key, p);
|
||||||
}
|
}
|
||||||
@@ -200,6 +198,17 @@ export class ConnectionMap {
|
|||||||
/** The folded keys the layers were last filtered for (a filter only changes when they do). */
|
/** The folded keys the layers were last filtered for (a filter only changes when they do). */
|
||||||
private hiddenKey = '';
|
private hiddenKey = '';
|
||||||
private focused: string | null = null;
|
private focused: string | null = null;
|
||||||
|
/** Destroyed: a mount still waiting for the library stops there instead of drawing into a dropped element. */
|
||||||
|
private dead = false;
|
||||||
|
/** A device's places (its window) by placeKey: what the replay switches on and off. */
|
||||||
|
private places = new Map<
|
||||||
|
string,
|
||||||
|
{ el: HTMLElement; tile: HTMLElement; label: HTMLElement; when: HTMLElement | null; g: Group; n: number; kind: string }
|
||||||
|
>();
|
||||||
|
/** The replay of a device's moves: the place the light is on and the time under it; null outside it. */
|
||||||
|
private replaying: { active: string | null; when: string } | null = null;
|
||||||
|
/** The replay's arc dots, kept for a style reload (a theme switch) in the middle of a move. */
|
||||||
|
private bandDots: unknown[] = [];
|
||||||
private card: HTMLElement;
|
private card: HTMLElement;
|
||||||
readonly el: HTMLElement;
|
readonly el: HTMLElement;
|
||||||
private status: HTMLElement;
|
private status: HTMLElement;
|
||||||
@@ -223,6 +232,7 @@ export class ConnectionMap {
|
|||||||
this.status.textContent = (e as Error).message;
|
this.status.textContent = (e as Error).message;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (this.dead) return;
|
||||||
this.map = new this.gl.Map({
|
this.map = new this.gl.Map({
|
||||||
container: this.el,
|
container: this.el,
|
||||||
style: isDark() ? STYLE_DARK : STYLE_LIGHT,
|
style: isDark() ? STYLE_DARK : STYLE_LIGHT,
|
||||||
@@ -285,14 +295,13 @@ export class ConnectionMap {
|
|||||||
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
|
'circle-stroke-opacity': ['case', ['get', 'online'], 0.35, 0.15],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
// A device's trail through its places in time order (its window): fine gray dots.
|
// A device's move in its replay: a dotted arc, transparent but where the shimmer is (band, bandAt).
|
||||||
this.map.addSource('dl-trail', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
|
this.map.addSource('dl-band', { type: 'geojson', data: { type: 'FeatureCollection', features: this.bandDots } });
|
||||||
this.map.addLayer({
|
this.map.addLayer({
|
||||||
id: 'dl-trail',
|
id: 'dl-band',
|
||||||
type: 'line',
|
type: 'circle',
|
||||||
source: 'dl-trail',
|
source: 'dl-band',
|
||||||
layout: { 'line-join': 'round', 'line-cap': 'round' },
|
paint: { 'circle-radius': 1.4, 'circle-color': LIVE, 'circle-opacity': 0 },
|
||||||
paint: { 'line-color': RECENT, 'line-width': 1.5, 'line-opacity': 0.85, 'line-dasharray': [0, 2.5] },
|
|
||||||
});
|
});
|
||||||
// mapcn's MapArc paint (width 2, opacity 0.85, rounded) with the Basic Arc example's dashes;
|
// mapcn's MapArc paint (width 2, opacity 0.85, rounded) with the Basic Arc example's dashes;
|
||||||
// recent arcs under live ones.
|
// recent arcs under live ones.
|
||||||
@@ -321,6 +330,7 @@ export class ConnectionMap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
destroy() {
|
destroy() {
|
||||||
|
this.dead = true;
|
||||||
this.dropCard();
|
this.dropCard();
|
||||||
for (const p of this.piles.values()) p.marker.remove();
|
for (const p of this.piles.values()) p.marker.remove();
|
||||||
this.piles.clear();
|
this.piles.clear();
|
||||||
@@ -334,7 +344,7 @@ export class ConnectionMap {
|
|||||||
private groups(pts: GeoPoint[]): Group[] {
|
private groups(pts: GeoPoint[]): Group[] {
|
||||||
const map = new Map<string, Group>();
|
const map = new Map<string, Group>();
|
||||||
for (const p of pts) {
|
for (const p of pts) {
|
||||||
const key = `${p.person}|${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`;
|
const key = `${p.person}|${placeKey(p)}`;
|
||||||
let g = map.get(key);
|
let g = map.get(key);
|
||||||
if (!g) {
|
if (!g) {
|
||||||
g = {
|
g = {
|
||||||
@@ -416,31 +426,16 @@ export class ConnectionMap {
|
|||||||
this.add(el, [home.lon, home.lat], true);
|
this.add(el, [home.lon, home.lat], true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// A device's places joined oldest to newest, each step bowed like an arc.
|
// A device's places, numbered as the list under the map (its strips say when it was where).
|
||||||
const steps = data.device ? [...placed].sort((a, b) => Number(a.g.online) - Number(b.g.online) || a.g.ts - b.g.ts) : [];
|
const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [placeKey(p), p.n]) : []);
|
||||||
this.map.getSource('dl-trail')?.setData({
|
|
||||||
type: 'FeatureCollection',
|
|
||||||
features:
|
|
||||||
steps.length > 1
|
|
||||||
? [
|
|
||||||
{
|
|
||||||
type: 'Feature',
|
|
||||||
properties: {},
|
|
||||||
geometry: { type: 'LineString', coordinates: steps.slice(1).flatMap((x, i) => arc(steps[i].at, x.at)) },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: [],
|
|
||||||
});
|
|
||||||
const numbers = new Map(data.device ? devicePlaces(data, this.range).map((p) => [`${p.city}|${p.cc}`, p.n]) : []);
|
|
||||||
|
|
||||||
this.people = [];
|
this.people = [];
|
||||||
|
this.places.clear();
|
||||||
for (const { g, at } of placed) {
|
for (const { g, at } of placed) {
|
||||||
const n = g.points.length;
|
const n = g.points.length;
|
||||||
const person = data.people.find((x) => x.id === g.person);
|
const person = data.people.find((x) => x.id === g.person);
|
||||||
if (data.person) {
|
if (data.person) {
|
||||||
const el = data.device
|
const el = data.device ? this.deviceMarker(g, at, person, numbers.get(placeKey(g)) ?? 0) : this.placeMarker(g, at, person);
|
||||||
? this.stepMarker(g, at, person, numbers.get(`${g.points[0].city}|${g.points[0].cc}`) ?? 0)
|
|
||||||
: this.placeMarker(g, at, person);
|
|
||||||
this.add(el, at);
|
this.add(el, at);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -820,23 +815,111 @@ export class ConnectionMap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A place in a device's window: the live one as a blue tile with the device's icon and
|
* A place in a device's window: on, a blue tile with the device's icon and "now" (the live
|
||||||
* "now", the earlier ones as small gray tiles numbered by recency (1 = most recent).
|
* place); off, a small gray tile numbered by recency (1 = most recent). One element whose
|
||||||
|
* state changes, so the replay can move the light from place to place (paintPlace).
|
||||||
*/
|
*/
|
||||||
private stepMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement {
|
private deviceMarker(g: Group, at: [number, number], person: Person | undefined, n: number): HTMLElement {
|
||||||
if (g.online) return this.placeMarker(g, at, person);
|
const kind = person?.devices.find((d) => d.id === g.points[0].device)?.kind ?? 'other';
|
||||||
const when = ago(g.ts, this.data!.now);
|
const tile = E('span', { class: 'dl-mk-tile' });
|
||||||
const el = E('button', { type: 'button', class: 'dl-mk place step', 'aria-label': `${n}: ${g.city || 'an unknown city'}, ${when}` }, [
|
const label = E('span', { class: 'dl-mk-label below' });
|
||||||
E('span', { class: 'dl-mk-tile sm' }, String(n)),
|
const el = E('button', { type: 'button', class: 'dl-mk place step' }, [tile, label]);
|
||||||
E('span', { class: 'dl-mk-label below' }, [g.city || g.cc || '?', ` · ${when}`]),
|
|
||||||
]);
|
|
||||||
el.addEventListener('click', (ev) => {
|
el.addEventListener('click', (ev) => {
|
||||||
ev.stopPropagation();
|
ev.stopPropagation();
|
||||||
this.openPopup(g, at, el);
|
this.openPopup(g, at, el);
|
||||||
});
|
});
|
||||||
|
const key = placeKey(g);
|
||||||
|
this.places.set(key, { el, tile, label, when: null, g, n, kind });
|
||||||
|
this.paintPlace(key, false);
|
||||||
return el;
|
return el;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A device's place as the replay has it (or, outside it, as it is now); `animate` lets the light come in. */
|
||||||
|
private paintPlace(key: string, animate: boolean) {
|
||||||
|
const x = this.places.get(key);
|
||||||
|
if (!x) return;
|
||||||
|
const r = this.replaying;
|
||||||
|
const on = r ? r.active === key : x.g.online;
|
||||||
|
const was = x.el.classList.contains('online');
|
||||||
|
const city = x.g.city || x.g.cc || '?';
|
||||||
|
x.el.classList.toggle('online', on);
|
||||||
|
x.el.classList.toggle('faded', !!r && !on);
|
||||||
|
x.tile.classList.toggle('sm', !on);
|
||||||
|
if (on || !x.n) x.tile.innerHTML = iconSvg(x.kind, 'dl-mk-tile-ic');
|
||||||
|
else x.tile.textContent = String(x.n);
|
||||||
|
x.when = null;
|
||||||
|
if (on) {
|
||||||
|
// In the replay the time goes on the city's line (two lines would run into a place below).
|
||||||
|
x.when = E('span', { class: `dl-mk-when${r ? ' inline' : ''}` }, r ? r.when : 'now');
|
||||||
|
x.label.replaceChildren(city, r ? ' · ' : '', x.when);
|
||||||
|
} else x.label.replaceChildren(`${city} · ${x.g.online ? 'now' : ago(x.g.ts, this.data!.now)}`);
|
||||||
|
const when = on ? (r ? r.when : 'now') : x.g.online ? 'now' : ago(x.g.ts, this.data!.now);
|
||||||
|
x.el.setAttribute('aria-label', `${x.n ? `${x.n}: ` : ''}${x.g.city || 'an unknown city'}, ${when}`);
|
||||||
|
if (animate && on && !was) {
|
||||||
|
x.el.classList.remove('arrive');
|
||||||
|
void x.el.offsetWidth;
|
||||||
|
x.el.classList.add('arrive');
|
||||||
|
setTimeout(() => x.el.classList.remove('arrive'), 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The replay of a device's moves (its window): `active` is the place (placeKey) the light is on,
|
||||||
|
* `when` the time under it; null goes back to how things are now. A change of place animates.
|
||||||
|
*/
|
||||||
|
replay(state: { active: string | null; when: string } | null, animate = true) {
|
||||||
|
const prev = this.replaying;
|
||||||
|
this.replaying = state;
|
||||||
|
// The same place a moment later: only its time changes.
|
||||||
|
if (prev && state && prev.active === state.active) {
|
||||||
|
const x = state.active ? this.places.get(state.active) : null;
|
||||||
|
if (x?.when) x.when.textContent = state.when;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const key of this.places.keys()) if (key !== state?.active) this.paintPlace(key, animate);
|
||||||
|
if (state?.active) this.paintPlace(state.active, animate);
|
||||||
|
// Tiles grow and shrink: spread the crowded ones again, now and once they have their size.
|
||||||
|
this.declutter();
|
||||||
|
setTimeout(() => this.declutter(), 320);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A device's place lit while its row under the map is hovered; null for none. */
|
||||||
|
hoverPlace(key: string | null) {
|
||||||
|
for (const [k, x] of this.places) x.el.classList.toggle('hl', k === key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The dots of the arc between two places (a move in the replay), as many as fit on screen at
|
||||||
|
* DOT_PX apart, all transparent until bandAt() brings the shimmer in; no arguments clear them.
|
||||||
|
*/
|
||||||
|
band(from?: [number, number], to?: [number, number]) {
|
||||||
|
this.bandDots = [];
|
||||||
|
if (this.map && from && to) {
|
||||||
|
const pts = arc(from, to);
|
||||||
|
const px = pts.map((c) => this.map.project(c));
|
||||||
|
const len = [0];
|
||||||
|
for (let i = 1; i < px.length; i++) len.push(len[i - 1] + Math.hypot(px[i].x - px[i - 1].x, px[i].y - px[i - 1].y));
|
||||||
|
const total = len[len.length - 1];
|
||||||
|
const n = Math.max(2, Math.round(total / DOT_PX));
|
||||||
|
let j = 0;
|
||||||
|
for (let i = 0; i <= n; i++) {
|
||||||
|
const d = (total * i) / n;
|
||||||
|
while (j < len.length - 2 && len[j + 1] < d) j++;
|
||||||
|
const t = len[j + 1] > len[j] ? (d - len[j]) / (len[j + 1] - len[j]) : 0;
|
||||||
|
const at = [pts[j][0] + (pts[j + 1][0] - pts[j][0]) * t, pts[j][1] + (pts[j + 1][1] - pts[j][1]) * t];
|
||||||
|
this.bandDots.push({ type: 'Feature', properties: { pos: i / n }, geometry: { type: 'Point', coordinates: at } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!this.map?.getLayer('dl-band')) return;
|
||||||
|
this.map.setPaintProperty('dl-band', 'circle-opacity', 0);
|
||||||
|
this.map.getSource('dl-band').setData({ type: 'FeatureCollection', features: this.bandDots });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The shimmer along the band's arc, its middle at `c` (a share of the arc: see places/model). */
|
||||||
|
bandAt(c: number) {
|
||||||
|
if (this.map?.getLayer('dl-band')) this.map.setPaintProperty('dl-band', 'circle-opacity', shimmerOpacity(c));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One person in focus (hovering any of their markers): all their places and arcs stay,
|
* One person in focus (hovering any of their markers): all their places and arcs stay,
|
||||||
* everyone else fades, and a card lists their devices with where and when.
|
* everyone else fades, and a card lists their devices with where and when.
|
||||||
@@ -894,9 +977,17 @@ export class ConnectionMap {
|
|||||||
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
|
const b = new this.gl.LngLatBounds(pts[0], pts[0]);
|
||||||
pts.forEach((c) => b.extend(c));
|
pts.forEach((c) => b.extend(c));
|
||||||
const h = this.el.clientHeight || 380;
|
const h = this.el.clientHeight || 380;
|
||||||
|
// A person's and a device's places have their name (and "now") under the tile; a device's
|
||||||
|
// window has the replay's controls in its top corner.
|
||||||
|
const below = !!this.data?.person;
|
||||||
const opts = {
|
const opts = {
|
||||||
// Just enough room for the labels: the server's chip above its plate, a place's name above its dot.
|
// Just enough room for the labels: the server's chip above its plate, a place's name above its dot.
|
||||||
padding: { top: Math.min(60, h / 5), bottom: Math.min(40, h / 8), left: 48, right: 48 },
|
padding: {
|
||||||
|
top: this.data?.device ? Math.min(56, h / 4) : Math.min(60, h / 5),
|
||||||
|
bottom: below ? Math.min(52, h / 4) : Math.min(40, h / 8),
|
||||||
|
left: 48,
|
||||||
|
right: 48,
|
||||||
|
},
|
||||||
// A person's page shows a little more around a single place.
|
// A person's page shows a little more around a single place.
|
||||||
maxZoom: this.data?.person ? 11 : 12,
|
maxZoom: this.data?.person ? 11 : 12,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -91,3 +91,226 @@ export function portalPortHelp(port: number, taken: PortHold[], ipLinks: boolean
|
|||||||
const who = holder(port + 1, taken);
|
const who = holder(port + 1, taken);
|
||||||
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
|
return who ? { text: `Links on IP addresses also need ${port + 1}, used by ${who}. Choose another port.`, bad: true } : h;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- other fields, mirroring the router's rules (dawnline.util, schema, core) ---------- */
|
||||||
|
|
||||||
|
/** Characters, not UTF-16 units or bytes: what the router counts (util.ulength). */
|
||||||
|
export const chars = (s: string): number => Array.from(s).length;
|
||||||
|
|
||||||
|
const NAME_MAX = 48;
|
||||||
|
const BAD_NAME = /[<>"\\\u0000-\u001f\u007f]/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A name people see (util.valid_name): 1–48 characters, none of < > " \.
|
||||||
|
* `taken` are names already used where it must be unique (case-insensitive).
|
||||||
|
*/
|
||||||
|
export function nameHelp(s: string, taken: string[] = [], good = ''): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'Enter a name.', bad: true };
|
||||||
|
if (chars(s) > NAME_MAX) return { text: `Up to ${NAME_MAX} characters (${chars(s)} now).`, bad: true };
|
||||||
|
if (BAD_NAME.test(s)) return { text: 'Names can’t contain < > " or \\.', bad: true };
|
||||||
|
if (taken.some((x) => x.toLowerCase() === t.toLowerCase())) return { text: `“${t}” already exists — pick another name.`, bad: true };
|
||||||
|
return { text: good, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A circle's name: like a name, up to 32 characters. */
|
||||||
|
export function circleNameHelp(s: string, taken: string[] = []): Help {
|
||||||
|
if (chars(s) > 32) return { text: `Up to 32 characters (${chars(s)} now).`, bad: true };
|
||||||
|
return nameHelp(s, taken, 'Shown on the person cards.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const HOSTNAME = /^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
||||||
|
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
||||||
|
|
||||||
|
export function isIpv4(s: string): boolean {
|
||||||
|
const m = IPV4.exec(s);
|
||||||
|
return !!m && m.slice(1).every((x) => Number(x) <= 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isIpv6(s: string): boolean {
|
||||||
|
return /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(s) && !/:::/.test(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The public address of a server or the portal (util.valid_host): a hostname
|
||||||
|
* or an IP address, nothing else. `port` names what devices connect to when
|
||||||
|
* it is fine; `empty` is what an empty field means (null: it is required).
|
||||||
|
*/
|
||||||
|
export function hostHelp(s: string, port?: number, empty: string | null = null): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return empty != null ? { text: empty, bad: false } : { text: 'Enter a hostname or IP address.', bad: true };
|
||||||
|
if (/^[a-z]+:\/\//i.test(t)) return { text: 'Leave out https:// — just the name.', bad: true };
|
||||||
|
if (/\/.*/.test(t)) return { text: 'Just the name, without a path.', bad: true };
|
||||||
|
if (/^[^:\[]+:\d+$/.test(t)) return { text: 'Just the name, without a port (the port is on AmneziaWG).', bad: true };
|
||||||
|
if (/\s/.test(t)) return { text: 'A hostname has no spaces.', bad: true };
|
||||||
|
if (t.length > 253 || !(HOSTNAME.test(t) || isIpv4(t) || isIpv6(t))) return { text: 'Use a hostname or an IP address.', bad: true };
|
||||||
|
const shown = isIpv6(t) ? `[${t}]` : t;
|
||||||
|
return { text: port ? `Devices connect to ${shown}:${port}.` : `Links use ${shown}.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The DNS list a server hands to devices (rpc/servers.uc dns_list): IPs, comma-separated; empty = this router. */
|
||||||
|
export function dnsHelp(s: string, routerAddr: string): Help {
|
||||||
|
const items = s.split(/[ ,]+/).filter(Boolean);
|
||||||
|
if (!items.length)
|
||||||
|
return { text: `This router (${routerAddr}): queries go where your home network sends them, and home names work.`, bad: false };
|
||||||
|
const bad = items.find((x) => !isIpv4(x) && !isIpv6(x));
|
||||||
|
if (bad) return { text: `“${bad}” is not an IP address. Separate several with commas.`, bad: true };
|
||||||
|
return { text: `Devices use ${items.join(' and ')} — home names and your LAN’s DNS filters no longer apply to them.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** MTU (rpc/servers.uc check_mtu): empty = automatic, else 1280–1500. */
|
||||||
|
export function mtuHelp(s: string, mtus: { computer: number; phone: number }): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t)
|
||||||
|
return {
|
||||||
|
text: `Automatic by device type and disguise: ${mtus.computer} for computers and routers, ${mtus.phone} for phones and tablets.`,
|
||||||
|
bad: false,
|
||||||
|
};
|
||||||
|
if (!/^\d{1,4}$/.test(t) || Number(t) < 1280 || Number(t) > 1500)
|
||||||
|
return { text: 'MTU must be 1280–1500, or empty for automatic.', bad: true };
|
||||||
|
const n = Number(t);
|
||||||
|
return { text: `Computers and routers get ${n}, phones and tablets ${Math.min(n, 1280)}.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep-alive (rpc/servers.uc): 0–600 s; empty = 25. */
|
||||||
|
export function keepaliveHelp(s: string): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'Default: a packet every 25 s keeps NAT open and “Connected” accurate.', bad: false };
|
||||||
|
if (!/^\d{1,3}$/.test(t) || Number(t) > 600) return { text: 'Use 0–600 seconds.', bad: true };
|
||||||
|
if (Number(t) === 0) return { text: 'Off: NAT may close the tunnel when idle, and “Connected” lags.', bad: false };
|
||||||
|
return { text: `Devices send a packet every ${t} s to keep NAT open (a little battery on phones).`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Device limit (core.create_person): 1–32; `have` is how many they have now (an edit). */
|
||||||
|
export function limitHelp(s: string, have = 0): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!/^\d{1,2}$/.test(t) || Number(t) < 1 || Number(t) > 32) return { text: 'Use 1–32.', bad: true };
|
||||||
|
const n = Number(t);
|
||||||
|
if (have > n)
|
||||||
|
return { text: `Already has ${have} devices: remove ${have - n === 1 ? 'one' : `${have - n}`} first, or allow more.`, bad: true };
|
||||||
|
return { text: `They can add ${n} device${n === 1 ? '' : 's'} themselves.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Monthly data in GB (core.create_person): empty = unlimited, else 0–100000. */
|
||||||
|
export function quotaHelp(s: string, monthly = true): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'Optional. No data limit.', bad: false };
|
||||||
|
const n = Number(t);
|
||||||
|
if (!/^\d+(\.\d+)?$/.test(t) || n < 0 || n > 100000) return { text: 'A number of GB, up to 100000.', bad: true };
|
||||||
|
if (n === 0) return { text: 'Optional. No data limit.', bad: false };
|
||||||
|
return { text: monthly ? `Paused after ${t} GB this month, resumed on the 1st.` : `Paused after ${t} GB in total.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An end date (YYYY-MM-DD) against the router's day; empty = none. */
|
||||||
|
export function expiresHelp(
|
||||||
|
s: string,
|
||||||
|
today: string,
|
||||||
|
daysLeft: (d: string, t: string) => number | null,
|
||||||
|
date: (d: string) => string,
|
||||||
|
): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'Optional. No end date.', bad: false };
|
||||||
|
const left = daysLeft(t, today);
|
||||||
|
if (left == null) return { text: 'Use a date.', bad: true };
|
||||||
|
if (left < 0) return { text: 'That date has passed: access would end at once.', bad: true };
|
||||||
|
return { text: left === 1 ? `Access ends today (${date(t)}).` : `Access ends in ${left} days (${date(t)}).`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A home service's address (rpc/home.uc): IPv4; `homeNets` warn when it is outside every home network. */
|
||||||
|
export function ipv4Help(s: string, inHome: ((ip: string) => boolean) | null = null): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'The device’s address at home.', bad: true };
|
||||||
|
if (!isIpv4(t)) return { text: 'Use an IPv4 address, like 192.168.1.10.', bad: true };
|
||||||
|
if (inHome && !inHome(t)) return { text: `${t} is not in any home network of this server: nobody would reach it.`, bad: false };
|
||||||
|
return { text: '', bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A service's ports: empty = all, else numbers 1–65535. */
|
||||||
|
export function portsHelp(s: string): Help {
|
||||||
|
const items = s.split(/[ ,]+/).filter(Boolean);
|
||||||
|
if (!items.length) return { text: 'All ports.', bad: false };
|
||||||
|
const bad = items.find((x) => !/^\d{1,5}$/.test(x) || Number(x) < 1 || Number(x) > 65535);
|
||||||
|
if (bad) return { text: `“${bad}” is not a port (1–65535).`, bad: true };
|
||||||
|
return { text: `Port${items.length === 1 ? '' : 's'} ${items.join(', ')}.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The portal's redirect for unknown links (schema portal_redirect): a full http(s) URL, or empty. */
|
||||||
|
export function urlHelp(s: string): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'Wrong links get a bare “Not found”.', bad: false };
|
||||||
|
if (!/^https?:\/\//i.test(t)) return { text: 'Must start with http:// or https://.', bad: true };
|
||||||
|
if (t.length > 300 || !/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(t))
|
||||||
|
return { text: 'Not a usable address (no spaces or quotes).', bad: true };
|
||||||
|
return { text: 'Wrong links are sent there instead of a “Not found”.', bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The home domain for device hostnames (schema domain): lowercase letters, digits, dashes, dots. */
|
||||||
|
export function domainHelp(s: string, example = 'phone.myata'): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
// Empty keeps the default (the router stores nothing then).
|
||||||
|
if (!t) return { text: `The default, lan: devices get names like ${example}.lan.`, bad: false };
|
||||||
|
if (!/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(t))
|
||||||
|
return { text: /[A-Z]/.test(t) ? 'Lowercase only.' : 'Lowercase letters, digits, dashes and dots.', bad: true };
|
||||||
|
return { text: `Devices get names like ${example}.${t}.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fallback DNS for home-names devices: an IPv4 address, or empty for none. */
|
||||||
|
export function fallbackDnsHelp(s: string): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!t) return { text: 'None: without the tunnel those devices have no DNS.', bad: false };
|
||||||
|
if (!isIpv4(t)) return { text: 'Use an IPv4 address, or leave it empty.', bad: true };
|
||||||
|
return { text: `${t} takes over when the tunnel is down.`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The daily update time (schema update_time): HH:MM. */
|
||||||
|
export function timeHelp(s: string): Help {
|
||||||
|
const t = s.trim();
|
||||||
|
if (!/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(t)) return { text: 'Use HH:MM, 00:00–23:59.', bad: true };
|
||||||
|
return { text: `Runs within an hour after ${t} (router time).`, bad: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A public address checked on the router as it is typed (rpc endpoint_probe:
|
||||||
|
* where it points, CGNAT, Cloudflare), debounced so a keystroke is not a
|
||||||
|
* lookup. `help()` is the row's: the syntax first (hostHelp), then the
|
||||||
|
* router's verdict once it arrives, "Checking…" in between.
|
||||||
|
*/
|
||||||
|
export function endpointProbe(
|
||||||
|
get: () => { host: string; port: number; id?: string },
|
||||||
|
probe: (host: string, id: string | undefined, port: number) => Promise<{ text: string; status?: string }>,
|
||||||
|
onResult: () => void,
|
||||||
|
opts: { empty?: string | null; idle?: () => string } = {},
|
||||||
|
) {
|
||||||
|
let timer = 0;
|
||||||
|
let asked = '';
|
||||||
|
let result: { host: string; text: string; bad: boolean } | null = null;
|
||||||
|
const schedule = () => {
|
||||||
|
const { host } = get();
|
||||||
|
const h = hostHelp(host, get().port, opts.empty ?? null);
|
||||||
|
if (h.bad || !host.trim() || host.trim() === result?.host) return;
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = window.setTimeout(async () => {
|
||||||
|
const want = host.trim();
|
||||||
|
asked = want;
|
||||||
|
try {
|
||||||
|
const { id, port } = get();
|
||||||
|
const r = await probe(want, id, port);
|
||||||
|
if (asked !== want) return;
|
||||||
|
result = { host: want, text: r.text, bad: r.status === 'error' };
|
||||||
|
} catch {
|
||||||
|
if (asked !== want) return;
|
||||||
|
result = { host: want, text: h.text, bad: false };
|
||||||
|
}
|
||||||
|
onResult();
|
||||||
|
}, 700);
|
||||||
|
};
|
||||||
|
const help = (): Help => {
|
||||||
|
const { host, port } = get();
|
||||||
|
const h = hostHelp(host, port, opts.empty ?? null);
|
||||||
|
if (h.bad || !host.trim()) return h;
|
||||||
|
if (result && result.host === host.trim()) return { text: result.text, bad: result.bad };
|
||||||
|
const idle = opts.idle?.();
|
||||||
|
return { text: idle ? `${idle} Checking where it points…` : `${h.text} Checking where it points…`, bad: false };
|
||||||
|
};
|
||||||
|
return { help, schedule };
|
||||||
|
}
|
||||||
@@ -8,7 +8,7 @@ import { api } from '../api';
|
|||||||
import { svg } from '../ui/layout';
|
import { svg } from '../ui/layout';
|
||||||
import { attachTip } from '../ui/tooltip';
|
import { attachTip } from '../ui/tooltip';
|
||||||
import { icon } from '../../shared/icons';
|
import { icon } from '../../shared/icons';
|
||||||
import { ago, bits, bytes, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
|
import { ago, bits, bytes, date, daysLeft, endsIn, endsSoon, initials, todayOf } from '../../shared/format';
|
||||||
import { ConnectionMap, rangeControl, type Range } from '../map';
|
import { ConnectionMap, rangeControl, type Range } from '../map';
|
||||||
import { personUrl } from '../urls';
|
import { personUrl } from '../urls';
|
||||||
import { eventRow } from '../events/render';
|
import { eventRow } from '../events/render';
|
||||||
@@ -17,6 +17,8 @@ import { repaint } from '../state/poller';
|
|||||||
import { daysTile, speedTile } from '../widgets/tiles';
|
import { daysTile, speedTile } from '../widgets/tiles';
|
||||||
import { coreOf } from '../cores';
|
import { coreOf } from '../cores';
|
||||||
import { healthNotices, runFix } from '../widgets/health';
|
import { healthNotices, runFix } from '../widgets/health';
|
||||||
|
import { attempt } from '../ui/toast';
|
||||||
|
import { isIpv4 } from '../netcheck';
|
||||||
import { onNavigate } from '../ui/nav';
|
import { onNavigate } from '../ui/nav';
|
||||||
|
|
||||||
interface Attention {
|
interface Attention {
|
||||||
@@ -48,6 +50,9 @@ function attention(st: Status): Attention[] {
|
|||||||
else {
|
else {
|
||||||
const left = daysLeft(p.expires, today);
|
const left = daysLeft(p.expires, today);
|
||||||
if (endsSoon(p, left)) out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ${endsIn(left as number)}.`] });
|
if (endsSoon(p, left)) out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s access ${endsIn(left as number)}.`] });
|
||||||
|
// "Keep access" at the end date: nothing changes on its own, so it is said here.
|
||||||
|
else if (left != null && left < 0 && p.expire_action === 'notify')
|
||||||
|
out.push({ tone: '', text: [link(personUrl(p.id), p.name), `’s end date passed (${date(p.expires)}) · access kept.`] });
|
||||||
if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
|
if (p.quota_limit && p.quota_used >= p.quota_limit * 0.9)
|
||||||
out.push({ tone: '', text: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] });
|
out.push({ tone: '', text: [link(personUrl(p.id), p.name), ' has used 90% of the data limit.'] });
|
||||||
}
|
}
|
||||||
@@ -64,12 +69,40 @@ function attention(st: Status): Attention[] {
|
|||||||
]
|
]
|
||||||
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
|
: [`${stale.length} devices need their configuration again (networks or DNS changed).`],
|
||||||
});
|
});
|
||||||
|
// A server that gives devices an IPv4 that is no longer the router's: one click puts the new one in.
|
||||||
|
for (const s of st.servers)
|
||||||
|
if (st.wan && isIpv4(s.endpoint) && s.endpoint !== st.wan)
|
||||||
|
out.push({
|
||||||
|
tone: 'warn',
|
||||||
|
text: [
|
||||||
|
`Public address changed: ${s.name} still gives devices ${s.endpoint}, the router is ${st.wan} now. `,
|
||||||
|
E(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
class: 'dl-fix',
|
||||||
|
click: async (ev: Event) => {
|
||||||
|
const b = ev.currentTarget as HTMLButtonElement;
|
||||||
|
b.disabled = true;
|
||||||
|
await attempt(
|
||||||
|
() => api.serverUpdate(s.id, { endpoint: st.wan }),
|
||||||
|
`${s.name} uses ${st.wan} now — devices need their configuration again`,
|
||||||
|
);
|
||||||
|
b.disabled = false;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
'Use the new address',
|
||||||
|
),
|
||||||
|
' A DDNS name would follow it by itself.',
|
||||||
|
],
|
||||||
|
});
|
||||||
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
|
if (st.servers.some((s) => s.lan_like) && st.like_home.error)
|
||||||
out.push({
|
out.push({
|
||||||
tone: 'warn',
|
tone: 'warn',
|
||||||
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/diagnostics'), 'Details')],
|
text: [`Internet through the LAN is off: ${st.like_home.error} `, link(L.url('admin/network/dawnline/diagnostics'), 'Details')],
|
||||||
});
|
});
|
||||||
if (!st.settings.portal_enabled)
|
// Only while setting up: an admin who keeps the portal off has decided so.
|
||||||
|
if (!st.settings.portal_enabled && !st.people.length)
|
||||||
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
|
out.push({ tone: '', text: ['The personal portal is off. ', link(L.url('admin/network/dawnline/settings'), 'Turn on')] });
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -78,6 +111,8 @@ export class ServerOverview {
|
|||||||
st!: Status;
|
st!: Status;
|
||||||
el = E('div', { class: 'dl-srvov' });
|
el = E('div', { class: 'dl-srvov' });
|
||||||
map: ConnectionMap | null = null;
|
map: ConnectionMap | null = null;
|
||||||
|
/** Whether the map card was made for locations on (a map) or off (a link to Settings); null before the first. */
|
||||||
|
mapOn: boolean | null = null;
|
||||||
range: Range = 'online';
|
range: Range = 'online';
|
||||||
parts: Record<string, HTMLElement> = {};
|
parts: Record<string, HTMLElement> = {};
|
||||||
healthAt = 0;
|
healthAt = 0;
|
||||||
@@ -91,11 +126,11 @@ export class ServerOverview {
|
|||||||
/** Build once; later calls to update() keep the map instance. */
|
/** Build once; later calls to update() keep the map instance. */
|
||||||
mount(st: Status): HTMLElement {
|
mount(st: Status): HTMLElement {
|
||||||
this.st = scoped(st, this.srvId);
|
this.st = scoped(st, this.srvId);
|
||||||
for (const k of ['health', 'bento', 'side', 'activity']) this.parts[k] = E('div', {});
|
for (const k of ['health', 'bento', 'map', 'side', 'activity']) this.parts[k] = E('div', {});
|
||||||
dom.content(this.el, [
|
dom.content(this.el, [
|
||||||
this.parts.health,
|
this.parts.health,
|
||||||
this.parts.bento,
|
this.parts.bento,
|
||||||
this.mapCard(),
|
this.parts.map,
|
||||||
E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]),
|
E('div', { class: 'dl-grid2' }, [this.parts.activity, this.parts.side]),
|
||||||
]);
|
]);
|
||||||
this.paint();
|
this.paint();
|
||||||
@@ -107,7 +142,6 @@ export class ServerOverview {
|
|||||||
update(st: Status, quiet = false) {
|
update(st: Status, quiet = false) {
|
||||||
this.st = scoped(st, this.srvId);
|
this.st = scoped(st, this.srvId);
|
||||||
this.paint(quiet);
|
this.paint(quiet);
|
||||||
this.map?.update(this.mapData());
|
|
||||||
// Health checks cost more than a status call: once a minute is plenty.
|
// Health checks cost more than a status call: once a minute is plenty.
|
||||||
if (Date.now() - this.healthAt > 60_000) void this.loadHealth();
|
if (Date.now() - this.healthAt > 60_000) void this.loadHealth();
|
||||||
}
|
}
|
||||||
@@ -135,6 +169,21 @@ export class ServerOverview {
|
|||||||
return { geo: this.st.geo, people: this.st.people, now: this.st.now };
|
return { geo: this.st.geo, people: this.st.people, now: this.st.now };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The map keeps its instance between updates. Its card is made again only
|
||||||
|
* when locations were turned on or off, or when the map was freed: leaving
|
||||||
|
* the page frees it, and Outline brings this same overview back on return.
|
||||||
|
*/
|
||||||
|
paintMap() {
|
||||||
|
const on = this.st.geo.enabled;
|
||||||
|
if (on === this.mapOn && (!on || this.map)) {
|
||||||
|
this.map?.update(this.mapData());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.mapOn = on;
|
||||||
|
dom.content(this.parts.map, this.mapCard());
|
||||||
|
}
|
||||||
|
|
||||||
mapCard(): HTMLElement {
|
mapCard(): HTMLElement {
|
||||||
const st = this.st;
|
const st = this.st;
|
||||||
const head = E('div', { class: 'dl-panel-head pad' }, [
|
const head = E('div', { class: 'dl-panel-head pad' }, [
|
||||||
@@ -148,6 +197,8 @@ export class ServerOverview {
|
|||||||
this.map?.setRange(r);
|
this.map?.setRange(r);
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
this.map?.destroy();
|
||||||
|
this.map = null;
|
||||||
if (!st.geo.enabled)
|
if (!st.geo.enabled)
|
||||||
return E('div', { class: 'dl-panel flush' }, [
|
return E('div', { class: 'dl-panel flush' }, [
|
||||||
head,
|
head,
|
||||||
@@ -157,27 +208,27 @@ export class ServerOverview {
|
|||||||
'.',
|
'.',
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
this.map?.destroy();
|
const map = (this.map = new ConnectionMap(
|
||||||
this.map = new ConnectionMap(
|
|
||||||
{
|
{
|
||||||
openPerson: (id) => (location.href = personUrl(id)),
|
openPerson: (id) => (location.href = personUrl(id)),
|
||||||
openDevice: (id, dev) => (location.href = personUrl(id, dev)),
|
openDevice: (id, dev) => (location.href = personUrl(id, dev)),
|
||||||
},
|
},
|
||||||
this.range,
|
this.range,
|
||||||
);
|
));
|
||||||
// A WebGL map outlives the page's DOM unless it is told: free it when
|
// A WebGL map outlives the page's DOM unless it is told: free it when
|
||||||
// Outline navigates away (the page object itself may be reused).
|
// Outline navigates away. The page object is reused on return, and its
|
||||||
|
// next update finds the map gone and makes the card again (paintMap).
|
||||||
const offNav = onNavigate(() => {
|
const offNav = onNavigate(() => {
|
||||||
offNav();
|
offNav();
|
||||||
this.map?.destroy();
|
map.destroy();
|
||||||
this.map = null;
|
if (this.map === map) this.map = null;
|
||||||
});
|
});
|
||||||
const legend = E('div', { class: 'dl-map-legend' }, [
|
const legend = E('div', { class: 'dl-map-legend' }, [
|
||||||
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
|
E('span', {}, [E('i', { class: 'line live' }), 'Live tunnel']),
|
||||||
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
|
E('span', {}, [E('i', { class: 'line' }), 'Seen recently']),
|
||||||
]);
|
]);
|
||||||
const wrap = E('div', { class: 'dl-map-wrap' }, [this.map.el, legend]);
|
const wrap = E('div', { class: 'dl-map-wrap' }, [map.el, legend]);
|
||||||
requestAnimationFrame(() => this.map!.mount(this.mapData()));
|
requestAnimationFrame(() => map.mount(this.mapData()));
|
||||||
return E('div', { class: 'dl-panel flush' }, [head, wrap]);
|
return E('div', { class: 'dl-panel flush' }, [head, wrap]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,6 +236,7 @@ export class ServerOverview {
|
|||||||
const st = this.st;
|
const st = this.st;
|
||||||
const srv = st.servers[0];
|
const srv = st.servers[0];
|
||||||
|
|
||||||
|
this.paintMap();
|
||||||
repaint(
|
repaint(
|
||||||
this.parts.bento,
|
this.parts.bento,
|
||||||
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
|
E('div', { class: 'dl-bento' }, [this.onlineTile(), this.speedTile(), coreOf(srv).overviewTile(srv), this.monthTile()]),
|
||||||
@@ -390,6 +442,12 @@ export class ServerOverview {
|
|||||||
|
|
||||||
/** The last 30 days, today on the right, with the peak. */
|
/** The last 30 days, today on the right, with the peak. */
|
||||||
monthTile(): HTMLElement {
|
monthTile(): HTMLElement {
|
||||||
return daysTile(this.st.series, '');
|
// Who used the most this month (the People sort has it too, a click away).
|
||||||
|
const top = [...this.st.people]
|
||||||
|
.map((p) => [p, p.month[0] + p.month[1]] as const)
|
||||||
|
.filter(([, n]) => n > 0)
|
||||||
|
.sort((a, b) => b[1] - a[1])
|
||||||
|
.slice(0, 2);
|
||||||
|
return daysTile(this.st.series, top.length ? `Most: ${top.map(([p, n]) => `${p.name} ${bytes(n)}`).join(' · ')}` : '');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,10 @@ import { copyPersonLink, inviteCard } from '../invite';
|
|||||||
import { personUrl } from '../urls';
|
import { personUrl } from '../urls';
|
||||||
import { scoped } from '../state/scope';
|
import { scoped } from '../state/scope';
|
||||||
import { createPoller, focusInside, type Poller } from '../state/poller';
|
import { createPoller, focusInside, type Poller } from '../state/poller';
|
||||||
|
import { onNavigate } from '../ui/nav';
|
||||||
import { accessPicker } from '../widgets/access-picker';
|
import { accessPicker } from '../widgets/access-picker';
|
||||||
|
import { firstBad, liveField } from '../ui/layout';
|
||||||
|
import { expiresHelp, limitHelp, nameHelp, quotaHelp } from '../netcheck';
|
||||||
import { coreFor } from '../cores';
|
import { coreFor } from '../cores';
|
||||||
import { icon } from '../../shared/icons';
|
import { icon } from '../../shared/icons';
|
||||||
import {
|
import {
|
||||||
@@ -38,6 +41,22 @@ import {
|
|||||||
|
|
||||||
type Sid = string;
|
type Sid = string;
|
||||||
|
|
||||||
|
/** Per-browser conveniences (a tab, a sort): storage may be absent or refuse. */
|
||||||
|
function remembered(key: string): string | null {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(key);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function remember(key: string, value: string) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(key, value);
|
||||||
|
} catch {
|
||||||
|
/* no storage */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
|
/** Device slots as a row of segments (one per allowed device, used ones lit) and "2 of 10". */
|
||||||
function slotBar(p: Person): HTMLElement {
|
function slotBar(p: Person): HTMLElement {
|
||||||
const used = p.devices.length;
|
const used = p.devices.length;
|
||||||
@@ -89,9 +108,14 @@ export class PeoplePage {
|
|||||||
/** The cards, one per person, in the current sort order. */
|
/** The cards, one per person, in the current sort order. */
|
||||||
private list: HTMLElement = E('div', { class: 'dl-plist', role: 'list' });
|
private list: HTMLElement = E('div', { class: 'dl-plist', role: 'list' });
|
||||||
// `?filter=online` (from Overview) preselects a tab.
|
// `?filter=online` (from Overview) preselects a tab.
|
||||||
|
// The tab and the sort are remembered in this browser; ?filter= (from Overview) wins for the tab.
|
||||||
filter: Filter =
|
filter: Filter =
|
||||||
(['all', 'online', 'attention', 'paused'] as Filter[]).find((f) => f === new URLSearchParams(location.search).get('filter')) ?? 'all';
|
(['all', 'online', 'attention', 'paused'] as Filter[]).find(
|
||||||
sort: SortBy = 'seen';
|
(f) => f === (new URLSearchParams(location.search).get('filter') ?? remembered('dl.people.filter')),
|
||||||
|
) ?? 'all';
|
||||||
|
sort: SortBy = (['seen', 'name', 'usage'] as SortBy[]).find((x) => x === remembered('dl.people.sort')) ?? 'seen';
|
||||||
|
/** What the admin typed into Find (name, note, device, address). */
|
||||||
|
query = '';
|
||||||
noFooter = true;
|
noFooter = true;
|
||||||
/** Set when shown as a server's People section: only that server's people. */
|
/** Set when shown as a server's People section: only that server's people. */
|
||||||
serverId: string | null = null;
|
serverId: string | null = null;
|
||||||
@@ -208,11 +232,37 @@ export class PeoplePage {
|
|||||||
'aria-label': 'Sort',
|
'aria-label': 'Sort',
|
||||||
change: (ev: Event) => {
|
change: (ev: Event) => {
|
||||||
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
|
page.sort = (ev.target as HTMLSelectElement).value as SortBy;
|
||||||
|
remember('dl.people.sort', page.sort);
|
||||||
page.decorate();
|
page.decorate();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
[E('option', { value: 'seen' }, 'Last seen'), E('option', { value: 'name' }, 'Name'), E('option', { value: 'usage' }, 'Usage')],
|
[
|
||||||
|
E('option', { value: 'seen', selected: page.sort === 'seen' ? 'selected' : null }, 'Last seen'),
|
||||||
|
E('option', { value: 'name', selected: page.sort === 'name' ? 'selected' : null }, 'Name'),
|
||||||
|
E('option', { value: 'usage', selected: page.sort === 'usage' ? 'selected' : null }, 'Usage'),
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
// Find, once the list is long enough to need it; "/" focuses it.
|
||||||
|
const find = E('input', {
|
||||||
|
type: 'search',
|
||||||
|
class: 'cbi-input-text dl-people-find',
|
||||||
|
placeholder: 'Find…',
|
||||||
|
'aria-label': 'Find a person or device',
|
||||||
|
hidden: st.people.length > 8 ? null : 'hidden',
|
||||||
|
input: (ev: Event) => {
|
||||||
|
page.query = (ev.target as HTMLInputElement).value.trim().toLowerCase();
|
||||||
|
page.decorate();
|
||||||
|
},
|
||||||
|
}) as HTMLInputElement;
|
||||||
|
const onSlash = (ev: KeyboardEvent) => {
|
||||||
|
const t = ev.target as HTMLElement;
|
||||||
|
if (ev.key === '/' && !find.hidden && !['INPUT', 'TEXTAREA', 'SELECT'].includes(t?.tagName) && !t?.isContentEditable) {
|
||||||
|
ev.preventDefault();
|
||||||
|
find.focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('keydown', onSlash);
|
||||||
|
onNavigate(() => document.removeEventListener('keydown', onSlash));
|
||||||
const wrap = E('div', { class: 'dl-root' }, [
|
const wrap = E('div', { class: 'dl-root' }, [
|
||||||
page.serverId
|
page.serverId
|
||||||
? ''
|
? ''
|
||||||
@@ -234,6 +284,7 @@ export class PeoplePage {
|
|||||||
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
|
E('div', { class: 'dl-seg dl-people-tabs', role: 'tablist' }),
|
||||||
// Sort and add stay together on the right, wrapping as one group.
|
// Sort and add stay together on the right, wrapping as one group.
|
||||||
E('div', { class: 'dl-toolbar-end' }, [
|
E('div', { class: 'dl-toolbar-end' }, [
|
||||||
|
find,
|
||||||
sort,
|
sort,
|
||||||
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
|
page.serverId ? button([icon('plus'), ' Add person'], () => page.openCreate(), 'add') : '',
|
||||||
]),
|
]),
|
||||||
@@ -290,6 +341,7 @@ export class PeoplePage {
|
|||||||
class: f === this.filter ? 'on' : '',
|
class: f === this.filter ? 'on' : '',
|
||||||
click: () => {
|
click: () => {
|
||||||
this.filter = f;
|
this.filter = f;
|
||||||
|
remember('dl.people.filter', f);
|
||||||
this.decorate();
|
this.decorate();
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -298,10 +350,14 @@ export class PeoplePage {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
const q = this.query;
|
||||||
|
const hay = (p: Person) =>
|
||||||
|
[p.name, p.note ?? '', ...p.devices.flatMap((d) => [d.name, d.address, d.hostname, d.endpoint])].join(' ').toLowerCase();
|
||||||
const match = (p: Person) => {
|
const match = (p: Person) => {
|
||||||
if (this.filter === 'online' && !p.online) return false;
|
if (this.filter === 'online' && !p.online) return false;
|
||||||
if (this.filter === 'attention' && !attn(p)) return false;
|
if (this.filter === 'attention' && !attn(p)) return false;
|
||||||
if (this.filter === 'paused' && !paused(p)) return false;
|
if (this.filter === 'paused' && !paused(p)) return false;
|
||||||
|
if (q && !hay(p).includes(q)) return false;
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
// Whatever the sort: people who can connect, then those held by a limit or an end
|
// Whatever the sort: people who can connect, then those held by a limit or an end
|
||||||
@@ -382,7 +438,7 @@ export class PeoplePage {
|
|||||||
icon(d.kind),
|
icon(d.kind),
|
||||||
E('span', { class: 'dl-chip-name' }, d.name),
|
E('span', { class: 'dl-chip-name' }, d.name),
|
||||||
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
|
!d.handshake && !d.disabled ? E('span', { class: 'dl-chip-tag' }, 'not set up') : '',
|
||||||
// Online shows as the green dashed chip (.dl-chip.live); no dots.
|
// Online shows as the green chip (.dl-chip.live); no dots.
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -392,16 +448,14 @@ export class PeoplePage {
|
|||||||
'button',
|
'button',
|
||||||
{
|
{
|
||||||
type: 'button',
|
type: 'button',
|
||||||
// Just a "+": the slots above say how many there are.
|
|
||||||
class: 'dl-chip add',
|
class: 'dl-chip add',
|
||||||
'aria-label': 'Add device',
|
title: free > 0 ? 'Add device' : 'Over the limit: admins can still add',
|
||||||
title: free > 0 ? 'Add device' : 'Add device · over the limit, admins can still add',
|
|
||||||
click: (ev: Event) => {
|
click: (ev: Event) => {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
addDevice(p, this.deviceOpts(p));
|
addDevice(p, this.deviceOpts(p));
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
icon('plus'),
|
[icon('plus'), 'Add device'],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -612,7 +666,15 @@ export class PeoplePage {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement;
|
const name = E('input', { type: 'text', class: 'cbi-input-text', placeholder: 'e.g. Myata', maxlength: 48 }) as HTMLInputElement;
|
||||||
const access = accessPicker('internet');
|
// The last person's access and data limit come back pre-filled (most are alike).
|
||||||
|
const last = (() => {
|
||||||
|
try {
|
||||||
|
return JSON.parse(remembered('dl.person.last') ?? '{}') as { access?: Person['access']; quota?: string };
|
||||||
|
} catch {
|
||||||
|
return {} as { access?: Person['access']; quota?: string };
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
const access = accessPicker(last.access ?? 'internet');
|
||||||
const limit = E('input', {
|
const limit = E('input', {
|
||||||
type: 'number',
|
type: 'number',
|
||||||
class: 'cbi-input-text',
|
class: 'cbi-input-text',
|
||||||
@@ -627,6 +689,7 @@ export class PeoplePage {
|
|||||||
min: 0,
|
min: 0,
|
||||||
step: 'any',
|
step: 'any',
|
||||||
placeholder: 'Unlimited',
|
placeholder: 'Unlimited',
|
||||||
|
value: last.quota ?? '',
|
||||||
}) as HTMLInputElement;
|
}) as HTMLInputElement;
|
||||||
const quick = (label: string, months: number) =>
|
const quick = (label: string, months: number) =>
|
||||||
E(
|
E(
|
||||||
@@ -636,6 +699,7 @@ export class PeoplePage {
|
|||||||
class: 'cbi-button cbi-button-neutral',
|
class: 'cbi-button cbi-button-neutral',
|
||||||
click: () => {
|
click: () => {
|
||||||
expires.value = months ? addMonthsClamped(todayOf(st.series), months) : '';
|
expires.value = months ? addMonthsClamped(todayOf(st.series), months) : '';
|
||||||
|
expires.dispatchEvent(new Event('change'));
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
label,
|
label,
|
||||||
@@ -655,44 +719,62 @@ export class PeoplePage {
|
|||||||
E('label', { class: 'cbi-value-title' }, label),
|
E('label', { class: 'cbi-value-title' }, label),
|
||||||
E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']),
|
E('div', { class: 'cbi-value-field' }, [w, help ? E('div', { class: 'cbi-value-description' }, help) : '']),
|
||||||
]);
|
]);
|
||||||
|
// Each field says what its value means, or what is wrong, as it is typed; Create refuses what the router would.
|
||||||
|
const today = todayOf(st.series);
|
||||||
|
const nameRow = liveField('Name', name, () => nameHelp(name.value, [], 'Shown in their portal and apps.'));
|
||||||
|
const limitRow = liveField('Devices', limit, () => limitHelp(limit.value));
|
||||||
|
const expRow = liveField(
|
||||||
|
'End date',
|
||||||
|
expires,
|
||||||
|
() => expiresHelp(expires.value, today, daysLeft, date),
|
||||||
|
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
|
||||||
|
);
|
||||||
|
const quotaRow = liveField('Monthly data (GB)', quota, () => quotaHelp(quota.value));
|
||||||
|
// The quick buttons set the date without an input event.
|
||||||
|
expires.addEventListener('change', () => expRow.refresh());
|
||||||
|
const portalOn = st.settings.portal_enabled;
|
||||||
|
|
||||||
modal(
|
modal(
|
||||||
'Add person',
|
'Add person',
|
||||||
[
|
[
|
||||||
row('Name', name),
|
nameRow,
|
||||||
server ? row('Server', server) : '',
|
server ? row('Server', server) : '',
|
||||||
E('div', { class: 'cbi-value dl-block' }, [
|
E('div', { class: 'cbi-value dl-block' }, [
|
||||||
E('label', { class: 'cbi-value-title' }, 'Access'),
|
E('label', { class: 'cbi-value-title' }, 'Access'),
|
||||||
E('div', { class: 'cbi-value-field' }, access.el),
|
E('div', { class: 'cbi-value-field' }, access.el),
|
||||||
]),
|
]),
|
||||||
row('Devices', limit, 'How many devices they can add themselves.'),
|
limitRow,
|
||||||
row(
|
expRow,
|
||||||
'End date',
|
quotaRow,
|
||||||
E('div', { class: 'dl-actions' }, [expires, quick('1 month', 1), quick('3 months', 3), quick('1 year', 12), quick('None', 0)]),
|
|
||||||
'Optional.',
|
|
||||||
),
|
|
||||||
row('Monthly data (GB)', quota, 'Optional. They are paused when it runs out and resumed next month.'),
|
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
cancelButton(),
|
cancelButton(),
|
||||||
' ',
|
' ',
|
||||||
button(
|
button(
|
||||||
'Create and copy link',
|
// Without the portal there is no link to copy.
|
||||||
|
portalOn ? 'Create and copy link' : 'Create',
|
||||||
async () => {
|
async () => {
|
||||||
|
const bad = firstBad([nameRow, limitRow, expRow, quotaRow]);
|
||||||
|
if (bad) {
|
||||||
|
notify(bad, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const r = await attempt(() =>
|
const r = await attempt(() =>
|
||||||
api.personCreate(
|
api.personCreate(
|
||||||
name.value.trim(),
|
name.value.trim(),
|
||||||
'',
|
'',
|
||||||
server?.value ?? srv.id,
|
server?.value ?? srv.id,
|
||||||
access.get(),
|
access.get(),
|
||||||
String(Number(limit.value) || st.settings.default_device_limit),
|
limit.value.trim(),
|
||||||
expires.value,
|
expires.value,
|
||||||
quota.value.trim(),
|
quota.value.trim(),
|
||||||
'month',
|
'month',
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (!r) return;
|
if (!r) return;
|
||||||
if (r.link) await copyText(r.link, 'Personal link copied');
|
remember('dl.person.last', JSON.stringify({ access: access.get(), quota: quota.value.trim() }));
|
||||||
|
// After the await some browsers refuse the clipboard: the card has its own Copy.
|
||||||
|
if (r.link) await copyText(r.link, 'Personal link copied', true);
|
||||||
this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name);
|
this.showCreated(r.id, name.value.trim(), r.link, st.servers.find((x) => x.id === (server?.value ?? srv.id))?.name ?? srv.name);
|
||||||
await this.refresh();
|
await this.refresh();
|
||||||
},
|
},
|
||||||
@@ -711,10 +793,31 @@ export class PeoplePage {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// No portal, no link: the two ways on from here, as buttons.
|
||||||
|
const p = this.person(id);
|
||||||
modal(
|
modal(
|
||||||
`${name} is ready`,
|
`${name} is ready`,
|
||||||
[E('p', {}, 'Created. Turn on the personal portal in Settings to get a link, or add devices for them here.')],
|
[E('p', {}, 'Created. Turn on the personal portal in Settings to get a link, or add devices for them here.')],
|
||||||
[E('button', { class: 'cbi-button cbi-button-positive', click: closeModal }, 'Done')],
|
[
|
||||||
|
E('button', { class: 'cbi-button cbi-button-neutral', click: closeModal }, 'Done'),
|
||||||
|
' ',
|
||||||
|
E(
|
||||||
|
'a',
|
||||||
|
{ class: 'cbi-button cbi-button-neutral', href: `${L.url('admin/network/dawnline/settings')}?section=portal` },
|
||||||
|
'Open Settings',
|
||||||
|
),
|
||||||
|
' ',
|
||||||
|
p
|
||||||
|
? button(
|
||||||
|
'Add device',
|
||||||
|
() => {
|
||||||
|
closeModal();
|
||||||
|
addDevice(p, this.deviceOpts(p));
|
||||||
|
},
|
||||||
|
'positive',
|
||||||
|
)
|
||||||
|
: '',
|
||||||
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,7 @@ export function devicesPart(page: PersonPage): HTMLElement {
|
|||||||
E('span', { class: 'dl-dcard-ic' }, icon(d.kind)),
|
E('span', { class: 'dl-dcard-ic' }, icon(d.kind)),
|
||||||
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
|
E('button', { type: 'button', class: 'dl-dcard-title', click: () => open(d) }, [
|
||||||
E('b', {}, d.name),
|
E('b', {}, d.name),
|
||||||
deviceStatus(d, now),
|
deviceStatus(d, now, undefined, p),
|
||||||
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
|
d.config_stale ? E('span', { class: 'dl-pill warn dl-stale' }, 'Update config') : '',
|
||||||
]),
|
]),
|
||||||
more(d),
|
more(d),
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
// Person page dialogs: rename, note, when access ends, new link, invite, delete.
|
// Person page dialogs: rename, note, when access ends, move to a server, new link, invite, delete.
|
||||||
|
|
||||||
import { E } from '../../e';
|
import { E } from '../../e';
|
||||||
import { api } from '../../api';
|
import { api } from '../../api';
|
||||||
import { button } from '../../ui/button';
|
import { button } from '../../ui/button';
|
||||||
import { cancelButton, closeModal, confirmDialog, modal } from '../../ui/modal';
|
import { cancelButton, closeModal, confirmDialog, modal } from '../../ui/modal';
|
||||||
import { copyText } from '../../ui/files';
|
import { copyText } from '../../ui/files';
|
||||||
import { attempt } from '../../ui/toast';
|
import { attempt, notify } from '../../ui/toast';
|
||||||
|
import { liveField } from '../../ui/layout';
|
||||||
|
import { nameHelp } from '../../netcheck';
|
||||||
import { inviteCard } from '../../invite';
|
import { inviteCard } from '../../invite';
|
||||||
import { peopleUrl } from '../../urls';
|
import { peopleUrl } from '../../urls';
|
||||||
import type { PersonPage } from './index';
|
import type { PersonPage } from './index';
|
||||||
@@ -126,15 +128,21 @@ export function endSettings(page: PersonPage) {
|
|||||||
|
|
||||||
export function rename(page: PersonPage) {
|
export function rename(page: PersonPage) {
|
||||||
const input = E('input', { type: 'text', class: 'cbi-input-text', value: page.p.name, maxlength: 48 }) as HTMLInputElement;
|
const input = E('input', { type: 'text', class: 'cbi-input-text', value: page.p.name, maxlength: 48 }) as HTMLInputElement;
|
||||||
|
const nameRow = liveField('Name', input, () => nameHelp(input.value, [], 'Shown in their portal and apps.'));
|
||||||
modal(
|
modal(
|
||||||
'Rename',
|
'Rename',
|
||||||
[field('Name', input)],
|
[nameRow],
|
||||||
[
|
[
|
||||||
cancelButton(),
|
cancelButton(),
|
||||||
' ',
|
' ',
|
||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
async () => {
|
async () => {
|
||||||
|
const h = nameRow.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
// The dialog stays open on a refusal, with the name still typed.
|
// The dialog stays open on a refusal, with the name still typed.
|
||||||
if (await page.patch({ name: input.value.trim() }, 'Renamed')) closeModal();
|
if (await page.patch({ name: input.value.trim() }, 'Renamed')) closeModal();
|
||||||
},
|
},
|
||||||
@@ -145,6 +153,45 @@ export function rename(page: PersonPage) {
|
|||||||
setTimeout(() => input.select(), 50);
|
setTimeout(() => input.select(), 50);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Another server: every device gets an address there and needs its configuration again. */
|
||||||
|
export function moveToServer(page: PersonPage) {
|
||||||
|
const p = page.p;
|
||||||
|
const others = page.st.servers.filter((s) => s.id !== p.server);
|
||||||
|
const sel = E(
|
||||||
|
'select',
|
||||||
|
{ class: 'cbi-input-select' },
|
||||||
|
others.map((s) => E('option', { value: s.id }, `${s.name} · ${s.endpoint || 'no address'}:${s.port}`)),
|
||||||
|
) as HTMLSelectElement;
|
||||||
|
const n = p.devices.length;
|
||||||
|
modal(
|
||||||
|
`Move ${p.name} to another server`,
|
||||||
|
[
|
||||||
|
field('Server', sel),
|
||||||
|
E(
|
||||||
|
'p',
|
||||||
|
{ class: 'dl-muted' },
|
||||||
|
n
|
||||||
|
? `${n} device${n === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${n === 1 ? 'it imports its' : 'they import their'} configuration again (from the personal link or from you). Circles and home networks of the old server are left behind.`
|
||||||
|
: 'They have no devices yet: nothing else changes.',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
cancelButton(),
|
||||||
|
' ',
|
||||||
|
button(
|
||||||
|
'Move',
|
||||||
|
async () => {
|
||||||
|
if (await page.patch({ server: sel.value }, `Moved to ${others.find((s) => s.id === sel.value)?.name ?? 'the server'}`)) {
|
||||||
|
closeModal();
|
||||||
|
if (n) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'positive',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function remove(page: PersonPage) {
|
export async function remove(page: PersonPage) {
|
||||||
const p = page.p;
|
const p = page.p;
|
||||||
const ok = await confirmDialog(
|
const ok = await confirmDialog(
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { icon } from '../../../shared/icons';
|
|||||||
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
|
import { ago, bytes, date, initials, isoDay } from '../../../shared/format';
|
||||||
import { copyPersonLink } from '../../invite';
|
import { copyPersonLink } from '../../invite';
|
||||||
import { daysTile, speedTile } from '../../widgets/tiles';
|
import { daysTile, speedTile } from '../../widgets/tiles';
|
||||||
import { editNote, invite, newLink, remove, rename } from './dialogs';
|
import { editNote, invite, moveToServer, newLink, remove, rename } from './dialogs';
|
||||||
import type { PersonPage } from './index';
|
import type { PersonPage } from './index';
|
||||||
|
|
||||||
export function headPart(page: PersonPage): HTMLElement {
|
export function headPart(page: PersonPage): HTMLElement {
|
||||||
@@ -21,6 +21,8 @@ export function headPart(page: PersonPage): HTMLElement {
|
|||||||
const menu: (MenuItem | null)[] = [
|
const menu: (MenuItem | null)[] = [
|
||||||
{ label: 'Rename', icon: icon('edit'), run: () => rename(page) },
|
{ label: 'Rename', icon: icon('edit'), run: () => rename(page) },
|
||||||
{ label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => editNote(page) },
|
{ label: p.note ? 'Edit note' : 'Add note', icon: icon('file'), run: () => editNote(page) },
|
||||||
|
// With one server there is nowhere to move to.
|
||||||
|
...(st.servers.length > 1 ? [{ label: 'Move to server…', icon: icon('server'), run: () => moveToServer(page) }] : []),
|
||||||
...(portal
|
...(portal
|
||||||
? [
|
? [
|
||||||
null,
|
null,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import { devicesPart } from './devices';
|
|||||||
import { limitsPart } from './limits';
|
import { limitsPart } from './limits';
|
||||||
import { activityPart, placesPart } from './activity';
|
import { activityPart, placesPart } from './activity';
|
||||||
|
|
||||||
type Part = 'head' | 'devices' | 'traffic' | 'places' | 'activity' | 'limits';
|
type Part = 'crumbs' | 'head' | 'devices' | 'traffic' | 'places' | 'activity' | 'limits';
|
||||||
|
|
||||||
interface Loaded {
|
interface Loaded {
|
||||||
st: Status;
|
st: Status;
|
||||||
@@ -69,16 +69,10 @@ export class PersonPage {
|
|||||||
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, 'Back to Servers'),
|
E('a', { class: 'cbi-button', href: L.url('admin/network/dawnline/server') }, 'Back to Servers'),
|
||||||
]);
|
]);
|
||||||
this.p = p;
|
this.p = p;
|
||||||
for (const k of ['head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
|
for (const k of ['crumbs', 'head', 'devices', 'traffic', 'places', 'activity', 'limits'] as Part[]) this.parts[k] = E('div', {});
|
||||||
this.parts.devices.className = 'dl-person-devices';
|
this.parts.devices.className = 'dl-person-devices';
|
||||||
const root = E('div', {}, [
|
const root = E('div', {}, [
|
||||||
E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
|
this.parts.crumbs,
|
||||||
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
|
|
||||||
E('span', {}, '/'),
|
|
||||||
E('a', { href: peopleUrl(p.server) }, 'People'),
|
|
||||||
E('span', {}, '/'),
|
|
||||||
E('span', {}, p.name),
|
|
||||||
]),
|
|
||||||
this.parts.head,
|
this.parts.head,
|
||||||
E('div', { class: 'dl-grid-person' }, [
|
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.devices, this.parts.traffic, this.parts.places, this.parts.activity]),
|
||||||
@@ -176,7 +170,20 @@ export class PersonPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Every part; a `quiet` (periodic) repaint leaves alone the parts that have the keyboard focus. */
|
/** Every part; a `quiet` (periodic) repaint leaves alone the parts that have the keyboard focus. */
|
||||||
|
/** Server / People / name: the server changes when the person is moved. */
|
||||||
|
private crumbs(): HTMLElement {
|
||||||
|
const p = this.p;
|
||||||
|
return E('nav', { class: 'dl-crumbs', 'aria-label': 'Breadcrumb' }, [
|
||||||
|
E('a', { href: peopleUrl(p.server) }, this.st.servers.find((x) => x.id === p.server)?.name ?? 'Servers'),
|
||||||
|
E('span', {}, '/'),
|
||||||
|
E('a', { href: peopleUrl(p.server) }, 'People'),
|
||||||
|
E('span', {}, '/'),
|
||||||
|
E('span', {}, p.name),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
paint(quiet = false) {
|
paint(quiet = false) {
|
||||||
|
repaint(this.parts.crumbs, this.crumbs(), quiet);
|
||||||
repaint(this.parts.head, headPart(this), quiet);
|
repaint(this.parts.head, headPart(this), quiet);
|
||||||
repaint(this.parts.traffic, trafficPart(this), quiet);
|
repaint(this.parts.traffic, trafficPart(this), quiet);
|
||||||
repaint(this.parts.devices, devicesPart(this), quiet);
|
repaint(this.parts.devices, devicesPart(this), quiet);
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import type { Person } from '../../../shared/types';
|
|||||||
import { E } from '../../e';
|
import { E } from '../../e';
|
||||||
import { notify } from '../../ui/toast';
|
import { notify } from '../../ui/toast';
|
||||||
import { seg } from '../../ui/controls';
|
import { seg } from '../../ui/controls';
|
||||||
|
import { button } from '../../ui/button';
|
||||||
|
import { cancelButton, closeModal, modal } from '../../ui/modal';
|
||||||
|
import { liveField } from '../../ui/layout';
|
||||||
|
import { quotaHelp } from '../../netcheck';
|
||||||
import { attachTip } from '../../ui/tooltip';
|
import { attachTip } from '../../ui/tooltip';
|
||||||
import { icon } from '../../../shared/icons';
|
import { icon } from '../../../shared/icons';
|
||||||
import { ACCESS_LABEL, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
|
import { ACCESS_LABEL, bytes, date, daysLeft, endsSoon, shiftDay } from '../../../shared/format';
|
||||||
@@ -163,8 +167,36 @@ function dataTile(page: PersonPage): HTMLElement {
|
|||||||
type: 'button',
|
type: 'button',
|
||||||
class: 'dl-chipbtn',
|
class: 'dl-chipbtn',
|
||||||
click: () => {
|
click: () => {
|
||||||
const v = prompt('Data limit in GB', p.quota_gb ? String(p.quota_gb) : '');
|
const inp = E('input', {
|
||||||
if (v != null && v.trim() !== '' && Number(v) > 0) void page.patch({ quota_gb: v.trim() }, `Data limit ${v.trim()} GB`);
|
type: 'number',
|
||||||
|
class: 'cbi-input-text dl-w-port',
|
||||||
|
min: 0,
|
||||||
|
step: 'any',
|
||||||
|
value: p.quota_gb ? String(p.quota_gb) : '',
|
||||||
|
}) as HTMLInputElement;
|
||||||
|
const row = liveField('Data limit (GB)', inp, () => quotaHelp(inp.value, p.quota_period === 'month'));
|
||||||
|
modal(
|
||||||
|
'Data limit',
|
||||||
|
[row],
|
||||||
|
[
|
||||||
|
cancelButton(),
|
||||||
|
' ',
|
||||||
|
button(
|
||||||
|
'Save',
|
||||||
|
async () => {
|
||||||
|
const h = row.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const v = inp.value.trim();
|
||||||
|
if (await page.patch({ quota_gb: v }, v && Number(v) > 0 ? `Data limit ${v} GB` : 'No data limit')) closeModal();
|
||||||
|
},
|
||||||
|
'positive',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
setTimeout(() => inp.select(), 50);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
'Custom',
|
'Custom',
|
||||||
@@ -249,20 +281,27 @@ function hoursTile(page: PersonPage): HTMLElement {
|
|||||||
'aria-checked': hoursOn ? 'true' : 'false',
|
'aria-checked': hoursOn ? 'true' : 'false',
|
||||||
class: `dl-switch${hoursOn ? ' on' : ''}`,
|
class: `dl-switch${hoursOn ? ' on' : ''}`,
|
||||||
'aria-label': 'Limit hours',
|
'aria-label': 'Limit hours',
|
||||||
click: () => page.patch({ hours: hoursOn ? '' : '07:00-23:00' }, hoursOn ? 'Any time' : 'Allowed 07:00–23:00'),
|
// Turning on shows the times to set; nothing is enforced until they are saved.
|
||||||
|
click: () => {
|
||||||
|
if (hoursOn) return page.patch({ hours: '' }, 'Any time');
|
||||||
|
sw.classList.add('on');
|
||||||
|
sw.setAttribute('aria-checked', 'true');
|
||||||
|
label.textContent = 'Set the hours, then press Enter';
|
||||||
|
tile.appendChild(times);
|
||||||
|
from.focus();
|
||||||
|
},
|
||||||
},
|
},
|
||||||
E('i'),
|
E('i'),
|
||||||
);
|
);
|
||||||
return E('div', { class: 'dl-tile2' }, [
|
const label = E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time');
|
||||||
|
const tile = E('div', { class: 'dl-tile2' }, [
|
||||||
E('div', { class: 'dl-tile2-row' }, [
|
E('div', { class: 'dl-tile2-row' }, [
|
||||||
E('div', { class: 'dl-stack' }, [
|
E('div', { class: 'dl-stack' }, [E('span', { class: 'dl-tile2-label' }, 'Allowed hours'), label]),
|
||||||
E('span', { class: 'dl-tile2-label' }, 'Allowed hours'),
|
|
||||||
E('span', {}, hoursOn ? `${h1} – ${h2} (router time)` : 'Any time'),
|
|
||||||
]),
|
|
||||||
sw,
|
sw,
|
||||||
]),
|
]),
|
||||||
hoursOn ? times : '',
|
hoursOn ? times : '',
|
||||||
]);
|
]);
|
||||||
|
return tile;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function limitsPart(page: PersonPage): HTMLElement {
|
export function limitsPart(page: PersonPage): HTMLElement {
|
||||||
|
|||||||
@@ -12,13 +12,13 @@ import { cancelButton, closeModal, confirmDialog, modal } from '../ui/modal';
|
|||||||
import { copyText } from '../ui/files';
|
import { copyText } from '../ui/files';
|
||||||
import { attempt, errorText, notify } from '../ui/toast';
|
import { attempt, errorText, notify } from '../ui/toast';
|
||||||
import { input, seg, sw } from '../ui/controls';
|
import { input, seg, sw } from '../ui/controls';
|
||||||
import { card, group, liveRow, needRow, row } from '../ui/layout';
|
import { card, firstBad, group, liveRow, needRow, row } from '../ui/layout';
|
||||||
import { portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
import { dnsHelp, endpointProbe, hostHelp, nameHelp, portalPortHelp, portHelp, rangeHelp, rangeOf, subnetOf } from '../netcheck';
|
||||||
import { icon } from '../../shared/icons';
|
import { icon } from '../../shared/icons';
|
||||||
import { duration } from '../../shared/format';
|
import { ago, duration } from '../../shared/format';
|
||||||
import { accessCards } from '../interfaces';
|
import { accessCards } from '../interfaces';
|
||||||
import { checkAccess, whoReaches } from '../access';
|
import { checkAccess, whoReaches } from '../access';
|
||||||
import { methodPicker, type Method } from '../disguise';
|
import { defaultMethod, methodPicker } from '../disguise';
|
||||||
import { coreOf } from '../cores';
|
import { coreOf } from '../cores';
|
||||||
import { installAwg } from '../pkgs';
|
import { installAwg } from '../pkgs';
|
||||||
import { createPoller, focusInside, repaint, type Poller } from '../state/poller';
|
import { createPoller, focusInside, repaint, type Poller } from '../state/poller';
|
||||||
@@ -299,7 +299,7 @@ export class ServerPage {
|
|||||||
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address', click: () => copyText(addr, 'Address copied') },
|
{ type: 'button', class: 'dl-addrbar-seg main', title: 'Copy address', click: () => copyText(addr, 'Address copied') },
|
||||||
[icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')],
|
[icon('globe'), E('span', { class: 'dl-mono' }, addr), icon('copy')],
|
||||||
),
|
),
|
||||||
part('tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
|
part(coreOf(srv).id === 'awg' ? 'amneziawg' : 'tunnel', [E('span', { class: 'dl-mono' }, `${coreOf(srv).label} :${srv.port}`)]),
|
||||||
srv.up ? part('clock', [`up ${duration(srv.uptime)}`]) : '',
|
srv.up ? part('clock', [`up ${duration(srv.uptime)}`]) : '',
|
||||||
]),
|
]),
|
||||||
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
|
// The reason the tunnel can't run at all ("can't use the network interface awg0: it exists and isn't Dawnline's").
|
||||||
@@ -318,7 +318,7 @@ export class ServerPage {
|
|||||||
const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text dl-mono' });
|
const dns = input(srv.dns.join(', '), { placeholder: 'This router (recommended)', class: 'cbi-input-text dl-mono' });
|
||||||
const people = this.st.people.filter((p) => p.server === srv.id).length;
|
const people = this.st.people.filter((p) => p.server === srv.id).length;
|
||||||
const toggle = button(
|
const toggle = button(
|
||||||
srv.enabled ? 'Turn off' : 'Turn on',
|
[icon(srv.enabled ? 'pause' : 'play'), srv.enabled ? ' Turn off' : ' Turn on'],
|
||||||
async () => {
|
async () => {
|
||||||
if (
|
if (
|
||||||
srv.enabled &&
|
srv.enabled &&
|
||||||
@@ -334,24 +334,51 @@ export class ServerPage {
|
|||||||
},
|
},
|
||||||
srv.enabled ? 'negative' : 'positive',
|
srv.enabled ? 'negative' : 'positive',
|
||||||
);
|
);
|
||||||
|
const portalHost = this.st.settings.portal_host;
|
||||||
|
const nameRow = liveRow('Name', name, () => nameHelp(name.value, [], 'Shown to people in their portal and apps.'));
|
||||||
|
// Where the address points is checked on the router as it is typed (debounced).
|
||||||
|
const ep = endpointProbe(
|
||||||
|
() => ({ host: endpoint.value, port: srv.port, id: srv.id }),
|
||||||
|
(h, id, port) => api.endpointProbe(h, id, port),
|
||||||
|
() => epRow.refresh(),
|
||||||
|
{ empty: portalHost ? `Empty = the portal’s address (${portalHost}).` : 'Empty = the portal’s address.' },
|
||||||
|
);
|
||||||
|
const epRow = liveRow('Public address', endpoint, ep.help);
|
||||||
|
endpoint.addEventListener('input', ep.schedule);
|
||||||
|
ep.schedule();
|
||||||
|
const reached = srv.reached
|
||||||
|
? `Reached from the internet ${ago(srv.reached, this.st.now)}.`
|
||||||
|
: 'Never reached from the internet yet — test with a phone on mobile data.';
|
||||||
|
const dnsRow = liveRow('DNS for devices', dns, () => dnsHelp(dns.value, srv.address));
|
||||||
return E('div', { class: 'dl-stack gap16' }, [
|
return E('div', { class: 'dl-stack gap16' }, [
|
||||||
card(
|
card(
|
||||||
'Connection',
|
'Connection',
|
||||||
[
|
[
|
||||||
E('p', { class: 'dl-muted' }, 'The name people see, where devices find the router, and DNS. The port is on AmneziaWG.'),
|
E('p', { class: 'dl-muted' }, 'The name people see, where devices find the router, and DNS. The port is on AmneziaWG.'),
|
||||||
group('router', 'Server', 'What people see', [row('Name', name, 'Shown to people in their portal and apps.')]),
|
group('router', 'Server', 'What people see', [nameRow]),
|
||||||
group('globe', 'Devices connect to', 'Where the router answers from the internet', [
|
group(
|
||||||
row(
|
'globe',
|
||||||
'Public address',
|
'Devices connect to',
|
||||||
endpoint,
|
'A DDNS name keeps links working when your IP changes; not through Cloudflare (use a DNS-only name or an IP)',
|
||||||
'Hostname or IP of the router on the internet. A DDNS name keeps links working when your IP changes. It must not go through Cloudflare: use a DNS-only name or an IP.',
|
[epRow, E('div', { class: `dl-sub ${srv.reached ? 'ok' : 'warn'}` }, reached)],
|
||||||
|
),
|
||||||
|
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [dnsRow]),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
E('span'),
|
||||||
|
button(
|
||||||
|
'Save',
|
||||||
|
() => {
|
||||||
|
const bad = firstBad([nameRow, epRow, dnsRow]);
|
||||||
|
if (bad) {
|
||||||
|
notify(bad, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return this.save(srv, { name: name.value, endpoint: endpoint.value, dns: dns.value });
|
||||||
|
},
|
||||||
|
'positive',
|
||||||
),
|
),
|
||||||
]),
|
|
||||||
group('file', 'For every device', 'Changing it marks devices “Update config” until they import again', [
|
|
||||||
row('DNS for devices', dns, 'Empty = this router, which sends each query where your home network would.'),
|
|
||||||
]),
|
|
||||||
],
|
],
|
||||||
[E('span'), button('Save', () => this.save(srv, { name: name.value, endpoint: endpoint.value, dns: dns.value }), 'positive')],
|
|
||||||
),
|
),
|
||||||
card(
|
card(
|
||||||
'Danger zone',
|
'Danger zone',
|
||||||
@@ -369,6 +396,21 @@ export class ServerPage {
|
|||||||
]),
|
]),
|
||||||
E('div', { class: 'dl-setrow-ctl' }, toggle),
|
E('div', { class: 'dl-setrow-ctl' }, toggle),
|
||||||
]),
|
]),
|
||||||
|
E('div', { class: 'dl-setrow' }, [
|
||||||
|
E('div', { class: 'dl-stack' }, [
|
||||||
|
E('span', { class: 'dl-setrow-label' }, 'Change the tunnel network'),
|
||||||
|
E(
|
||||||
|
'span',
|
||||||
|
{ class: 'dl-sub' },
|
||||||
|
`Devices have ${rangeOf(srv.subnet)}.x addresses now. A new range when it clashes with a network you connect to; every device then needs its configuration again.`,
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
E(
|
||||||
|
'div',
|
||||||
|
{ class: 'dl-setrow-ctl' },
|
||||||
|
button([icon('edit'), ' Change'], () => this.changeSubnet(srv), 'negative'),
|
||||||
|
),
|
||||||
|
]),
|
||||||
E('div', { class: 'dl-setrow' }, [
|
E('div', { class: 'dl-setrow' }, [
|
||||||
E('div', { class: 'dl-stack' }, [
|
E('div', { class: 'dl-stack' }, [
|
||||||
E('span', { class: 'dl-setrow-label' }, 'Remove server'),
|
E('span', { class: 'dl-setrow-label' }, 'Remove server'),
|
||||||
@@ -434,6 +476,55 @@ export class ServerPage {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A new tunnel network: checked as you type against the router's networks, then every device renumbered. */
|
||||||
|
async changeSubnet(srv: Server) {
|
||||||
|
const taken = await attempt(() => api.serverPorts(srv.id));
|
||||||
|
if (!taken) return;
|
||||||
|
const nets = taken.networks ?? [];
|
||||||
|
const devices = this.st.people.filter((p) => p.server === srv.id).reduce((n, p) => n + p.devices.length, 0);
|
||||||
|
const range = input(rangeOf(srv.subnet), { class: 'cbi-input-text dl-mono dl-w-range' });
|
||||||
|
const rangeRow = liveRow('Address range', range, () => rangeHelp(range.value, nets, ''));
|
||||||
|
modal(
|
||||||
|
'Change the tunnel network',
|
||||||
|
[
|
||||||
|
rangeRow,
|
||||||
|
E(
|
||||||
|
'p',
|
||||||
|
{ class: 'dl-muted' },
|
||||||
|
devices
|
||||||
|
? `${devices} device${devices === 1 ? ' gets a new address and stops' : 's get new addresses and stop'} connecting until ${devices === 1 ? 'it imports its' : 'they import their'} configuration again (from their personal link or from you).`
|
||||||
|
: 'No devices on this server yet: nothing else changes.',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
cancelButton(),
|
||||||
|
' ',
|
||||||
|
button(
|
||||||
|
'Change',
|
||||||
|
async () => {
|
||||||
|
const h = rangeRow.help();
|
||||||
|
if (h.bad) {
|
||||||
|
notify(h.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const subnet = subnetOf(range.value);
|
||||||
|
if (subnet === srv.subnet) {
|
||||||
|
closeModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (await attempt(() => api.serverUpdate(srv.id, { subnet }), 'Tunnel network changed')) {
|
||||||
|
closeModal();
|
||||||
|
if (devices) notify('Devices are marked “Update config” until they import again.', 'info', 6000);
|
||||||
|
await this.refresh();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
'negative',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
setTimeout(() => range.select(), 50);
|
||||||
|
}
|
||||||
|
|
||||||
async remove(srv: Server) {
|
async remove(srv: Server) {
|
||||||
const people = this.st.people.filter((p) => p.server === srv.id);
|
const people = this.st.people.filter((p) => p.server === srv.id);
|
||||||
modal(
|
modal(
|
||||||
@@ -477,7 +568,7 @@ export class ServerPage {
|
|||||||
port: d.port,
|
port: d.port,
|
||||||
// The tunnel's first three numbers ("10.77.0"): it is that /24.
|
// The tunnel's first three numbers ("10.77.0"): it is that /24.
|
||||||
range: rangeOf(d.subnet),
|
range: rangeOf(d.subnet),
|
||||||
preset: 'standard' as Method,
|
preset: defaultMethod(d.awg),
|
||||||
// Off by default: the portal opens a port on WAN, so it is a choice.
|
// Off by default: the portal opens a port on WAN, so it is a choice.
|
||||||
portal: false,
|
portal: false,
|
||||||
portal_port: d.portal_port || 8443,
|
portal_port: d.portal_port || 8443,
|
||||||
@@ -489,7 +580,45 @@ export class ServerPage {
|
|||||||
// The portal takes the server's port number (TCP beside UDP) until it is changed by hand.
|
// The portal takes the server's port number (TCP beside UDP) until it is changed by hand.
|
||||||
let portalSame = !extra && state.portal_port === state.port;
|
let portalSame = !extra && state.portal_port === state.port;
|
||||||
const ipLinks = () => /^\d{1,3}(\.\d{1,3}){3}$/.test(state.endpoint);
|
const ipLinks = () => /^\d{1,3}(\.\d{1,3}){3}$/.test(state.endpoint);
|
||||||
const portHelpNow = () => portHelp(state.port, d.udp_taken ?? [], 'Opened on the WAN firewall automatically.');
|
const portHelpNow = () =>
|
||||||
|
portHelp(
|
||||||
|
state.port,
|
||||||
|
d.udp_taken ?? [],
|
||||||
|
`Opened on the WAN firewall automatically.${state.port === 4500 ? ' 4500 is IPsec’s port: most networks let it through.' : ''}`,
|
||||||
|
);
|
||||||
|
const FROM: Record<string, string> = {
|
||||||
|
ddns: 'From your DDNS name.',
|
||||||
|
cert: 'From your Let’s Encrypt certificate.',
|
||||||
|
wan: 'Your WAN address now — it may change; a DDNS name is better.',
|
||||||
|
portal: 'The portal’s address.',
|
||||||
|
};
|
||||||
|
const ep = endpointProbe(
|
||||||
|
() => ({ host: state.endpoint, port: state.port }),
|
||||||
|
(h, _id, port) => api.endpointProbe(h, '', port),
|
||||||
|
() => epRow?.refresh(),
|
||||||
|
{ idle: () => (state.endpoint === d.endpoint && d.endpoint_from ? (FROM[d.endpoint_from] ?? '') : '') },
|
||||||
|
);
|
||||||
|
let epRow: ReturnType<typeof liveRow> | null = null;
|
||||||
|
// Nobody on the internet reaches a private or CGNAT address: say it before the first step.
|
||||||
|
const wanNote =
|
||||||
|
d.wan_kind === 'cgnat' || d.wan_kind === 'private'
|
||||||
|
? needRow(
|
||||||
|
'alert',
|
||||||
|
'warn',
|
||||||
|
d.wan_kind === 'cgnat' ? 'Your router has no public address (CGNAT)' : `Your router is behind another router (WAN ${d.wan_ip})`,
|
||||||
|
d.wan_kind === 'cgnat'
|
||||||
|
? 'The ISP shares one address: devices can only connect if the ISP gives you a public address or IPv6. Ask them, or use a DDNS name that points at an IPv6 address.'
|
||||||
|
: 'Forward the UDP port on the upstream router to this one and use a DDNS name or that router’s public address here.',
|
||||||
|
'',
|
||||||
|
)
|
||||||
|
: '';
|
||||||
|
const restartNote =
|
||||||
|
d.awg_state?.tools && d.awg_state.handler === false
|
||||||
|
? E('div', { class: 'dl-note warn' }, [
|
||||||
|
icon('alert'),
|
||||||
|
E('span', {}, 'Creating the server restarts the network for a few seconds: AmneziaWG was installed after the network started.'),
|
||||||
|
])
|
||||||
|
: '';
|
||||||
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
|
const rangeHelpNow = () => rangeHelp(state.range, d.networks ?? [], rangeOf(d.subnet));
|
||||||
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
|
const portalHelpNow = () => portalPortHelp(state.portal_port, d.tcp_taken ?? [], ipLinks());
|
||||||
const root = E('div', { class: 'dl-wizard' });
|
const root = E('div', { class: 'dl-wizard' });
|
||||||
@@ -513,18 +642,36 @@ export class ServerPage {
|
|||||||
E(
|
E(
|
||||||
'p',
|
'p',
|
||||||
{ class: 'dl-muted' },
|
{ class: 'dl-muted' },
|
||||||
'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
|
extra
|
||||||
|
? 'One more server: another port or disguise for networks where the first does not get through, or its own home access rules. People are moved between servers from their page.'
|
||||||
|
: 'Where devices connect to. A hostname that always points at your router (DDNS) keeps links working when your IP changes.',
|
||||||
),
|
),
|
||||||
group('router', 'Server', 'What people see', [row('Name', field('name'), 'Shown to people in their portal and apps.')]),
|
group('router', 'Server', 'What people see', [
|
||||||
group('globe', 'Devices connect to', 'Where the router answers from the internet', [
|
liveRow('Name', field('name'), () => nameHelp(state.name, [], 'Shown to people in their portal and apps.')),
|
||||||
row(
|
]),
|
||||||
'Public address',
|
group(
|
||||||
field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' }),
|
'globe',
|
||||||
'Hostname or IP address of your router on the internet. Not through Cloudflare: use a DNS-only name or an IP.',
|
'Devices connect to',
|
||||||
|
'A hostname or IP address of your router on the internet; not through Cloudflare (use a DNS-only name or an IP). IPv6 works too, and is the way out of CGNAT',
|
||||||
|
[
|
||||||
|
(() => {
|
||||||
|
const el = field('endpoint', { placeholder: 'vpn.example.com', class: 'cbi-input-text dl-mono' });
|
||||||
|
epRow = liveRow('Public address', el, ep.help);
|
||||||
|
el.addEventListener('input', ep.schedule);
|
||||||
|
ep.schedule();
|
||||||
|
return epRow;
|
||||||
|
})(),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
|
wanNote,
|
||||||
|
restartNote,
|
||||||
]),
|
]),
|
||||||
]),
|
check: () => {
|
||||||
check: () => (!state.endpoint ? 'Fill in the public address.' : null),
|
const n = nameHelp(state.name);
|
||||||
|
if (n.bad) return `Name: ${n.text}`;
|
||||||
|
const h = hostHelp(state.endpoint, state.port);
|
||||||
|
return h.bad ? `Public address: ${h.text}` : null;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
const awgPage: Page = {
|
const awgPage: Page = {
|
||||||
id: 'awg',
|
id: 'awg',
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
import { E } from '../../e';
|
import { E } from '../../e';
|
||||||
import { button } from '../../ui/button';
|
import { button } from '../../ui/button';
|
||||||
import { input, isOn, sw } from '../../ui/controls';
|
import { input, isOn, sw } from '../../ui/controls';
|
||||||
import { row } from '../../ui/layout';
|
import { firstBad, liveRow } from '../../ui/layout';
|
||||||
|
import { notify } from '../../ui/toast';
|
||||||
|
import { domainHelp, fallbackDnsHelp, limitHelp } from '../../netcheck';
|
||||||
import { section, type SettingsHost } from './common';
|
import { section, type SettingsHost } from './common';
|
||||||
|
|
||||||
export function defaultsCard(host: SettingsHost): HTMLElement {
|
export function defaultsCard(host: SettingsHost): HTMLElement {
|
||||||
@@ -17,28 +19,37 @@ export function defaultsCard(host: SettingsHost): HTMLElement {
|
|||||||
inputmode: 'decimal',
|
inputmode: 'decimal',
|
||||||
class: 'cbi-input-text dl-w-ip dl-mono',
|
class: 'cbi-input-text dl-w-ip dl-mono',
|
||||||
});
|
});
|
||||||
|
const limitRow = liveRow('Devices per person', limit, () => {
|
||||||
|
// Empty keeps the default (the router stores nothing then).
|
||||||
|
if (!limit.value.trim()) return { text: 'The default, 3. Pre-filled when you add someone.', bad: false };
|
||||||
|
const h = limitHelp(limit.value);
|
||||||
|
return h.bad ? h : { text: 'Pre-filled when you add someone.', bad: false };
|
||||||
|
});
|
||||||
|
const domainRow = liveRow(
|
||||||
|
'Device hostnames',
|
||||||
|
domain,
|
||||||
|
() => domainHelp(domain.value),
|
||||||
|
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
|
||||||
|
);
|
||||||
|
const fallbackRow = liveRow('Fallback DNS', fallback, () => {
|
||||||
|
const h = fallbackDnsHelp(fallback.value);
|
||||||
|
return h.bad ? h : { text: `For Home-only devices using home names: ${h.text}`, bad: false };
|
||||||
|
});
|
||||||
return section(
|
return section(
|
||||||
'defaults',
|
'defaults',
|
||||||
'Defaults',
|
'New people',
|
||||||
[
|
[limitRow, domainRow, fallbackRow],
|
||||||
row('Devices per person', limit, 'Pre-filled when you add someone.'),
|
|
||||||
row(
|
|
||||||
'Device hostnames',
|
|
||||||
E('div', { class: 'dl-hostport' }, [hn, E('span', { class: 'dl-faint dl-mono' }, 'phone.myata.'), domain]),
|
|
||||||
'Name devices in your home DNS.',
|
|
||||||
),
|
|
||||||
row(
|
|
||||||
'Fallback DNS',
|
|
||||||
fallback,
|
|
||||||
'For Home-only devices using home names: the second DNS server, used by the device when the tunnel is down. Empty = none.',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
E('span'),
|
E('span'),
|
||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
() =>
|
() => {
|
||||||
host.save(
|
const bad = firstBad([limitRow, domainRow, fallbackRow]);
|
||||||
|
if (bad) {
|
||||||
|
notify(bad, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return host.save(
|
||||||
{
|
{
|
||||||
default_device_limit: limit.value,
|
default_device_limit: limit.value,
|
||||||
hostnames: isOn(hn) ? '1' : '0',
|
hostnames: isOn(hn) ? '1' : '0',
|
||||||
@@ -47,7 +58,8 @@ export function defaultsCard(host: SettingsHost): HTMLElement {
|
|||||||
},
|
},
|
||||||
'Saved',
|
'Saved',
|
||||||
'defaults',
|
'defaults',
|
||||||
),
|
);
|
||||||
|
},
|
||||||
'positive',
|
'positive',
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import { E } from '../../e';
|
|||||||
import { button } from '../../ui/button';
|
import { button } from '../../ui/button';
|
||||||
import { cancelButton, closeModal, modal } from '../../ui/modal';
|
import { cancelButton, closeModal, modal } from '../../ui/modal';
|
||||||
import { input, isOn, sw } from '../../ui/controls';
|
import { input, isOn, sw } from '../../ui/controls';
|
||||||
import { group, liveRow, needRow, row } from '../../ui/layout';
|
import { firstBad, group, liveRow, needRow, row } from '../../ui/layout';
|
||||||
import { portalPortHelp } from '../../netcheck';
|
import { hostHelp, portalPortHelp, urlHelp } from '../../netcheck';
|
||||||
import { icon } from '../../../shared/icons';
|
import { icon } from '../../../shared/icons';
|
||||||
import { fmtDay } from '../../../shared/format';
|
import { fmtDay } from '../../../shared/format';
|
||||||
import { installMissing } from '../../pkgs';
|
import { installMissing } from '../../pkgs';
|
||||||
@@ -29,7 +29,6 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
|||||||
const c = host.d.cert;
|
const c = host.d.cert;
|
||||||
const pOn = sw(eff.portal_enabled, 'Enable portal');
|
const pOn = sw(eff.portal_enabled, 'Enable portal');
|
||||||
const port = input(s.portal_port, { placeholder: '8443', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
|
const port = input(s.portal_port, { placeholder: '8443', inputmode: 'numeric', class: 'cbi-input-text dl-w-port' });
|
||||||
const title = input(s.portal_title, { placeholder: 'Dawnline' });
|
|
||||||
const redirect = input(s.portal_redirect, { placeholder: 'Show “Not found”', class: 'cbi-input-text dl-mono' });
|
const redirect = input(s.portal_redirect, { placeholder: 'Show “Not found”', class: 'cbi-input-text dl-mono' });
|
||||||
const other = input('', { placeholder: 'vpn.example.com or an IP', 'aria-label': 'Other address' });
|
const other = input('', { placeholder: 'vpn.example.com or an IP', 'aria-label': 'Other address' });
|
||||||
const isIp = (h: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h);
|
const isIp = (h: string) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h);
|
||||||
@@ -132,6 +131,12 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
|||||||
button('Add', () => {
|
button('Add', () => {
|
||||||
const h = other.value.trim().toLowerCase();
|
const h = other.value.trim().toLowerCase();
|
||||||
if (!h) return;
|
if (!h) return;
|
||||||
|
// The router would refuse it on Save: say so here.
|
||||||
|
const check = hostHelp(h);
|
||||||
|
if (check.bad) {
|
||||||
|
notify(check.text, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
addRow(h);
|
addRow(h);
|
||||||
if (!picked.includes(h)) picked = [...picked, h];
|
if (!picked.includes(h)) picked = [...picked, h];
|
||||||
other.value = '';
|
other.value = '';
|
||||||
@@ -273,6 +278,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
|||||||
portalPortHelp(port.value.trim() === '' ? eff.portal_port : Number(port.value), host.d.tcp_taken ?? [], picked.some(isIp)),
|
portalPortHelp(port.value.trim() === '' ? eff.portal_port : Number(port.value), host.d.tcp_taken ?? [], picked.some(isIp)),
|
||||||
);
|
);
|
||||||
refreshPort = listenRow.refresh;
|
refreshPort = listenRow.refresh;
|
||||||
|
const redirectRow = liveRow('Unknown links', redirect, () => urlHelp(redirect.value));
|
||||||
const custom = !!(s.portal_cert && s.portal_key);
|
const custom = !!(s.portal_cert && s.portal_key);
|
||||||
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
|
const kind = !c ? 'Portal is off' : custom ? 'Your files' : c.self_signed ? 'Self-signed' : 'Let’s Encrypt';
|
||||||
const certFiles = () => {
|
const certFiles = () => {
|
||||||
@@ -363,10 +369,7 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
|||||||
E('span', { class: 'dl-muted' }, 'A page where each person adds and manages their devices with their personal link.'),
|
E('span', { class: 'dl-muted' }, 'A page where each person adds and manages their devices with their personal link.'),
|
||||||
httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '',
|
httpsRow ? E('div', { class: 'dl-list' }, [httpsRow]) : '',
|
||||||
group('network', 'Port', 'How the portal listens (80 and 443 stay free)', [listenRow]),
|
group('network', 'Port', 'How the portal listens (80 and 443 stay free)', [listenRow]),
|
||||||
group('edit', 'Appearance', 'What people see', [
|
group('edit', 'Appearance', 'What people see', [redirectRow]),
|
||||||
row('Title', title, 'Shown at the top of the portal.'),
|
|
||||||
row('Unknown links', redirect, 'Where a wrong or old link goes, for example your website. Empty shows a plain “Not found”.'),
|
|
||||||
]),
|
|
||||||
group('link', 'Addresses', 'Pick one or more; the first is the main link', [
|
group('link', 'Addresses', 'Pick one or more; the first is the main link', [
|
||||||
opts,
|
opts,
|
||||||
E('div', { class: 'dl-stack gap8' }, [
|
E('div', { class: 'dl-stack gap8' }, [
|
||||||
@@ -382,14 +385,10 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
|||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
() => {
|
() => {
|
||||||
// The port's help line already says what is wrong: do not send it anyway.
|
// The help lines already say what is wrong: do not send it anyway.
|
||||||
const h = portalPortHelp(
|
const bad = firstBad([listenRow, redirectRow]);
|
||||||
port.value.trim() === '' ? eff.portal_port : Number(port.value),
|
if (bad) {
|
||||||
host.d.tcp_taken ?? [],
|
notify(bad, 'warning');
|
||||||
picked.some(isIp),
|
|
||||||
);
|
|
||||||
if (h.bad) {
|
|
||||||
notify(`Listening port: ${h.text}`, 'warning');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return host.save(
|
return host.save(
|
||||||
@@ -398,7 +397,6 @@ export function portalCard(host: SettingsHost): HTMLElement {
|
|||||||
portal_host: picked[0] ?? '',
|
portal_host: picked[0] ?? '',
|
||||||
portal_alt: picked.slice(1),
|
portal_alt: picked.slice(1),
|
||||||
portal_port: port.value,
|
portal_port: port.value,
|
||||||
portal_title: title.value,
|
|
||||||
portal_redirect: redirect.value.trim(),
|
portal_redirect: redirect.value.trim(),
|
||||||
},
|
},
|
||||||
'Saved',
|
'Saved',
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { E } from '../../e';
|
|||||||
import { button } from '../../ui/button';
|
import { button } from '../../ui/button';
|
||||||
import { chipToggle, input, isOn, seg, setChip, sw } from '../../ui/controls';
|
import { chipToggle, input, isOn, seg, setChip, sw } from '../../ui/controls';
|
||||||
import { row } from '../../ui/layout';
|
import { row } from '../../ui/layout';
|
||||||
|
import { notify } from '../../ui/toast';
|
||||||
|
import { timeHelp } from '../../netcheck';
|
||||||
import { section, type SettingsHost } from './common';
|
import { section, type SettingsHost } from './common';
|
||||||
|
|
||||||
const TARGET: [string, string][] = [
|
const TARGET: [string, string][] = [
|
||||||
@@ -99,8 +101,15 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
E('span', { class: 'dl-sub' }, 'Run a check or an update by hand in Components.'),
|
E('span', { class: 'dl-sub' }, 'Run a check or an update by hand in Components.'),
|
||||||
button(
|
button(
|
||||||
'Save',
|
'Save',
|
||||||
() =>
|
() => {
|
||||||
host.save(
|
if (mode.dataset.value === 'scheduled') {
|
||||||
|
const h = timeHelp(at.value);
|
||||||
|
if (h.bad) {
|
||||||
|
notify(`Time: ${h.text}`, 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return host.save(
|
||||||
{
|
{
|
||||||
update_check: isOn(check) ? '1' : '0',
|
update_check: isOn(check) ? '1' : '0',
|
||||||
update_interval: every.dataset.value!,
|
update_interval: every.dataset.value!,
|
||||||
@@ -113,7 +122,8 @@ export function updatesCard(host: SettingsHost): HTMLElement {
|
|||||||
},
|
},
|
||||||
'Saved',
|
'Saved',
|
||||||
'updates',
|
'updates',
|
||||||
),
|
);
|
||||||
|
},
|
||||||
'positive',
|
'positive',
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
// Where a device went: its stretches on each client address from the activity log
|
||||||
|
// (connect, roam, disconnect), as visits to the places the map shows, folded into
|
||||||
|
// stays for the replay, and the replay's timeline and shimmer. No DOM here (see ./render).
|
||||||
|
|
||||||
|
import type { GeoPoint, LogEvent } from '../../shared/types';
|
||||||
|
|
||||||
|
/** On one client address: from a connect or a roam to the next one, a disconnect or now. */
|
||||||
|
export interface Stretch {
|
||||||
|
ip: string;
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
live: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A device's stretches in time order, from the activity log. A stretch the log leaves open
|
||||||
|
* goes on until now while the device is online, and ends at `seen` (its latest handshake)
|
||||||
|
* when it is not. Empty when the log has no connections (the category is off or cleared).
|
||||||
|
*/
|
||||||
|
export function stretches(events: LogEvent[], device: string, now: number, online: boolean, seen = 0): Stretch[] {
|
||||||
|
const out: Stretch[] = [];
|
||||||
|
let cur: Stretch | null = null;
|
||||||
|
const close = (t: number) => {
|
||||||
|
if (cur && t > cur.from) out.push({ ...cur, to: t });
|
||||||
|
cur = null;
|
||||||
|
};
|
||||||
|
const mine = events.filter((e) => e.device === device).sort((a, b) => a.ts - b.ts);
|
||||||
|
for (const e of mine) {
|
||||||
|
if (e.type === 'connect') {
|
||||||
|
close(e.ts);
|
||||||
|
if (e.detail) cur = { ip: e.detail, from: e.ts, to: e.ts, live: false };
|
||||||
|
} else if (e.type === 'roam') {
|
||||||
|
// "old → new"
|
||||||
|
const ip = e.detail?.split('→')[1]?.trim();
|
||||||
|
close(e.ts);
|
||||||
|
if (ip) cur = { ip, from: e.ts, to: e.ts, live: false };
|
||||||
|
} else if (e.type === 'disconnect') close(e.ts);
|
||||||
|
}
|
||||||
|
const open = cur as Stretch | null;
|
||||||
|
if (open && online) out.push({ ...open, to: Math.max(now, open.from), live: true });
|
||||||
|
else close(Math.min(now, seen));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A place as the map groups them: the city (or rounded coordinates where there is none) and the country. */
|
||||||
|
export function placeKey(p: Pick<GeoPoint, 'city' | 'lat' | 'lon' | 'cc'>): string {
|
||||||
|
return `${p.city || `${p.lat.toFixed(1)},${p.lon.toFixed(1)}`}|${p.cc}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A stretch at a located address: the place it was at. */
|
||||||
|
export interface Visit {
|
||||||
|
key: string;
|
||||||
|
point: GeoPoint;
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
live: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The stretches since `from` whose address has a location (the device's own point first, then
|
||||||
|
* anyone's at that address), clipped to `from`. Addresses without one are left out, as on the map.
|
||||||
|
*/
|
||||||
|
export function visits(list: Stretch[], points: GeoPoint[], device: string, from: number): Visit[] {
|
||||||
|
const at = new Map<string, GeoPoint>();
|
||||||
|
for (const p of points) if (p.device === device || !at.has(p.ip)) at.set(p.ip, p);
|
||||||
|
const out: Visit[] = [];
|
||||||
|
for (const s of list) {
|
||||||
|
const p = at.get(s.ip);
|
||||||
|
if (!p || s.to <= from) continue;
|
||||||
|
out.push({ key: placeKey(p), point: p, from: Math.max(s.from, from), to: s.to, live: s.live });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Each place's share of the time the visits cover (0–1), by place key. */
|
||||||
|
export function shares(v: Visit[]): Map<string, number> {
|
||||||
|
const time = new Map<string, number>();
|
||||||
|
let total = 0;
|
||||||
|
for (const x of v) {
|
||||||
|
time.set(x.key, (time.get(x.key) ?? 0) + (x.to - x.from));
|
||||||
|
total += x.to - x.from;
|
||||||
|
}
|
||||||
|
return new Map([...time].map(([k, t]) => [k, total ? t / total : 0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Visits in a row at one place, with `short` visits elsewhere folded in. */
|
||||||
|
export interface Stay {
|
||||||
|
key: string;
|
||||||
|
point: GeoPoint;
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
live: boolean;
|
||||||
|
/** Visits elsewhere shorter than the fold (a phone flipping to mobile data and back), folded into this stay. */
|
||||||
|
short: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Visits as stays: a place's visits in a row are one, and a visit elsewhere shorter than `fold` seconds joins the stay around it. */
|
||||||
|
export function stays(v: Visit[], fold = 45 * 60): Stay[] {
|
||||||
|
const out: Stay[] = [];
|
||||||
|
for (const x of v) {
|
||||||
|
const last = out[out.length - 1];
|
||||||
|
if (last && x.key !== last.key && !x.live && x.to - x.from < fold) {
|
||||||
|
last.short++;
|
||||||
|
last.to = x.to;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (last && last.key === x.key) {
|
||||||
|
last.to = x.to;
|
||||||
|
last.live = x.live;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push({ key: x.key, point: x.point, from: x.from, to: x.to, live: x.live, short: 0 });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stays for a replay of at most `max` moves: every move while there are few, folding the
|
||||||
|
* shortest visits (minutes on mobile data, then longer) only as far as needed.
|
||||||
|
*/
|
||||||
|
export function replayStays(v: Visit[], max = 24): Stay[] {
|
||||||
|
for (const fold of [0, 5 * 60, 15 * 60, 45 * 60, 2 * 3600, 6 * 3600]) {
|
||||||
|
const st = stays(v, fold);
|
||||||
|
if (st.length - 1 <= max) return st;
|
||||||
|
}
|
||||||
|
return stays(v, 24 * 3600);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- the replay ---------- */
|
||||||
|
|
||||||
|
/** One move (ms): the place it leaves lets go, the shimmer runs along the arc, the next place lights up. */
|
||||||
|
export const MOVE_MS = 1600;
|
||||||
|
/** The shimmer sets off once the place it leaves has started to go gray (a share of the move). */
|
||||||
|
const LEAVE = 0.12;
|
||||||
|
/** The shimmer's length, a share of the arc: longer than the arc, so most of it is lit mid-move. */
|
||||||
|
export const BAND = 1.3;
|
||||||
|
/** ± this around the shimmer's middle is fully lit; it fades out to ±BAND/2. */
|
||||||
|
export const FLAT = 0.32;
|
||||||
|
|
||||||
|
/** A move into stay `k` (from stay k − 1), or stay `k` itself, `ms` long from `start`. */
|
||||||
|
export interface Step {
|
||||||
|
kind: 'move' | 'stay';
|
||||||
|
k: number;
|
||||||
|
start: number;
|
||||||
|
ms: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The replay's steps: each stay held in proportion to how long it lasted (within bounds), a move before each but the first. */
|
||||||
|
export function timeline(st: Stay[], move = MOVE_MS): { steps: Step[]; total: number } {
|
||||||
|
const steps: Step[] = [];
|
||||||
|
let t = 0;
|
||||||
|
st.forEach((s, k) => {
|
||||||
|
if (k) {
|
||||||
|
steps.push({ kind: 'move', k, start: t, ms: move });
|
||||||
|
t += move;
|
||||||
|
}
|
||||||
|
const ms = Math.min(1100, Math.max(350, ((s.to - s.from) / 3600) * 45));
|
||||||
|
steps.push({ kind: 'stay', k, start: t, ms });
|
||||||
|
t += ms;
|
||||||
|
});
|
||||||
|
return { steps, total: t };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where the replay is at `ms`: the step (its index), how far into it (0–1) and the moment shown. */
|
||||||
|
export function moment(st: Stay[], steps: Step[], ms: number): { i: number; step: Step; q: number; t: number } {
|
||||||
|
let i = steps.findIndex((s) => ms >= s.start && ms < s.start + s.ms);
|
||||||
|
if (i < 0) i = steps.length - 1;
|
||||||
|
const step = steps[i];
|
||||||
|
const q = Math.min(1, Math.max(0, (ms - step.start) / step.ms));
|
||||||
|
const s = st[step.k];
|
||||||
|
return { i, step, q, t: step.kind === 'move' ? s.from : s.from + (s.to - s.from) * q };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The replay's `ms` for moment `t` (a click on a strip): inside the stay it falls in. */
|
||||||
|
export function msAt(st: Stay[], steps: Step[], t: number): number {
|
||||||
|
let k = st.findIndex((s) => t >= s.from && t < s.to);
|
||||||
|
if (k < 0) k = t < (st[0]?.from ?? 0) ? 0 : st.length - 1;
|
||||||
|
const step = steps.find((s) => s.kind === 'stay' && s.k === k)!;
|
||||||
|
const s = st[k];
|
||||||
|
return step.start + step.ms * Math.min(0.999, Math.max(0, (t - s.from) / Math.max(1, s.to - s.from)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ease = (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : x < 0.5 ? 2 * x * x : 1 - (-2 * x + 2) ** 2 / 2);
|
||||||
|
|
||||||
|
/** The shimmer's middle (a share of the arc) `q` into a move: it enters before the place it leaves and runs out past the next. */
|
||||||
|
export function bandMiddle(q: number): number {
|
||||||
|
return -BAND / 2 + (1 + BAND) * ease((q - LEAVE) / (1 - LEAVE));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The next place lights up once the shimmer's bright part reaches it. */
|
||||||
|
export const arrived = (middle: number) => middle + FLAT >= 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The opacity of the arc's dots (each has its `pos` along the arc, 0–1) with the shimmer's middle
|
||||||
|
* at `c`: beui's text shimmer along a line, the arc itself transparent. A MapLibre expression.
|
||||||
|
*/
|
||||||
|
export function shimmerOpacity(c: number): unknown[] {
|
||||||
|
return ['interpolate', ['linear'], ['abs', ['-', ['get', 'pos'], c]], 0, 1, FLAT, 1, BAND / 2, 0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- labels ---------- */
|
||||||
|
|
||||||
|
/** Labels under the strips for a range ending `now`: [share of the range, label], in local time. */
|
||||||
|
export function ticks(range: '24h' | '7d' | '30d', now: number): [number, string][] {
|
||||||
|
const span = range === '24h' ? 86400 : range === '7d' ? 7 * 86400 : 30 * 86400;
|
||||||
|
const from = now - span;
|
||||||
|
const out: [number, string][] = [];
|
||||||
|
const put = (ts: number, label: string) => {
|
||||||
|
const f = (ts - from) / span;
|
||||||
|
if (f > 0.02 && f < 0.98) out.push([f, label]);
|
||||||
|
};
|
||||||
|
const d = new Date(from * 1000);
|
||||||
|
if (range === '24h') {
|
||||||
|
d.setMinutes(0, 0, 0);
|
||||||
|
while (d.getTime() / 1000 <= now) {
|
||||||
|
if (d.getHours() % 6 === 0) put(d.getTime() / 1000, `${String(d.getHours()).padStart(2, '0')}:00`);
|
||||||
|
d.setHours(d.getHours() + 1);
|
||||||
|
}
|
||||||
|
} else if (range === '7d') {
|
||||||
|
d.setHours(12, 0, 0, 0);
|
||||||
|
for (; d.getTime() / 1000 <= now; d.setDate(d.getDate() + 1))
|
||||||
|
put(d.getTime() / 1000, d.toLocaleDateString('en-GB', { weekday: 'short' }));
|
||||||
|
} else {
|
||||||
|
const end = new Date(now * 1000);
|
||||||
|
end.setHours(0, 0, 0, 0);
|
||||||
|
for (let i = 0; i < 5; i++) {
|
||||||
|
const w = new Date(end);
|
||||||
|
w.setDate(end.getDate() - 7 * i);
|
||||||
|
put(w.getTime() / 1000, w.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }));
|
||||||
|
}
|
||||||
|
out.reverse();
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "14:05", local. */
|
||||||
|
export const clock = (ts: number) => new Date(ts * 1000).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
|
||||||
|
|
||||||
|
/** "Today", "Yesterday" or "Wed 14 Oct" for a moment, against the router's `now`. */
|
||||||
|
export function dayName(ts: number, now: number): string {
|
||||||
|
const day = (x: number) => new Date(x * 1000).toDateString();
|
||||||
|
if (day(ts) === day(now)) return 'Today';
|
||||||
|
if (day(ts) === day(now - 86400)) return 'Yesterday';
|
||||||
|
return new Date(ts * 1000).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
// Where a device went, under its map (the device window): a row per place with a strip of
|
||||||
|
// when it was there, and a replay of the period: the place it leaves goes gray, a blue
|
||||||
|
// shimmer runs along the dotted arc to the next place, which lights up. The model is
|
||||||
|
// ./model; the map draws (ConnectionMap.replay, band, bandAt).
|
||||||
|
|
||||||
|
import type { Device, Geo, LogEvent, Person } from '../../shared/types';
|
||||||
|
import { E } from '../e';
|
||||||
|
import { icon } from '../../shared/icons';
|
||||||
|
import { ago } from '../../shared/format';
|
||||||
|
import { devicePlaces, type ConnectionMap, type MapData, type Range } from '../map';
|
||||||
|
import {
|
||||||
|
MOVE_MS,
|
||||||
|
arrived,
|
||||||
|
bandMiddle,
|
||||||
|
clock,
|
||||||
|
dayName,
|
||||||
|
moment,
|
||||||
|
msAt,
|
||||||
|
placeKey,
|
||||||
|
shares,
|
||||||
|
replayStays,
|
||||||
|
stretches,
|
||||||
|
ticks,
|
||||||
|
timeline,
|
||||||
|
visits,
|
||||||
|
type Stay,
|
||||||
|
type Step,
|
||||||
|
} from './model';
|
||||||
|
|
||||||
|
export interface PlacesData {
|
||||||
|
geo: Geo;
|
||||||
|
/** The router's clock (seconds). */
|
||||||
|
now: number;
|
||||||
|
person: Person;
|
||||||
|
device: Device;
|
||||||
|
/** The person's activity log (the device's connects and roams in it); null until loaded. */
|
||||||
|
events: LogEvent[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SPAN: Record<Exclude<Range, 'online'>, number> = { '24h': 86400, '7d': 7 * 86400, '30d': 30 * 86400 };
|
||||||
|
const pct = (part: number, whole: number) => `${((part / whole) * 100).toFixed(3)}%`;
|
||||||
|
|
||||||
|
export class PlacesView {
|
||||||
|
/** The rows under the map. */
|
||||||
|
readonly el = E('div', { class: 'dl-dplaces' });
|
||||||
|
/** The replay's controls, for the map's top corner. */
|
||||||
|
readonly controls = E('div', { class: 'dl-map-replay' });
|
||||||
|
private data: PlacesData;
|
||||||
|
/** What came while the replay ran: shown once it ends (the replay plays what it started with). */
|
||||||
|
private pending: PlacesData | null = null;
|
||||||
|
private rows = new Map<string, HTMLElement>();
|
||||||
|
private st: Stay[] = [];
|
||||||
|
private steps: Step[] = [];
|
||||||
|
private total = 0;
|
||||||
|
/** Where the replay is (ms into it) and the step it showed last. */
|
||||||
|
private ms = 0;
|
||||||
|
private stepI = -1;
|
||||||
|
/** In the replay (playing or paused), and playing. */
|
||||||
|
private on = false;
|
||||||
|
private playing = false;
|
||||||
|
private raf = 0;
|
||||||
|
private last = 0;
|
||||||
|
private endTimer = 0;
|
||||||
|
private play = E('button', { type: 'button', class: 'dl-map-btn' });
|
||||||
|
private chip = E('span', { class: 'dl-map-chip' });
|
||||||
|
private stop = E('button', { type: 'button', class: 'dl-map-btn', title: 'Back to now', 'aria-label': 'Back to now' }, icon('x'));
|
||||||
|
private reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private map: ConnectionMap,
|
||||||
|
private range: Range,
|
||||||
|
data: PlacesData,
|
||||||
|
) {
|
||||||
|
this.data = data;
|
||||||
|
this.play.addEventListener('click', () => this.toggle());
|
||||||
|
this.stop.addEventListener('click', () => this.end());
|
||||||
|
this.paint();
|
||||||
|
}
|
||||||
|
|
||||||
|
mapData(): MapData {
|
||||||
|
const d = this.data;
|
||||||
|
return { geo: d.geo, people: [d.person], now: d.now, person: d.person.id, device: d.device.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** New status or log: shown at once, or after the replay. */
|
||||||
|
update(data: Partial<PlacesData>) {
|
||||||
|
const next = { ...(this.pending ?? this.data), ...data };
|
||||||
|
if (this.on) {
|
||||||
|
this.pending = next;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.data = next;
|
||||||
|
this.map.update(this.mapData());
|
||||||
|
this.paint();
|
||||||
|
}
|
||||||
|
|
||||||
|
setRange(r: Range) {
|
||||||
|
this.end();
|
||||||
|
this.range = r;
|
||||||
|
this.map.setRange(r);
|
||||||
|
this.paint();
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
cancelAnimationFrame(this.raf);
|
||||||
|
clearTimeout(this.endTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
private paint() {
|
||||||
|
const d = this.data;
|
||||||
|
const span = SPAN[this.range as keyof typeof SPAN];
|
||||||
|
const from = d.now - span;
|
||||||
|
const v = visits(stretches(d.events ?? [], d.device.id, d.now, d.device.online, d.device.handshake), d.geo.points, d.device.id, from);
|
||||||
|
const share = shares(v);
|
||||||
|
this.st = replayStays(v);
|
||||||
|
const list = devicePlaces(this.mapData(), this.range);
|
||||||
|
const strips = v.length > 0;
|
||||||
|
this.el.classList.toggle('strips', strips);
|
||||||
|
this.el.classList.toggle('can-replay', this.st.length > 1);
|
||||||
|
this.rows.clear();
|
||||||
|
dom.content(
|
||||||
|
this.el,
|
||||||
|
list.length
|
||||||
|
? [
|
||||||
|
...list.map((x) => {
|
||||||
|
const key = placeKey(x);
|
||||||
|
const sh = share.get(key);
|
||||||
|
const strip = strips
|
||||||
|
? E(
|
||||||
|
'div',
|
||||||
|
{ class: `dl-dplace-strip${x.online ? ' live' : ''}` },
|
||||||
|
v
|
||||||
|
.filter((y) => y.key === key)
|
||||||
|
.map((y) => E('i', { style: `left:${pct(y.from - from, span)};width:${pct(y.to - y.from, span)}` })),
|
||||||
|
)
|
||||||
|
: '';
|
||||||
|
const row = E('div', { class: 'dl-dplace-row' }, [
|
||||||
|
E('span', { class: `dl-dplace-n${x.online ? ' live' : ''}` }, x.online ? icon(d.device.kind) : String(x.n)),
|
||||||
|
E('span', { class: 'dl-row-main dl-stack' }, [
|
||||||
|
E('span', {}, [x.city || x.cc || 'Unknown city', x.org ? E('span', { class: 'dl-muted' }, ` · ${x.org}`) : '']),
|
||||||
|
E('span', { class: 'dl-faint' }, [
|
||||||
|
E('span', { class: 'dl-mono' }, x.ip),
|
||||||
|
sh != null ? ` · ${sh > 0 && sh < 0.005 ? '<1' : Math.round(sh * 100)}% of the time` : '',
|
||||||
|
]),
|
||||||
|
]),
|
||||||
|
E('span', { class: x.online ? 'dl-dplace-now' : 'dl-faint dl-nowrap' }, x.online ? 'now' : ago(x.ts, d.now)),
|
||||||
|
strip,
|
||||||
|
]);
|
||||||
|
row.addEventListener('mouseenter', () => this.map.hoverPlace(key));
|
||||||
|
row.addEventListener('mouseleave', () => this.map.hoverPlace(null));
|
||||||
|
// The strips are the replay's timeline: a click or a drag on one goes to that moment.
|
||||||
|
if (strip) {
|
||||||
|
const seek = (ev: PointerEvent) => {
|
||||||
|
const r = strip.getBoundingClientRect();
|
||||||
|
this.seek(from + span * Math.min(1, Math.max(0, (ev.clientX - r.left) / r.width)));
|
||||||
|
};
|
||||||
|
strip.addEventListener('pointerdown', (ev) => {
|
||||||
|
strip.setPointerCapture(ev.pointerId);
|
||||||
|
seek(ev);
|
||||||
|
});
|
||||||
|
strip.addEventListener('pointermove', (ev) => ev.buttons && seek(ev));
|
||||||
|
}
|
||||||
|
this.rows.set(key, row);
|
||||||
|
return row;
|
||||||
|
}),
|
||||||
|
strips
|
||||||
|
? E(
|
||||||
|
'div',
|
||||||
|
{ class: 'dl-dplace-axis' },
|
||||||
|
ticks(this.range as keyof typeof SPAN, d.now).map(([f, label]) =>
|
||||||
|
E('span', { style: `left:${(f * 100).toFixed(2)}%` }, label),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: '',
|
||||||
|
]
|
||||||
|
: E('div', { class: 'dl-sub' }, 'No locations in this period.'),
|
||||||
|
);
|
||||||
|
this.paintControls();
|
||||||
|
}
|
||||||
|
|
||||||
|
private paintControls() {
|
||||||
|
dom.content(this.play, icon(this.playing ? 'pause' : 'play'));
|
||||||
|
this.play.title = this.playing ? 'Pause' : 'Replay this period';
|
||||||
|
this.play.setAttribute('aria-label', this.play.title);
|
||||||
|
// LuCI's dom.content takes one level of children: no nested arrays.
|
||||||
|
dom.content(this.controls, this.on ? [this.play, this.chip, this.stop] : this.st.length > 1 ? [this.play] : []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- the replay ---------- */
|
||||||
|
|
||||||
|
private begin() {
|
||||||
|
this.on = true;
|
||||||
|
({ steps: this.steps, total: this.total } = timeline(this.st, this.reduced ? 400 : MOVE_MS));
|
||||||
|
this.ms = 0;
|
||||||
|
this.stepI = -1;
|
||||||
|
// The live place lets go; the first stay lights up on the first frame.
|
||||||
|
this.map.replay({ active: null, when: '' }, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private toggle() {
|
||||||
|
if (this.playing) {
|
||||||
|
this.playing = false;
|
||||||
|
cancelAnimationFrame(this.raf);
|
||||||
|
this.paintControls();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clearTimeout(this.endTimer);
|
||||||
|
if (!this.on || this.ms >= this.total) this.begin();
|
||||||
|
this.playing = true;
|
||||||
|
this.last = performance.now();
|
||||||
|
this.paintControls();
|
||||||
|
this.raf = requestAnimationFrame((t) => this.frame(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
private frame(now: number) {
|
||||||
|
if (!this.playing) return;
|
||||||
|
this.ms = Math.min(this.total, this.ms + (now - this.last));
|
||||||
|
this.last = now;
|
||||||
|
this.show(true);
|
||||||
|
if (this.ms < this.total) {
|
||||||
|
this.raf = requestAnimationFrame((t) => this.frame(t));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// At the end: a moment on the last place, then back to now.
|
||||||
|
this.playing = false;
|
||||||
|
this.paintControls();
|
||||||
|
this.endTimer = window.setTimeout(() => this.end(), 1500);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Moment `t` (a click on a strip): its place at once, paused there. */
|
||||||
|
private seek(t: number) {
|
||||||
|
if (this.st.length < 2) return;
|
||||||
|
clearTimeout(this.endTimer);
|
||||||
|
if (!this.on) this.begin();
|
||||||
|
this.ms = msAt(this.st, this.steps, t);
|
||||||
|
this.stepI = -1;
|
||||||
|
this.show(false);
|
||||||
|
this.paintControls();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The replay at `this.ms`: the map's light and shimmer, the strips' tick, the chip. */
|
||||||
|
private show(animate: boolean) {
|
||||||
|
const m = moment(this.st, this.steps, this.ms);
|
||||||
|
const s = this.st[m.step.k];
|
||||||
|
if (m.step.kind === 'move') {
|
||||||
|
const prev = this.st[m.step.k - 1];
|
||||||
|
if (m.i !== this.stepI) {
|
||||||
|
// The place it leaves goes gray; the shimmer sets off from it.
|
||||||
|
this.map.replay({ active: null, when: '' }, animate);
|
||||||
|
this.map.band([prev.point.lon, prev.point.lat], [s.point.lon, s.point.lat]);
|
||||||
|
}
|
||||||
|
const c = bandMiddle(m.q);
|
||||||
|
if (!this.reduced) this.map.bandAt(c);
|
||||||
|
if (this.reduced ? m.q >= 0.5 : arrived(c)) this.map.replay({ active: s.key, when: clock(m.t) }, animate);
|
||||||
|
} else {
|
||||||
|
if (m.i !== this.stepI) this.map.band();
|
||||||
|
this.map.replay({ active: s.key, when: clock(m.t) }, animate);
|
||||||
|
}
|
||||||
|
this.stepI = m.i;
|
||||||
|
const d = this.data;
|
||||||
|
const from = d.now - SPAN[this.range as keyof typeof SPAN];
|
||||||
|
this.el.classList.add('replay');
|
||||||
|
this.el.style.setProperty('--at', pct(m.t - from, d.now - from));
|
||||||
|
for (const [k, r] of this.rows) r.classList.toggle('cur', k === s.key);
|
||||||
|
this.chip.textContent = `${dayName(m.t, d.now)}, ${clock(m.t)} · ${s.point.city || s.point.cc || '?'}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Back to now: the map as it is, and whatever came while the replay ran. */
|
||||||
|
private end() {
|
||||||
|
cancelAnimationFrame(this.raf);
|
||||||
|
clearTimeout(this.endTimer);
|
||||||
|
if (!this.on) return;
|
||||||
|
this.on = false;
|
||||||
|
this.playing = false;
|
||||||
|
this.ms = 0;
|
||||||
|
this.stepI = -1;
|
||||||
|
this.map.band();
|
||||||
|
this.map.replay(null, false);
|
||||||
|
this.el.classList.remove('replay');
|
||||||
|
for (const r of this.rows.values()) r.classList.remove('cur');
|
||||||
|
if (this.pending) {
|
||||||
|
this.data = this.pending;
|
||||||
|
this.pending = null;
|
||||||
|
this.map.update(this.mapData());
|
||||||
|
this.paint();
|
||||||
|
} else this.paintControls();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,9 @@
|
|||||||
|
|
||||||
/* dialogs */
|
/* dialogs */
|
||||||
.dl-modal .cbi-tabmenu { margin-bottom: 16px; }
|
.dl-modal .cbi-tabmenu { margin-bottom: 16px; }
|
||||||
|
/* A dialog field checked as you type: its help under the label, as on the cards. */
|
||||||
|
.dl-modal .cbi-value.dl-live > .cbi-value-title { display: flex; flex-direction: column; gap: 2px; text-align: left; }
|
||||||
|
.dl-modal .cbi-value.dl-live > .cbi-value-title > .dl-sub { white-space: normal; }
|
||||||
/* A list of things to tick (devices to remove with an old link). */
|
/* A list of things to tick (devices to remove with an old link). */
|
||||||
.dl-checklist { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 8px; }
|
.dl-checklist { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 8px; }
|
||||||
.dl-checklist label { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; }
|
.dl-checklist label { display: flex; align-items: center; gap: 8px; font-size: 14px; cursor: pointer; }
|
||||||
|
|||||||
@@ -51,6 +51,43 @@
|
|||||||
.dl-dplace-n.live { background: #3b82f6; color: #fff; }
|
.dl-dplace-n.live { background: #3b82f6; color: #fff; }
|
||||||
.dl-dplace-n .dl-icon { width: 12px; height: 12px; }
|
.dl-dplace-n .dl-icon { width: 12px; height: 12px; }
|
||||||
.dl-dplace-now { color: #3b82f6; }
|
.dl-dplace-now { color: #3b82f6; }
|
||||||
|
/* With the log's connections, each place has a strip: when the device was there in the range (the
|
||||||
|
live place's blue). The highlight (hover, the replay's place) reaches past the content on both
|
||||||
|
sides, the separators stay with the content. */
|
||||||
|
.dl-dplaces.strips .dl-dplace-row { position: relative; display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; column-gap: 10px; row-gap: 9px;
|
||||||
|
margin: 0 -10px; padding: 11px 10px; border-top: 0; border-radius: 10px; transition: background .15s; }
|
||||||
|
.dl-dplaces.strips .dl-dplace-row + .dl-dplace-row::before { content: ''; position: absolute; left: 10px; right: 10px; top: 0; height: 1px; background: var(--dl-line); }
|
||||||
|
.dl-dplaces.strips .dl-dplace-row:is(:hover, .cur) { background: var(--dl-soft); }
|
||||||
|
.dl-dplaces.strips .dl-dplace-row:is(:hover, .cur)::before, .dl-dplaces.strips .dl-dplace-row:is(:hover, .cur) + .dl-dplace-row::before { opacity: 0; }
|
||||||
|
.dl-dplace-strip { grid-column: 2 / 4; position: relative; height: 6px; border-radius: 3px; background: var(--dl-track); }
|
||||||
|
.dl-dplaces.can-replay .dl-dplace-strip { cursor: ew-resize; touch-action: none; }
|
||||||
|
.dl-dplace-strip i { position: absolute; top: 0; bottom: 0; min-width: 2px; border-radius: 2px; background: #8a8a8a; }
|
||||||
|
.dl-dplace-strip.live i { background: #3b82f6; }
|
||||||
|
/* The replay's moment: a tick on every strip. */
|
||||||
|
.dl-dplaces.replay .dl-dplace-strip::after { content: ''; position: absolute; left: var(--at); top: -4px; bottom: -4px; width: 2px; margin-left: -1px; border-radius: 1px;
|
||||||
|
background: var(--dl-fg); box-shadow: 0 0 0 2px var(--dialog-bg, var(--dl-elevated)); pointer-events: none; }
|
||||||
|
.dl-dplace-axis { position: relative; height: 16px; margin: 4px 0 0 30px; font-size: 11px; line-height: 16px; color: var(--dl-fg-faint); }
|
||||||
|
.dl-dplace-axis span { position: absolute; top: 0; transform: translateX(-50%); white-space: nowrap; }
|
||||||
|
/* The replay's controls in the map's top corner, and the place it lights. */
|
||||||
|
.dl-dmap { position: relative; }
|
||||||
|
.dl-map-replay { position: absolute; left: 10px; top: 10px; z-index: 3; display: flex; align-items: center; gap: 6px; }
|
||||||
|
.dl-map-btn { all: unset; box-sizing: border-box; cursor: pointer; width: 28px; height: 28px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center;
|
||||||
|
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg); }
|
||||||
|
.dl-map-btn:hover { background: color-mix(in srgb, var(--dl-fg) 8%, var(--dl-elevated)); }
|
||||||
|
.dl-map-btn:focus-visible { outline: 2px solid var(--dl-ring); }
|
||||||
|
.dl-map-btn .dl-icon { width: 13px; height: 13px; }
|
||||||
|
.dl-map-chip { display: inline-flex; align-items: center; height: 28px; box-sizing: border-box; padding: 0 10px; border-radius: 8px; font-size: 11.5px; white-space: nowrap;
|
||||||
|
background: var(--dl-elevated); border: 1px solid var(--dl-line); color: var(--dl-fg); font-variant-numeric: tabular-nums; }
|
||||||
|
.dl-mk.step .dl-mk-tile { transition: width .3s cubic-bezier(.2, .8, .2, 1), height .3s cubic-bezier(.2, .8, .2, 1), border-radius .3s, background-color .3s, color .3s,
|
||||||
|
box-shadow .3s, transform .24s; }
|
||||||
|
.dl-mk.step .dl-mk-tile.sm .dl-mk-tile-ic { width: 11px; height: 11px; }
|
||||||
|
.dl-mk.step.faded > * { opacity: .5; }
|
||||||
|
/* The place in the light (or hovered in the list) over its neighbours, its name readable. */
|
||||||
|
.dl-mk.step:is(.online, .hl) { z-index: 2; }
|
||||||
|
.dl-mk.step.hl .dl-mk-tile { box-shadow: 0 0 0 3px color-mix(in srgb, #3b82f6 55%, transparent); }
|
||||||
|
.dl-mk.step.arrive .dl-mk-tile { animation: dl-mk-arrive .45s cubic-bezier(.2, .8, .2, 1); }
|
||||||
|
@keyframes dl-mk-arrive { 0% { transform: scale(.8); } 55% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||||
|
.dl-mk-when.inline { display: inline; }
|
||||||
/* Someone on top of the server: folded into a count on its plate until there is room. */
|
/* Someone on top of the server: folded into a count on its plate until there is room. */
|
||||||
/* MapLibre writes the marker's own opacity (fading what is behind the globe): ours goes on its parts. */
|
/* MapLibre writes the marker's own opacity (fading what is behind the globe): ours goes on its parts. */
|
||||||
.dl-mk > * { transition: opacity .15s; opacity: var(--dl-mk-fade, 1); }
|
.dl-mk > * { transition: opacity .15s; opacity: var(--dl-mk-fade, 1); }
|
||||||
@@ -116,14 +153,15 @@
|
|||||||
.dl-lod-far .dl-mk-more { margin-left: 4px; font-size: 10px; }
|
.dl-lod-far .dl-mk-more { margin-left: 4px; font-size: 10px; }
|
||||||
/* Place names only from the country level: far out they would crowd the plates. */
|
/* Place names only from the country level: far out they would crowd the plates. */
|
||||||
.dl-mk-label { transition: opacity .2s ease; }
|
.dl-mk-label { transition: opacity .2s ease; }
|
||||||
.dl-lod-far .dl-mk-label { opacity: 0; }
|
/* A device's few places keep their names at any distance. */
|
||||||
|
.dl-lod-far .dl-mk:not(.step) .dl-mk-label { opacity: 0; }
|
||||||
.dl-lod-mid .dl-mk-host { width: 36px; height: 36px; }
|
.dl-lod-mid .dl-mk-host { width: 36px; height: 36px; }
|
||||||
.dl-lod-mid .dl-mk-dock, .dl-lod-mid .dl-mk-pile-box { height: 36px; }
|
.dl-lod-mid .dl-mk-dock, .dl-lod-mid .dl-mk-pile-box { height: 36px; }
|
||||||
.dl-lod-mid .dl-mk-face .dl-mk-av { width: 24px; height: 24px; font-size: 9px; }
|
.dl-lod-mid .dl-mk-face .dl-mk-av { width: 24px; height: 24px; font-size: 9px; }
|
||||||
.dl-lod-mid .dl-mk-face > .dl-mk-badge { height: 12px; min-width: 12px; margin-left: -10px; bottom: -7px; }
|
.dl-lod-mid .dl-mk-face > .dl-mk-badge { height: 12px; min-width: 12px; margin-left: -10px; bottom: -7px; }
|
||||||
.dl-lod-mid .dl-mk-face > .dl-mk-badge:has(> svg:only-child) { width: 12px; }
|
.dl-lod-mid .dl-mk-face > .dl-mk-badge:has(> svg:only-child) { width: 12px; }
|
||||||
.dl-lod-mid .dl-mk-face > .dl-mk-badge .dl-mk-badge-ic { width: 8px; height: 8px; }
|
.dl-lod-mid .dl-mk-face > .dl-mk-badge .dl-mk-badge-ic { width: 8px; height: 8px; }
|
||||||
@media (prefers-reduced-motion: reduce) { .dl-mk-dock, .dl-mk-pile-box, .dl-mk-face, .dl-mk-av, .dl-mk-tile, .dl-mk-host, .dl-mk-face > .dl-mk-badge { transition: none; animation: none; } }
|
@media (prefers-reduced-motion: reduce) { .dl-mk-dock, .dl-mk-pile-box, .dl-mk-face, .dl-mk-av, .dl-mk-tile, .dl-mk.step .dl-mk-tile, .dl-mk-host, .dl-mk-face > .dl-mk-badge { transition: none; animation: none; } }
|
||||||
.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host { cursor: zoom-in; }
|
.dl-mk-hub:has(.dl-mk-host.docked) .dl-mk-host { cursor: zoom-in; }
|
||||||
/* A marker moved clear of a crowd: a line back to its real spot, and a dot there. */
|
/* A marker moved clear of a crowd: a line back to its real spot, and a dot there. */
|
||||||
.dl-mk-ptr { position: absolute; left: 50%; top: 50%; width: 0; height: 0; z-index: -1; pointer-events: none; }
|
.dl-mk-ptr { position: absolute; left: 50%; top: 50%; width: 0; height: 0; z-index: -1; pointer-events: none; }
|
||||||
|
|||||||
@@ -99,6 +99,8 @@
|
|||||||
.dl-disg-ic { width: 36px; height: 36px; border-radius: 11px; background: color-mix(in srgb, var(--dl-accent) 14%, transparent); color: var(--dl-accent);
|
.dl-disg-ic { width: 36px; height: 36px; border-radius: 11px; background: color-mix(in srgb, var(--dl-accent) 14%, transparent); color: var(--dl-accent);
|
||||||
display: inline-flex; align-items: center; justify-content: center; flex: none; }
|
display: inline-flex; align-items: center; justify-content: center; flex: none; }
|
||||||
.dl-disg-ic .dl-icon-wrap { display: inline-flex; } .dl-disg-ic .dl-icon { width: 18px; height: 18px; }
|
.dl-disg-ic .dl-icon-wrap { display: inline-flex; } .dl-disg-ic .dl-icon { width: 18px; height: 18px; }
|
||||||
|
/* No disguise: gray, as the picker's unselected methods. */
|
||||||
|
.dl-disg-ic.off { background: var(--dl-soft); color: var(--dl-fg-muted); }
|
||||||
.dl-disg-meters { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; align-items: center; font-size: 12px; color: var(--dl-fg-muted); }
|
.dl-disg-meters { display: grid; grid-template-columns: auto 1fr; gap: 6px 10px; align-items: center; font-size: 12px; color: var(--dl-fg-muted); }
|
||||||
.dl-segs { display: inline-flex; gap: 3px; } .dl-segs i { width: 18px; height: 5px; border-radius: 3px; background: var(--dl-track); }
|
.dl-segs { display: inline-flex; gap: 3px; } .dl-segs i { width: 18px; height: 5px; border-radius: 3px; background: var(--dl-track); }
|
||||||
.dl-segs.acc i.on { background: var(--dl-accent); } .dl-segs.ok i.on { background: var(--dl-ok); }
|
.dl-segs.acc i.on { background: var(--dl-accent); } .dl-segs.ok i.on { background: var(--dl-ok); }
|
||||||
|
|||||||
@@ -34,8 +34,9 @@
|
|||||||
.dl-chip:hover { background: var(--dl-soft-hover); }
|
.dl-chip:hover { background: var(--dl-soft-hover); }
|
||||||
.dl-chip:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; }
|
.dl-chip:focus-visible { outline: 2px solid var(--dl-ring); outline-offset: 2px; }
|
||||||
.dl-chip .dl-icon { width: 14px; height: 14px; color: var(--dl-fg-muted); }
|
.dl-chip .dl-icon { width: 14px; height: 14px; color: var(--dl-fg-muted); }
|
||||||
.dl-chip.add { background: transparent; box-shadow: inset 0 0 0 1px var(--dl-line); color: var(--dl-fg-muted); aspect-ratio: 1; padding: 0; justify-content: center; }
|
.dl-chip.add { background: transparent; border: 1px dashed color-mix(in srgb, var(--dl-fg) 28%, transparent); color: var(--dl-fg-muted); }
|
||||||
.dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); }
|
.dl-chip.add:hover { background: var(--dl-soft); color: var(--dl-fg); border-color: color-mix(in srgb, var(--dl-fg) 45%, transparent); }
|
||||||
|
.dl-chip.add:hover .dl-icon { color: var(--dl-fg); }
|
||||||
.dl-chip.disabled .dl-chip-name { text-decoration: line-through; color: var(--dl-fg-faint); }
|
.dl-chip.disabled .dl-chip-name { text-decoration: line-through; color: var(--dl-fg-faint); }
|
||||||
.dl-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.dl-chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.dl-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); opacity: .6; }
|
.dl-dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%; background: var(--dl-fg-faint); opacity: .6; }
|
||||||
@@ -56,3 +57,6 @@
|
|||||||
.cbi-value.dl-block { display: block !important; }
|
.cbi-value.dl-block { display: block !important; }
|
||||||
.cbi-value.dl-block > .cbi-value-title { display: block; width: auto; float: none; text-align: left; padding: 0 0 8px; }
|
.cbi-value.dl-block > .cbi-value-title { display: block; width: auto; float: none; text-align: left; padding: 0 0 8px; }
|
||||||
.cbi-value.dl-block > .cbi-value-field { display: block; width: 100%; margin: 0; }
|
.cbi-value.dl-block > .cbi-value-field { display: block; width: 100%; margin: 0; }
|
||||||
|
/* Find (shown once the list is long): a compact search field beside the sort. */
|
||||||
|
.dl-people-find { width: 160px; min-width: 0; }
|
||||||
|
.dl-people-find[hidden] { display: none; }
|
||||||
@@ -47,7 +47,9 @@
|
|||||||
.dl-pgrid.flush { padding: 0; grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
.dl-pgrid.flush { padding: 0; grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||||
@media (max-width: 640px) { .dl-pgrid.flush { grid-template-columns: minmax(0, 1fr); } }
|
@media (max-width: 640px) { .dl-pgrid.flush { grid-template-columns: minmax(0, 1fr); } }
|
||||||
.dl-qr-pane { display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; }
|
.dl-qr-pane { display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; }
|
||||||
.dl-qr { width: min(280px, 72vw); aspect-ratio: 1; background: #fff; padding: 8px; border-radius: 12px; box-shadow: inset 0 0 0 1px var(--dl-line); }
|
.dl-qr { width: min(280px, 72vw); aspect-ratio: 1; background: #0a0a0a; border-radius: 18px; overflow: hidden; }
|
||||||
|
/* The portal's round look: its own card colour (black at night, white by day), the light one ringed. */
|
||||||
|
.dl-qr.light { background: #fff; box-shadow: inset 0 0 0 1px var(--dl-line); }
|
||||||
.dl-qr svg { display: block; width: 100%; height: 100%; }
|
.dl-qr svg { display: block; width: 100%; height: 100%; }
|
||||||
.dl-filecard { display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 14px; background: var(--dl-soft); min-width: 0; }
|
.dl-filecard { display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 14px; background: var(--dl-soft); min-width: 0; }
|
||||||
.dl-filecard > .dl-stack { flex: 1; min-width: 0; }
|
.dl-filecard > .dl-stack { flex: 1; min-width: 0; }
|
||||||
|
|||||||
@@ -49,13 +49,28 @@ export function accessBadge(p: Person): HTMLElement {
|
|||||||
return el;
|
return el;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Why a person's devices cannot connect right now, in two words. */
|
||||||
|
const STOPPED: Partial<Record<Person['state'], string>> = {
|
||||||
|
paused: 'Paused',
|
||||||
|
expired: 'Access ended',
|
||||||
|
quota: 'Data limit',
|
||||||
|
hours: 'Outside hours',
|
||||||
|
server_off: 'Server off',
|
||||||
|
no_server: 'No server',
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A device's status as coloured text, no dots (only avatars carry one). `now`
|
* A device's status as coloured text, no dots (only avatars carry one). `now`
|
||||||
* is the router's clock; `waiting` is the text before the first connection.
|
* is the router's clock; `waiting` is the text before the first connection.
|
||||||
|
* With the person, a device that cannot come back says why ("Paused",
|
||||||
|
* "Data limit") instead of a "Last seen" that reads like it might.
|
||||||
*/
|
*/
|
||||||
export function deviceStatus(d: Device, now?: number, waiting = 'Not set up yet'): HTMLElement {
|
export function deviceStatus(d: Device, now?: number, waiting = 'Not set up yet', p?: Person): HTMLElement {
|
||||||
if (d.disabled) return E('span', { class: 'dl-dstat' }, 'Disabled');
|
const seen = d.handshake ? `Last seen ${ago(d.handshake, now)} · ${new Date(d.handshake * 1000).toLocaleString()}` : '';
|
||||||
|
if (d.disabled) return E('span', { class: 'dl-dstat', title: seen }, 'Disabled');
|
||||||
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
|
if (d.online) return E('span', { class: 'dl-dstat ok' }, 'Connected');
|
||||||
|
const why = p && STOPPED[p.state];
|
||||||
|
if (why) return E('span', { class: 'dl-dstat warn', title: seen || 'Not connected yet' }, why);
|
||||||
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, waiting);
|
if (!d.handshake) return E('span', { class: 'dl-dstat warn', title: 'Waiting for the first connection' }, waiting);
|
||||||
return E('span', { class: 'dl-dstat' }, `Last seen ${ago(d.handshake, now)}`);
|
return E('span', { class: 'dl-dstat', title: new Date(d.handshake * 1000).toLocaleString() }, `Last seen ${ago(d.handshake, now)}`);
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,13 @@
|
|||||||
import { E } from '../e';
|
import { E } from '../e';
|
||||||
import { errorText, notify } from './toast';
|
import { errorText, notify } from './toast';
|
||||||
|
|
||||||
export async function copyText(text: string, what = 'Copied to clipboard') {
|
/**
|
||||||
|
* Copy to the clipboard and say so. `quiet`: a copy that is a convenience
|
||||||
|
* after something else (a link right after creating a person): browsers
|
||||||
|
* refuse a write outside the click that started it (Safari after an await),
|
||||||
|
* and then nothing is said — the link is on screen with its own Copy button.
|
||||||
|
*/
|
||||||
|
export async function copyText(text: string, what = 'Copied to clipboard', quiet = false): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
if (navigator.clipboard && window.isSecureContext) {
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
await navigator.clipboard.writeText(text);
|
await navigator.clipboard.writeText(text);
|
||||||
@@ -16,8 +22,10 @@ export async function copyText(text: string, what = 'Copied to clipboard') {
|
|||||||
if (!ok) throw new Error('Copying is blocked here. Select the text and copy it by hand.');
|
if (!ok) throw new Error('Copying is blocked here. Select the text and copy it by hand.');
|
||||||
}
|
}
|
||||||
notify(what, 'success', 2500);
|
notify(what, 'success', 2500);
|
||||||
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
notify(errorText(e), 'error');
|
if (!quiet) notify(errorText(e), 'error');
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,8 +23,8 @@ export function liveRow(
|
|||||||
el: HTMLInputElement,
|
el: HTMLInputElement,
|
||||||
help: () => { text: string; bad: boolean },
|
help: () => { text: string; bad: boolean },
|
||||||
control: Node = el,
|
control: Node = el,
|
||||||
): HTMLElement & { refresh: () => void } {
|
): HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } } {
|
||||||
const r = row(label, control, ' ') as HTMLElement & { refresh: () => void };
|
const r = row(label, control, ' ') as HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } };
|
||||||
const sub = r.querySelector('.dl-sub') as HTMLElement;
|
const sub = r.querySelector('.dl-sub') as HTMLElement;
|
||||||
const paint = () => {
|
const paint = () => {
|
||||||
const h = help();
|
const h = help();
|
||||||
@@ -34,10 +34,57 @@ export function liveRow(
|
|||||||
};
|
};
|
||||||
el.addEventListener('input', paint);
|
el.addEventListener('input', paint);
|
||||||
r.refresh = paint;
|
r.refresh = paint;
|
||||||
|
r.help = help;
|
||||||
paint();
|
paint();
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* liveRow for a dialog field (LuCI's cbi-value layout: label beside the
|
||||||
|
* control, the help under the label as on the cards). Same contract: `help`
|
||||||
|
* repaints on input, `refresh()` when something else changes.
|
||||||
|
*/
|
||||||
|
export function liveField(
|
||||||
|
label: string,
|
||||||
|
el: HTMLInputElement | HTMLSelectElement,
|
||||||
|
help: () => { text: string; bad: boolean },
|
||||||
|
control: Node = el,
|
||||||
|
): HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } } {
|
||||||
|
const sub = E('div', { class: 'dl-sub' });
|
||||||
|
const r = E('div', { class: 'cbi-value dl-live' }, [
|
||||||
|
E('div', { class: 'cbi-value-title' }, [E('label', {}, label), sub]),
|
||||||
|
E('div', { class: 'cbi-value-field' }, control),
|
||||||
|
]) as HTMLElement & { refresh: () => void; help: () => { text: string; bad: boolean } };
|
||||||
|
const paint = () => {
|
||||||
|
const h = help();
|
||||||
|
sub.textContent = h.text;
|
||||||
|
sub.classList.toggle('bad', h.bad);
|
||||||
|
el.classList.toggle('cbi-input-invalid', h.bad);
|
||||||
|
};
|
||||||
|
el.addEventListener('input', paint);
|
||||||
|
el.addEventListener('change', paint);
|
||||||
|
r.refresh = paint;
|
||||||
|
r.help = help;
|
||||||
|
paint();
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first problem among live rows (their help as it stands), or null: what refuses a Save. */
|
||||||
|
export function firstBad(
|
||||||
|
rows: { help?: () => { text: string; bad: boolean } }[],
|
||||||
|
helps: (() => { text: string; bad: boolean })[] = [],
|
||||||
|
): string | null {
|
||||||
|
for (const r of rows) {
|
||||||
|
const h = r.help?.();
|
||||||
|
if (h?.bad) return h.text;
|
||||||
|
}
|
||||||
|
for (const f of helps) {
|
||||||
|
const h = f();
|
||||||
|
if (h.bad) return h.text;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/** A section card with its own footer (Save etc.). */
|
/** A section card with its own footer (Save etc.). */
|
||||||
export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement {
|
export function card(title: string, body: (Node | string)[], foot: (Node | string)[], extra = ''): HTMLElement {
|
||||||
return E('section', { class: `dl-setsec ${extra}` }, [
|
return E('section', { class: `dl-setsec ${extra}` }, [
|
||||||
|
|||||||
@@ -53,7 +53,22 @@ export function dropdown(anchor: HTMLElement, items: (MenuItem | null)[]) {
|
|||||||
if (!menu.contains(ev.target as Node) && !anchor.contains(ev.target as Node)) close();
|
if (!menu.contains(ev.target as Node) && !anchor.contains(ev.target as Node)) close();
|
||||||
};
|
};
|
||||||
const onKey = (ev: KeyboardEvent) => {
|
const onKey = (ev: KeyboardEvent) => {
|
||||||
if (ev.key === 'Escape') close();
|
if (ev.key === 'Escape' || ev.key === 'Tab') return close();
|
||||||
|
// Arrow keys walk the items (wrapping), Home/End jump; a menu that has the
|
||||||
|
// keyboard focus must not scroll the page under it.
|
||||||
|
const items = [...menu.querySelectorAll<HTMLButtonElement>('button:not([disabled])')];
|
||||||
|
if (!items.length || !['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(ev.key)) return;
|
||||||
|
ev.preventDefault();
|
||||||
|
const i = items.indexOf(document.activeElement as HTMLButtonElement);
|
||||||
|
const next =
|
||||||
|
ev.key === 'Home'
|
||||||
|
? 0
|
||||||
|
: ev.key === 'End'
|
||||||
|
? items.length - 1
|
||||||
|
: ev.key === 'ArrowDown'
|
||||||
|
? (i + 1) % items.length
|
||||||
|
: (i - 1 + items.length) % items.length;
|
||||||
|
items[next].focus({ preventScroll: true });
|
||||||
};
|
};
|
||||||
const offNav = onNavigate(close);
|
const offNav = onNavigate(close);
|
||||||
menu.dlAnchor = anchor;
|
menu.dlAnchor = anchor;
|
||||||
|
|||||||
@@ -17,7 +17,27 @@ function settle(ok = false) {
|
|||||||
|
|
||||||
export function modal(title: string, body: Child, actions: Child, cls = '') {
|
export function modal(title: string, body: Child, actions: Child, cls = '') {
|
||||||
settle();
|
settle();
|
||||||
ui.showModal(title, [E('div', { class: `dl-modal ${cls}` }, body), E('div', { class: 'button-row' }, actions)]);
|
const bodyEl = E('div', { class: `dl-modal ${cls}` }, body);
|
||||||
|
const rowEl = E('div', { class: 'button-row' }, actions);
|
||||||
|
// Enter in a field submits: the dialog's positive button (buttons, selects
|
||||||
|
// and text areas keep their own Enter).
|
||||||
|
bodyEl.addEventListener('keydown', (ev: KeyboardEvent) => {
|
||||||
|
// Escape closes the dialog only: a drawer under it stays (it listens on the document).
|
||||||
|
if (ev.key === 'Escape') {
|
||||||
|
ev.preventDefault();
|
||||||
|
ev.stopPropagation();
|
||||||
|
closeModal();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ev.key !== 'Enter' || ev.shiftKey || ev.ctrlKey || ev.metaKey || ev.altKey) return;
|
||||||
|
const t = ev.target as HTMLElement;
|
||||||
|
if (!t || ['TEXTAREA', 'BUTTON', 'SELECT', 'A'].includes(t.tagName)) return;
|
||||||
|
const go = rowEl.querySelector<HTMLButtonElement>('.cbi-button-positive');
|
||||||
|
if (!go || go.disabled) return;
|
||||||
|
ev.preventDefault();
|
||||||
|
go.click();
|
||||||
|
});
|
||||||
|
ui.showModal(title, [bodyEl, rowEl]);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function closeModal() {
|
export function closeModal() {
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// A device's QR code, in the portal's round look: light dots on black on the
|
||||||
|
// dark theme, the same dots dark on white on a light one (shared/qr.ts).
|
||||||
|
|
||||||
|
import { qrSvg } from '../../shared/qr';
|
||||||
|
import { svg } from './layout';
|
||||||
|
import { isDark } from './theme';
|
||||||
|
|
||||||
|
export function qrCode(text: string): HTMLElement {
|
||||||
|
const dark = isDark();
|
||||||
|
return svg(qrSvg(text, 3, true, dark ? 'night' : 'day'), `dl-qr${dark ? '' : ' light'}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// Which theme the admin shows: Outline switches light and dark in place with
|
||||||
|
// html[data-darkmode]; without it, the system's choice. Read where something
|
||||||
|
// is drawn in the theme's own colours (the map, QR codes).
|
||||||
|
|
||||||
|
export function isDark(): boolean {
|
||||||
|
const attr = document.documentElement.getAttribute('data-darkmode');
|
||||||
|
if (attr != null) return attr === 'true';
|
||||||
|
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
|
||||||
|
}
|
||||||
@@ -34,6 +34,13 @@ export function attachTip(el: HTMLElement, content: () => (Node | string)[]) {
|
|||||||
el.addEventListener('mouseenter', show);
|
el.addEventListener('mouseenter', show);
|
||||||
el.addEventListener('mousemove', show);
|
el.addEventListener('mousemove', show);
|
||||||
el.addEventListener('mouseleave', hideTip);
|
el.addEventListener('mouseleave', hideTip);
|
||||||
|
// No hover on a touch screen: a tap on the anchor shows it, the next tap
|
||||||
|
// anywhere (the document listener below) hides it.
|
||||||
|
el.addEventListener('pointerup', (ev: PointerEvent) => {
|
||||||
|
if (ev.pointerType === 'mouse') return;
|
||||||
|
if (anchor === el) hideTip();
|
||||||
|
else show(ev as unknown as MouseEvent);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onNavigate(hideTip);
|
onNavigate(hideTip);
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// The portal's API: one fetch per call to the router, under the personal link.
|
||||||
|
// No sessions and no cookies: the code in the path is the key. A refused call
|
||||||
|
// throws an ApiError carrying the status and, for a plain-HTTP visitor, the
|
||||||
|
// HTTPS twin of the link.
|
||||||
|
|
||||||
|
import { base } from './state';
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
public status: number,
|
||||||
|
message: string,
|
||||||
|
/** The HTTPS twin of this link, when the answer was "not over plain HTTP". */
|
||||||
|
public httpsUrl?: string,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function call<T>(path: string, body?: unknown): Promise<T> {
|
||||||
|
const res = await fetch(`${base}/api/${path}`, {
|
||||||
|
method: body === undefined ? 'GET' : 'POST',
|
||||||
|
credentials: 'omit',
|
||||||
|
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
// Any shape: an error answer may be empty or not JSON at all.
|
||||||
|
let data: { error?: string; https_url?: string } | null = null;
|
||||||
|
try {
|
||||||
|
data = await res.json();
|
||||||
|
} catch {
|
||||||
|
/* empty */
|
||||||
|
}
|
||||||
|
if (!res.ok) throw new ApiError(res.status, data?.error ?? `Request failed (${res.status})`, data?.https_url || undefined);
|
||||||
|
return data as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The link stopped working (code regenerated, person removed). */
|
||||||
|
export const gone = (e: unknown) => e instanceof ApiError && (e.status === 404 || e.status === 401);
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// The days and hours the access section draws, as plain data: the weeks left
|
||||||
|
// as a calendar, the admin's hours moved into the visitor's time, the month as
|
||||||
|
// one bar a day. Pure (no DOM): page/access.ts draws it; dates are the
|
||||||
|
// router's (`today` from its state), never the browser's calendar.
|
||||||
|
|
||||||
|
import { addDays, parseDay } from '../shared/format';
|
||||||
|
|
||||||
|
export type CellKind = 'past' | 'today' | 'left' | 'end' | 'after';
|
||||||
|
export interface Cell {
|
||||||
|
day: string;
|
||||||
|
kind: CellKind;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The weeks from this one to the one the access ends in, Monday first, one
|
||||||
|
* cell a day: gone, today, left, the last day, after it. Null when that would
|
||||||
|
* take more than `maxWeeks` (far ends: the number of days says it alone).
|
||||||
|
*/
|
||||||
|
export function calendar(today: string, end: string, maxWeeks = 10): Cell[] | null {
|
||||||
|
const dow = (d: string) => (parseDay(d).getDay() + 6) % 7;
|
||||||
|
const first = addDays(today, -dow(today));
|
||||||
|
const last = addDays(end, 6 - dow(end));
|
||||||
|
const cells: Cell[] = [];
|
||||||
|
for (let d = first; d <= last; d = addDays(d, 1)) {
|
||||||
|
cells.push({ day: d, kind: d < today ? 'past' : d === today ? 'today' : d < end ? 'left' : d === end ? 'end' : 'after' });
|
||||||
|
if (cells.length > maxWeeks * 7) return null;
|
||||||
|
}
|
||||||
|
return cells;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
|
||||||
|
/** "08:30" → 510, or null for anything else. */
|
||||||
|
export function minuteOf(t: string): number | null {
|
||||||
|
const m = HM.exec(t.trim());
|
||||||
|
return m ? +m[1] * 60 + +m[2] : null;
|
||||||
|
}
|
||||||
|
const wrap = (m: number) => ((m % 1440) + 1440) % 1440;
|
||||||
|
export const clockOf = (m: number) => `${String(Math.floor(wrap(m) / 60)).padStart(2, '0')}:${String(wrap(m) % 60).padStart(2, '0')}`;
|
||||||
|
|
||||||
|
export interface Hours {
|
||||||
|
/** Start and end, minutes after midnight in the visitor's time. */
|
||||||
|
from: number;
|
||||||
|
to: number;
|
||||||
|
/** In the visitor's time (the router told its offset), or the router's own. */
|
||||||
|
yours: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The admin's hours ("08:00-22:00", router time) in the visitor's time. The
|
||||||
|
* offsets are minutes east of UTC; without the router's offset the hours stay
|
||||||
|
* in the router's time. Null when they cannot be read.
|
||||||
|
*/
|
||||||
|
export function hoursFor(hours: string, routerOffset: number | undefined, visitorOffset: number): Hours | null {
|
||||||
|
const [a, b] = hours.split('-');
|
||||||
|
const from = minuteOf(a ?? '');
|
||||||
|
const to = minuteOf(b ?? '');
|
||||||
|
if (from == null || to == null) return null;
|
||||||
|
const shift = routerOffset == null ? 0 : visitorOffset - routerOffset;
|
||||||
|
return { from: wrap(from + shift), to: wrap(to + shift), yours: routerOffset != null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The window as stretches of the day: one, or two when it runs past midnight. */
|
||||||
|
export const stretches = (h: Hours): [number, number][] =>
|
||||||
|
h.from < h.to
|
||||||
|
? [[h.from, h.to]]
|
||||||
|
: [
|
||||||
|
[h.from, 1440],
|
||||||
|
[0, h.to],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** The moment `nowSec` (epoch seconds) as minutes after midnight at `offset` minutes east of UTC. */
|
||||||
|
export const minuteAt = (nowSec: number, offset: number) => wrap(Math.floor(nowSec / 60) + offset);
|
||||||
|
|
||||||
|
/** The days of today's month: how many, and which one today is (1-based). */
|
||||||
|
export function monthOf(today: string): { days: number; day: number } {
|
||||||
|
const d = parseDay(today);
|
||||||
|
return { days: new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate(), day: d.getDate() };
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// The portal's DOM builders: an element from a tag, attributes and children;
|
||||||
|
// an icon; markup that is ours (icons, glass icons, QR codes) as an element.
|
||||||
|
// No framework. The page's CSP forbids inline styles, so nothing here writes a
|
||||||
|
// `style` attribute: styles set from script go through `el.style`.
|
||||||
|
|
||||||
|
import { iconSvg } from '../shared/icons';
|
||||||
|
|
||||||
|
export type Attrs = Record<string, string | number | boolean | EventListener | null | undefined>;
|
||||||
|
export type Kid = Node | string | null | undefined | false | Kid[];
|
||||||
|
|
||||||
|
function append(el: Node, kids: Kid[]) {
|
||||||
|
const add = (c: Kid) => {
|
||||||
|
if (c == null || c === false) return;
|
||||||
|
if (Array.isArray(c)) c.forEach(add);
|
||||||
|
else el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
|
||||||
|
};
|
||||||
|
kids.forEach(add);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function h(tag: string, attrs: Attrs = {}, ...kids: Kid[]): HTMLElement {
|
||||||
|
const el = document.createElement(tag);
|
||||||
|
for (const [k, v] of Object.entries(attrs)) {
|
||||||
|
if (v == null || v === false) continue;
|
||||||
|
if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v as EventListener);
|
||||||
|
else if (k === 'class') el.className = String(v);
|
||||||
|
else if (v === true) el.setAttribute(k, '');
|
||||||
|
else el.setAttribute(k, String(v));
|
||||||
|
}
|
||||||
|
append(el, kids);
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replace what `el` holds with `kids` (nested lists flattened, empty ones skipped). */
|
||||||
|
export function put(el: HTMLElement, ...kids: Kid[]) {
|
||||||
|
el.replaceChildren();
|
||||||
|
append(el, kids);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Our own markup (never anything a visitor or the router typed) as one element. */
|
||||||
|
export function markup(html: string): Element {
|
||||||
|
const t = document.createElement('template');
|
||||||
|
t.innerHTML = html.trim();
|
||||||
|
return t.content.firstElementChild!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A line icon (`svg.i`, stroke = currentColor), sized by CSS. */
|
||||||
|
export const ic = (name: string, cls = 'i'): Element => markup(iconSvg(name, cls));
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
// Adding a device: what it is (four kinds; phones and tablets are one choice,
|
||||||
|
// the same apps and the same smaller packets) and its name, guessed from the
|
||||||
|
// browser when it is this device; then straight on to its set-up. Or the page
|
||||||
|
// opens on the device itself, from a code, ready to add it there.
|
||||||
|
|
||||||
|
import type { ClientConfig, Kind } from '../../shared/types';
|
||||||
|
import { KIND_LABEL } from '../../shared/format';
|
||||||
|
import { ApiError, call } from '../api';
|
||||||
|
import { h, ic } from '../dom';
|
||||||
|
import { EASE_OUT, play } from '../motion';
|
||||||
|
import { addLink } from '../setup';
|
||||||
|
import { pageUrl, repaint, setState, state, type State } from '../state';
|
||||||
|
import { linkRow, qrBox } from '../ui/codes';
|
||||||
|
import { once, toast } from '../ui/feedback';
|
||||||
|
import { glass } from '../ui/glass';
|
||||||
|
import { morphText } from '../ui/morph';
|
||||||
|
import { go, head, hint, openSheet, sub, type View } from '../ui/sheet';
|
||||||
|
import { secureFirst, showSecure } from './secure';
|
||||||
|
import { continueSetup } from './setup-view';
|
||||||
|
|
||||||
|
// Best guess at the device this page is open on (the browser never tells its real name).
|
||||||
|
const UA = navigator.userAgent;
|
||||||
|
const IPAD = /iPad/.test(UA) || (/Macintosh/.test(UA) && navigator.maxTouchPoints > 1);
|
||||||
|
|
||||||
|
function guessKind(): Kind {
|
||||||
|
if (IPAD || /Tablet/i.test(UA) || (/Android/.test(UA) && !/Mobile/.test(UA))) return 'tablet';
|
||||||
|
if (/Android|iPhone|Mobile/i.test(UA)) return 'phone';
|
||||||
|
return 'computer';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Samsung model codes → names people know (S and A series; the code stays in brackets). */
|
||||||
|
const GALAXY: [RegExp, string][] = [
|
||||||
|
[/^SM-S93/, 'Galaxy S25'],
|
||||||
|
[/^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'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Android model from Client Hints (Chrome); filled in shortly after the page loads. */
|
||||||
|
let MODEL = '';
|
||||||
|
const modelReady: Promise<string> = (async () => {
|
||||||
|
const uad = (navigator as Navigator & { userAgentData?: { getHighEntropyValues(h: string[]): Promise<{ model?: string }> } })
|
||||||
|
.userAgentData;
|
||||||
|
if (!uad || !/Android/.test(UA)) return '';
|
||||||
|
try {
|
||||||
|
const m = ((await uad.getHighEntropyValues(['model'])).model ?? '').trim();
|
||||||
|
if (!m || m === 'K') return '';
|
||||||
|
const g = GALAXY.find(([re]) => re.test(m));
|
||||||
|
MODEL = g ? `${g[1]} (${m})` : /^SM-/.test(m) ? `Galaxy ${m}` : m;
|
||||||
|
} catch {
|
||||||
|
/* not offered */
|
||||||
|
}
|
||||||
|
return MODEL;
|
||||||
|
})();
|
||||||
|
|
||||||
|
function guessName(kind: Kind): string {
|
||||||
|
if (/iPhone/.test(UA)) return 'iPhone';
|
||||||
|
if (IPAD) return 'iPad';
|
||||||
|
if (/Android/.test(UA)) return MODEL || (kind === 'tablet' ? 'Android tablet' : 'Android phone');
|
||||||
|
if (/CrOS/.test(UA)) return 'Chromebook';
|
||||||
|
if (/Mac OS X/.test(UA)) return 'Mac';
|
||||||
|
if (/Windows/.test(UA)) return 'Windows PC';
|
||||||
|
if (/Linux/.test(UA)) return 'Linux PC';
|
||||||
|
return KIND_LABEL[kind];
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Phones and tablets are one choice. The device is still kept as a phone or a
|
||||||
|
* tablet (the lines say "the tablet"): on the device itself the browser tells
|
||||||
|
* which; picked from elsewhere it is a phone.
|
||||||
|
*/
|
||||||
|
type Pick = 'computer' | 'mobile' | 'router' | 'other';
|
||||||
|
const PICK_LABEL: Record<Pick, string> = { computer: 'PC', mobile: 'Mobile', router: 'Router', other: 'Other' };
|
||||||
|
const pickOf = (k: Kind): Pick => (k === 'phone' || k === 'tablet' ? 'mobile' : k);
|
||||||
|
const kindOf = (p: Pick): Kind => (p !== 'mobile' ? p : guessKind() === 'tablet' ? 'tablet' : 'phone');
|
||||||
|
|
||||||
|
export function startAdd() {
|
||||||
|
const st = state();
|
||||||
|
if (!st || st.locked) return;
|
||||||
|
if (!st.can_add) return toast(`You have reached your limit of ${st.person.device_limit} devices`, true);
|
||||||
|
if (secureFirst()) return;
|
||||||
|
openSheet(vAdd);
|
||||||
|
}
|
||||||
|
|
||||||
|
function vAdd(): View {
|
||||||
|
const st = state()!;
|
||||||
|
const p = st.person;
|
||||||
|
// The kinds this router takes, as the four choices.
|
||||||
|
const picks = (['computer', 'mobile', 'router', 'other'] as Pick[]).filter((k) => st.kinds.some((x) => pickOf(x) === k));
|
||||||
|
let pick: Pick = picks.includes(pickOf(guessKind())) ? pickOf(guessKind()) : picks[0];
|
||||||
|
let edited = false;
|
||||||
|
const taken = new Set(p.devices.map((d) => d.name.toLowerCase()));
|
||||||
|
const suggest = (k: Pick) => {
|
||||||
|
const n = k === pickOf(guessKind()) ? guessName(kindOf(k)) : k === 'mobile' ? 'Phone' : KIND_LABEL[k];
|
||||||
|
if (!taken.has(n.toLowerCase())) return n;
|
||||||
|
for (let i = 2; i < 20; i++) if (!taken.has(`${n} ${i}`.toLowerCase())) return `${n} ${i}`;
|
||||||
|
return n;
|
||||||
|
};
|
||||||
|
|
||||||
|
const kinds = h('div', { class: 'kinds', role: 'radiogroup', 'aria-label': 'What is it?' });
|
||||||
|
kinds.style.setProperty('--n', String(picks.length));
|
||||||
|
const tiles = picks.map((k) => {
|
||||||
|
const t = h(
|
||||||
|
'button',
|
||||||
|
{ type: 'button', class: 'kind', role: 'radio', 'aria-label': PICK_LABEL[k], onclick: () => choose(k) },
|
||||||
|
h('span', { class: 'kind-tile' }, glass(k, 'blue')),
|
||||||
|
h('span', { class: 'kind-lbl' }, PICK_LABEL[k]),
|
||||||
|
);
|
||||||
|
kinds.appendChild(t);
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
const input = h('input', { type: 'text', maxlength: 48, required: true, 'aria-label': 'Name', autocomplete: 'off' }) as HTMLInputElement;
|
||||||
|
const goBtn = h('button', { class: 'go ready', type: 'submit', 'aria-label': 'Create connection' }, ic('arrow')) as HTMLButtonElement;
|
||||||
|
const err = h('p', { class: 'hint bad-t', hidden: true });
|
||||||
|
const say = (msg: string) => {
|
||||||
|
// Already showing: its words change in place.
|
||||||
|
if (!err.hidden) return morphText(err, msg);
|
||||||
|
err.textContent = msg;
|
||||||
|
err.hidden = false;
|
||||||
|
play(
|
||||||
|
err,
|
||||||
|
[
|
||||||
|
{ opacity: 0, transform: 'translateY(-4px)' },
|
||||||
|
{ opacity: 1, transform: 'none' },
|
||||||
|
],
|
||||||
|
{ duration: 220, easing: EASE_OUT },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
input.value = suggest(pick);
|
||||||
|
input.addEventListener('input', () => {
|
||||||
|
edited = true;
|
||||||
|
goBtn.classList.toggle('ready', !!input.value.trim());
|
||||||
|
err.hidden = true;
|
||||||
|
});
|
||||||
|
// The Android model arrives a moment later: use it unless they started typing.
|
||||||
|
void modelReady.then(() => {
|
||||||
|
if (!edited && pick === pickOf(guessKind())) input.value = suggest(pick);
|
||||||
|
});
|
||||||
|
// The picked tile rings itself where it stands (the ring does not travel between tiles).
|
||||||
|
function choose(k: Pick) {
|
||||||
|
pick = k;
|
||||||
|
tiles.forEach((t, i) => {
|
||||||
|
const on = picks[i] === k;
|
||||||
|
t.classList.toggle('on', on);
|
||||||
|
t.setAttribute('aria-checked', String(on));
|
||||||
|
});
|
||||||
|
if (!edited) {
|
||||||
|
input.value = suggest(k);
|
||||||
|
goBtn.classList.add('ready');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
choose(pick);
|
||||||
|
|
||||||
|
const form = h('form', { class: 'field', autocomplete: 'off' }, input, goBtn);
|
||||||
|
form.addEventListener('submit', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const name = input.value.trim();
|
||||||
|
if (!name) return;
|
||||||
|
if (taken.has(name.toLowerCase())) return say('You already have a device with this name.');
|
||||||
|
void once(goBtn, async () => {
|
||||||
|
try {
|
||||||
|
const r = await call<{ id: string; config: ClientConfig; state: State }>('devices', { name, kind: kindOf(pick) });
|
||||||
|
setState(r.state);
|
||||||
|
repaint({ pop: r.id });
|
||||||
|
const dev = r.state.person.devices.find((d) => d.id === r.id)!;
|
||||||
|
await continueSetup(dev, r.config);
|
||||||
|
} catch (er) {
|
||||||
|
if (er instanceof ApiError && er.httpsUrl) return showSecure(er.httpsUrl);
|
||||||
|
say((er as Error).message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const viaLink = h(
|
||||||
|
'button',
|
||||||
|
{ type: 'button', class: 'btn soft block', onclick: () => go(vLink) },
|
||||||
|
ic('qr'),
|
||||||
|
h('span', {}, 'Add it from the device'),
|
||||||
|
);
|
||||||
|
const free = p.device_limit - p.devices.length;
|
||||||
|
const el = h(
|
||||||
|
'div',
|
||||||
|
{ class: 'view' },
|
||||||
|
head('Add a device'),
|
||||||
|
sub(`${free} of ${p.device_limit} slots free`),
|
||||||
|
kinds,
|
||||||
|
hint('Phones and tablets get a smaller packet size that suits mobile networks.'),
|
||||||
|
form,
|
||||||
|
err,
|
||||||
|
h('div', { class: 'or' }, 'OR'),
|
||||||
|
viaLink,
|
||||||
|
);
|
||||||
|
el.querySelector('.hint')!.classList.add('kinds-note');
|
||||||
|
return { el, label: 'Add a device' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The page on the device itself, ready to add it: the link as a code for its camera, and as text. */
|
||||||
|
function vLink(): View {
|
||||||
|
const link = addLink(pageUrl());
|
||||||
|
const el = h(
|
||||||
|
'div',
|
||||||
|
{ class: 'view' },
|
||||||
|
head('Open on the device', { back: true }),
|
||||||
|
sub('Point its camera at the code: your page opens there with this device ready to add.'),
|
||||||
|
qrBox(link, true),
|
||||||
|
linkRow(link),
|
||||||
|
);
|
||||||
|
return { el, label: 'Open on the device' };
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
// A device's own actions from its ⋯ menu: Rename, Reconnect (new keys, then
|
||||||
|
// the set-up of the new ones) and Remove. A question comes before what cannot
|
||||||
|
// be undone; the action's button stays busy until the router answers.
|
||||||
|
|
||||||
|
import type { ClientConfig, Device } from '../../shared/types';
|
||||||
|
import { call } from '../api';
|
||||||
|
import { h, ic } from '../dom';
|
||||||
|
import { EASE_IN, play } from '../motion';
|
||||||
|
import { repaint, setState, state, type State } from '../state';
|
||||||
|
import { once, toast } from '../ui/feedback';
|
||||||
|
import { glass, type Tone } from '../ui/glass';
|
||||||
|
import { closeSheet, head, onClosed, openSheet, type View } from '../ui/sheet';
|
||||||
|
import { secureFirst } from './secure';
|
||||||
|
import { continueSetup } from './setup-view';
|
||||||
|
|
||||||
|
/** A question before something that cannot be undone: the action's icon in its colour, what happens, Cancel and the action. */
|
||||||
|
function ask(o: { icon: string; tone: Tone; title: string; text: string; action: string; cls: string; run: () => Promise<void> }): View {
|
||||||
|
const ok = h(
|
||||||
|
'button',
|
||||||
|
{ type: 'button', class: `btn ${o.cls}`, onclick: (ev: Event) => once(ev.currentTarget as HTMLButtonElement, o.run) },
|
||||||
|
// In an element: a busy button blurs its content away for the orb (ui/busy.ts).
|
||||||
|
h('span', {}, o.action),
|
||||||
|
) as HTMLButtonElement;
|
||||||
|
const el = h(
|
||||||
|
'div',
|
||||||
|
{ class: 'view' },
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'center-col ask' },
|
||||||
|
glass(o.icon, o.tone, 'gi xl'),
|
||||||
|
h('h3', {}, o.title),
|
||||||
|
h('p', {}, o.text),
|
||||||
|
h('div', { class: 'btnrow' }, h('button', { type: 'button', class: 'btn soft', onclick: () => closeSheet() }, 'Cancel'), ok),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return { el, label: o.title, asks: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rename(d: Device) {
|
||||||
|
openSheet(() => {
|
||||||
|
const input = h('input', { type: 'text', maxlength: 48, 'aria-label': 'Device name', autocomplete: 'off' }) as HTMLInputElement;
|
||||||
|
input.value = d.name;
|
||||||
|
const save = h('button', { class: 'go', type: 'submit', 'aria-label': 'Save' }, ic('check')) as HTMLButtonElement;
|
||||||
|
input.addEventListener('input', () => save.classList.toggle('ready', !!input.value.trim() && input.value.trim() !== d.name));
|
||||||
|
const form = h('form', { class: 'field', autocomplete: 'off' }, input, save);
|
||||||
|
form.addEventListener('submit', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const name = input.value.trim();
|
||||||
|
if (!name || name === d.name) return;
|
||||||
|
void once(save, async () => {
|
||||||
|
try {
|
||||||
|
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'rename', name });
|
||||||
|
setState(r.state);
|
||||||
|
onClosed(() => {
|
||||||
|
repaint();
|
||||||
|
toast('Renamed');
|
||||||
|
});
|
||||||
|
closeSheet();
|
||||||
|
} catch (er) {
|
||||||
|
toast((er as Error).message, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
setTimeout(() => input.select(), 60);
|
||||||
|
return { el: h('div', { class: 'view' }, head(`Rename ${d.name}`), form), label: `Rename ${d.name}` };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a device up from scratch (a new phone, the app reinstalled, settings the
|
||||||
|
* admin changed): new keys, so what it holds stops working; it shows "Not set
|
||||||
|
* up yet" until it connects with the new configuration, which the sheet goes on to.
|
||||||
|
*/
|
||||||
|
export function reconnect(d: Device) {
|
||||||
|
if (secureFirst()) return;
|
||||||
|
const here = state()?.here === d.id;
|
||||||
|
openSheet(() =>
|
||||||
|
ask({
|
||||||
|
icon: 'refresh',
|
||||||
|
tone: 'orange',
|
||||||
|
title: `Reconnect ${d.name}?`,
|
||||||
|
text: here
|
||||||
|
? 'It gets new keys. This device is connected through its current settings: it disconnects a few seconds after you confirm. Add the new ones that open next.'
|
||||||
|
: 'It gets new keys and its current settings stop working. Set it up again with the new ones that open next.',
|
||||||
|
action: 'Reconnect',
|
||||||
|
cls: 'accent',
|
||||||
|
run: async () => {
|
||||||
|
try {
|
||||||
|
const r = await call<{ config: ClientConfig; state: State }>(`devices/${d.id}`, { action: 'reconnect' });
|
||||||
|
setState(r.state);
|
||||||
|
repaint();
|
||||||
|
await continueSetup(r.state.person.devices.find((x) => x.id === d.id) ?? { ...d, handshake: 0 }, r.config);
|
||||||
|
} catch (er) {
|
||||||
|
toast((er as Error).message, true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeDevice(d: Device) {
|
||||||
|
openSheet(() =>
|
||||||
|
ask({
|
||||||
|
icon: 'trash',
|
||||||
|
tone: 'red',
|
||||||
|
title: `Remove ${d.name}?`,
|
||||||
|
text: 'Its connection stops working at once. You can add it again later.',
|
||||||
|
action: 'Remove',
|
||||||
|
cls: 'red',
|
||||||
|
run: async () => {
|
||||||
|
try {
|
||||||
|
const r = await call<{ state: State }>(`devices/${d.id}`, { action: 'delete' });
|
||||||
|
setState(r.state);
|
||||||
|
// The card goes first; the rest then glide into its place.
|
||||||
|
onClosed(() => {
|
||||||
|
const card = document.querySelector(`.dev[data-id="${CSS.escape(d.id)}"]`);
|
||||||
|
const done = () => {
|
||||||
|
repaint();
|
||||||
|
toast('Device removed');
|
||||||
|
};
|
||||||
|
if (!card) return done();
|
||||||
|
play(
|
||||||
|
card,
|
||||||
|
[
|
||||||
|
{ opacity: 1, transform: 'none', filter: 'none' },
|
||||||
|
{ opacity: 0, transform: 'scale(.9)', filter: 'blur(6px)' },
|
||||||
|
],
|
||||||
|
{
|
||||||
|
duration: 220,
|
||||||
|
easing: EASE_IN,
|
||||||
|
fill: 'forwards',
|
||||||
|
},
|
||||||
|
).onfinish = done;
|
||||||
|
});
|
||||||
|
closeSheet();
|
||||||
|
} catch (er) {
|
||||||
|
toast((er as Error).message, true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// This page on another device: from the breadcrumb, its link as a code for a
|
||||||
|
// phone's camera, and the link itself to copy or share.
|
||||||
|
|
||||||
|
import { h } from '../dom';
|
||||||
|
import { pageUrl } from '../state';
|
||||||
|
import { linkRow, qrBox } from '../ui/codes';
|
||||||
|
import { head, openSheet, sub } from '../ui/sheet';
|
||||||
|
|
||||||
|
export function showPageCode() {
|
||||||
|
openSheet(() => {
|
||||||
|
const url = pageUrl();
|
||||||
|
const el = h(
|
||||||
|
'div',
|
||||||
|
{ class: 'view' },
|
||||||
|
head('Open on another device'),
|
||||||
|
sub('Point its camera at the code: this page opens there.'),
|
||||||
|
qrBox(url, true),
|
||||||
|
linkRow(url),
|
||||||
|
);
|
||||||
|
return { el, label: 'Open on another device' };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// A plain-HTTP link (an IP address) shows the page, but keys only travel
|
||||||
|
// encrypted: adding or setting up a device sends the visitor to the HTTPS twin
|
||||||
|
// first. Its certificate is the router's own, so the browser warns once; say so.
|
||||||
|
|
||||||
|
import { h, ic } from '../dom';
|
||||||
|
import { httpsTwin } from '../state';
|
||||||
|
import { glass } from '../ui/glass';
|
||||||
|
import { head, hint, openSheet, sub, type View } from '../ui/sheet';
|
||||||
|
|
||||||
|
function vSecure(url: string): View {
|
||||||
|
const el = h(
|
||||||
|
'div',
|
||||||
|
{ class: 'view' },
|
||||||
|
head('Open the link securely'),
|
||||||
|
sub('Connection settings only travel encrypted'),
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'center-col secure' },
|
||||||
|
glass('lock', 'blue', 'gi xl'),
|
||||||
|
h('p', {}, 'This page is open without encryption. To add or set up a device, open the same link over HTTPS:'),
|
||||||
|
),
|
||||||
|
// The same tab: the HTTPS page replaces this one.
|
||||||
|
h('a', { class: 'btn accent block', href: url }, ic('lock'), h('span', {}, 'Open securely')),
|
||||||
|
hint('The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”).'),
|
||||||
|
);
|
||||||
|
el.lastElementChild!.classList.add('secure-note');
|
||||||
|
return { el, label: 'Open the link securely' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The HTTPS twin's sheet (here, or the one the router named in a refusal). */
|
||||||
|
export const showSecure = (url: string) => openSheet(() => vSecure(url));
|
||||||
|
|
||||||
|
/** Over plain HTTP: the twin's sheet instead, and true (the caller stops). */
|
||||||
|
export function secureFirst(): boolean {
|
||||||
|
const twin = httpsTwin();
|
||||||
|
if (!twin) return false;
|
||||||
|
showSecure(twin);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,408 @@
|
|||||||
|
// The pieces the set-up sheet is made of: store badges, the step that adds the
|
||||||
|
// connection (a link, the share sheet, a key or a file, as the app and the
|
||||||
|
// device allow), the panel that sends the connection to another device, the
|
||||||
|
// .conf for a router, the Download / Copy keys beside × and the line saying
|
||||||
|
// where an app scans a code. The rules behind them are setup.ts.
|
||||||
|
|
||||||
|
import type { ClientConfig, Device } from '../../shared/types';
|
||||||
|
import { h, ic, type Kid } from '../dom';
|
||||||
|
import { EASE_OUT, POP, SMOOTH, play } from '../motion';
|
||||||
|
import {
|
||||||
|
APP_NAME,
|
||||||
|
PLATFORM_LABEL,
|
||||||
|
importSteps,
|
||||||
|
keyFileName,
|
||||||
|
opensKeyLinks,
|
||||||
|
routerStore,
|
||||||
|
scanPath,
|
||||||
|
storeFor,
|
||||||
|
type AppId,
|
||||||
|
type Platform,
|
||||||
|
type Store,
|
||||||
|
} from '../setup';
|
||||||
|
import { accordion } from '../ui/accordion';
|
||||||
|
import { copy, download, sendFile, shareFile } from '../ui/feedback';
|
||||||
|
import { glass } from '../ui/glass';
|
||||||
|
import { menuLine, morphText, setText } from '../ui/morph';
|
||||||
|
import { hint } from '../ui/sheet';
|
||||||
|
|
||||||
|
export const APP_ICON: Record<AppId, string> = { vpn: 'amnezia', awg: 'amneziawg', wg: 'wireguard' };
|
||||||
|
|
||||||
|
/** The app a device was set up with last time, so the sheet reopens on it. */
|
||||||
|
const memo = (d: Device) => `dl.app.${d.id}`;
|
||||||
|
export function recallApp(d: Device): AppId | null {
|
||||||
|
try {
|
||||||
|
const v = localStorage.getItem(memo(d));
|
||||||
|
return v === 'vpn' || v === 'awg' || v === 'wg' ? v : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function rememberApp(d: Device, app: AppId) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(memo(d), app);
|
||||||
|
} catch {
|
||||||
|
/* private mode */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the steps work with: the device, its configuration, the key, and the choices made. */
|
||||||
|
export interface SetupCtx {
|
||||||
|
d: Device;
|
||||||
|
cfg: ClientConfig;
|
||||||
|
key: string;
|
||||||
|
/** The platform this page is open on. */
|
||||||
|
pf: Platform;
|
||||||
|
/** "the phone": the device in a sentence. */
|
||||||
|
there: string;
|
||||||
|
app(): AppId;
|
||||||
|
/** The page is open on the device being set up. */
|
||||||
|
same(): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A badge: the mark in a tile, two lines, a chevron (an action) or the open
|
||||||
|
* mark (a store page, in a new tab). `primary`: the one thing to tap in step 2.
|
||||||
|
*/
|
||||||
|
export function badge(
|
||||||
|
st: { href?: string; top: string; main: string; mark: string; onclick?: (ev: Event) => void },
|
||||||
|
primary = false,
|
||||||
|
): HTMLElement {
|
||||||
|
const inner = [
|
||||||
|
h('span', { class: 'b-ic' }, ic(st.mark)),
|
||||||
|
h('span', { class: 'b-t' }, h('span', { class: 'b-top' }, st.top), h('span', { class: 'b-main' }, st.main)),
|
||||||
|
ic(st.onclick || st.href?.startsWith('vpn:') ? 'chevron' : 'open'),
|
||||||
|
];
|
||||||
|
const cls = `badge${primary ? ' primary' : ''}`;
|
||||||
|
if (st.onclick) return h('button', { type: 'button', class: cls, onclick: st.onclick }, inner);
|
||||||
|
// A vpn:// key opens the app in place: no new tab.
|
||||||
|
const app = st.href?.startsWith('vpn:');
|
||||||
|
return h('a', { class: cls, href: st.href, target: app ? null : '_blank', rel: 'noopener noreferrer' }, inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where the app comes from: the store (and, on Android, the APK beside it), or a line to go and get it. */
|
||||||
|
export function storeBlock(app: AppId, os: Platform, router: boolean): Kid[] {
|
||||||
|
const st: Store | null = router ? routerStore(app) : storeFor(app, os);
|
||||||
|
if (!st) return [hint(`Get ${APP_NAME[app]} on the ${PLATFORM_LABEL[os]} and come back here.`)];
|
||||||
|
// Android: the store can fail (no Google Play, or it hides the app), so the APK sits beside it.
|
||||||
|
if (st.alt) return [h('div', { class: 'badges2' }, badge(st), badge(st.alt)), hint(st.alt.why)];
|
||||||
|
return [badge(st)];
|
||||||
|
}
|
||||||
|
|
||||||
|
const howto = (steps: [string, string][]) =>
|
||||||
|
h(
|
||||||
|
'ol',
|
||||||
|
{ class: 'howto' },
|
||||||
|
steps.map(([text, bold]) => h('li', {}, text.replace(/ → $/, ' ›'), bold ? [' ', h('b', {}, bold)] : null)),
|
||||||
|
);
|
||||||
|
|
||||||
|
const linkBtn = (label: string, run: (ev: Event) => void) => h('button', { type: 'button', onclick: run }, label);
|
||||||
|
|
||||||
|
/** Step 2: a link for AmneziaVPN, the file for the others, in the words of where they go. */
|
||||||
|
export function connectKids(c: SetupCtx): Kid[] {
|
||||||
|
const app = c.app();
|
||||||
|
const name = APP_NAME[app];
|
||||||
|
const hereHandheld = c.pf === 'ios' || c.pf === 'android';
|
||||||
|
// On the phone being set up, a link opens AmneziaVPN only on Android; an
|
||||||
|
// iPhone takes the key as a .vpn file from the share sheet.
|
||||||
|
const inHand = c.same() && hereHandheld;
|
||||||
|
const copyKey = (ev: Event) => copy(c.key, 'Key copied', ev.currentTarget);
|
||||||
|
const send = app === 'vpn' && inHand && !opensKeyLinks(c.pf) ? shareFile(keyFileName(c.cfg.filename), c.key) : null;
|
||||||
|
if (app === 'vpn' && inHand && (opensKeyLinks(c.pf) || send))
|
||||||
|
return [
|
||||||
|
send
|
||||||
|
? badge({ top: 'Then come back here and tap', main: 'Send to AmneziaVPN', mark: 'amnezia', onclick: () => void send() }, true)
|
||||||
|
: badge({ href: c.key, top: 'Then come back here and tap', main: 'Open in AmneziaVPN', mark: 'amnezia' }, true),
|
||||||
|
hint(
|
||||||
|
send ? 'Pick AmneziaVPN in the share sheet. Not there? ' : 'Nothing opened? ',
|
||||||
|
linkBtn('Copy the key', copyKey),
|
||||||
|
' and add it in the app.',
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if (app === 'vpn')
|
||||||
|
return [
|
||||||
|
badge({ top: 'The connection as one key', main: 'Copy the key', mark: 'copy', onclick: copyKey }, true),
|
||||||
|
howto([
|
||||||
|
['Open AmneziaVPN', ''],
|
||||||
|
['Add server › ', 'Insert key'],
|
||||||
|
['Paste the key and connect', ''],
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
const share = hereHandheld ? shareFile(c.cfg.filename, c.cfg.conf) : null;
|
||||||
|
return [
|
||||||
|
share
|
||||||
|
? badge(
|
||||||
|
{
|
||||||
|
top: c.same() ? `Straight into ${name}` : `Send it to the ${c.there}`,
|
||||||
|
main: 'Share the file',
|
||||||
|
mark: 'share',
|
||||||
|
onclick: () => void share(),
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
: badge(
|
||||||
|
{
|
||||||
|
top: 'Then import it in the app',
|
||||||
|
main: 'Download the file',
|
||||||
|
mark: 'download',
|
||||||
|
onclick: () => download(c.cfg.filename, c.cfg.conf),
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// In the words of the app where the file goes: the phone in hand, or the computer's system.
|
||||||
|
howto(importSteps(app, c.pf, c.cfg.filename, !!share && c.same())),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A computer set up from elsewhere: the connection to send there, as the key or the file. */
|
||||||
|
export function sendKids(c: SetupCtx): Kid[] {
|
||||||
|
const app = c.app();
|
||||||
|
const btn = (icon: string, label: string, run: (ev: Event) => void) =>
|
||||||
|
h('button', { type: 'button', class: 'btn soft sm', onclick: run }, ic(icon), h('span', { class: 'lbl' }, label));
|
||||||
|
if (app === 'vpn') {
|
||||||
|
const file = keyFileName(c.cfg.filename);
|
||||||
|
const share = !!shareFile(file, c.key);
|
||||||
|
return [
|
||||||
|
h('p', { class: 'desc' }, `Send it to the ${c.there} in a message or a note, then in AmneziaVPN: Add server › Insert key.`),
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'btnrow2' },
|
||||||
|
btn('copy', 'Copy the key', (ev) => copy(c.key, 'Key copied', ev.currentTarget)),
|
||||||
|
btn(share ? 'share' : 'download', share ? 'Share as a file' : 'Download the key', () => sendFile(file, c.key)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
const share = !!shareFile(c.cfg.filename, c.cfg.conf);
|
||||||
|
return [
|
||||||
|
h('p', { class: 'desc' }, `Send it to the ${c.there}, then import `, h('b', {}, c.cfg.filename), ` in ${APP_NAME[app]}.`),
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'btnrow2' },
|
||||||
|
btn(share ? 'share' : 'download', share ? 'Share the file' : 'Download the file', () => sendFile(c.cfg.filename, c.cfg.conf)),
|
||||||
|
btn('copy', 'Copy the configuration', (ev) => copy(c.cfg.conf, 'Configuration copied', ev.currentTarget)),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One configuration line, highlighted; private and preshared keys masked unless shown. */
|
||||||
|
function confLine(line: string, reveal: boolean): Node {
|
||||||
|
if (/^\s*\[.+\]\s*$/.test(line)) return h('span', { class: 'sec' }, line);
|
||||||
|
const m = /^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(line);
|
||||||
|
if (!m) return document.createTextNode(line);
|
||||||
|
const secret = /^(\s*)(PrivateKey|PresharedKey)\b/.test(line);
|
||||||
|
return h('span', {}, h('span', { class: 'k' }, m[1]), ' ', secret && !reveal ? h('span', { class: 'mask' }, '••••••••••••••••') : m[2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The .conf for a router: a file card to download (or share), and the configuration folded, its keys hidden. */
|
||||||
|
export function filePane(cfg: ClientConfig): HTMLElement {
|
||||||
|
let reveal = false;
|
||||||
|
const pre = h('pre', { class: 'conf' });
|
||||||
|
const paint = () =>
|
||||||
|
pre.replaceChildren(...cfg.conf.split('\n').flatMap((l, i) => (i ? ['\n', confLine(l, reveal)] : [confLine(l, reveal)])));
|
||||||
|
paint();
|
||||||
|
const share = !!shareFile(cfg.filename, cfg.conf);
|
||||||
|
const eye = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
class: 'btn soft sm',
|
||||||
|
onclick: () => {
|
||||||
|
reveal = !reveal;
|
||||||
|
eye.replaceChildren(ic(reveal ? 'x' : 'key'), h('span', {}, reveal ? 'Hide key' : 'Show key'));
|
||||||
|
paint();
|
||||||
|
// A key shown comes into focus out of a blur; hidden again, the mask fades back.
|
||||||
|
pre.querySelectorAll('.mask, .k').forEach((x) =>
|
||||||
|
play(
|
||||||
|
x,
|
||||||
|
[
|
||||||
|
{ filter: 'blur(4px)', opacity: 0.4 },
|
||||||
|
{ filter: 'none', opacity: 1 },
|
||||||
|
],
|
||||||
|
{ duration: 320, easing: EASE_OUT },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
ic('key'),
|
||||||
|
h('span', {}, 'Show key'),
|
||||||
|
);
|
||||||
|
const cp = h(
|
||||||
|
'button',
|
||||||
|
{ type: 'button', class: 'btn soft sm', onclick: (ev: Event) => copy(cfg.conf, 'Configuration copied', ev.currentTarget) },
|
||||||
|
ic('copy'),
|
||||||
|
h('span', { class: 'lbl' }, 'Copy'),
|
||||||
|
);
|
||||||
|
const card = h(
|
||||||
|
'div',
|
||||||
|
{ class: 'filecard' },
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ class: 'fc-row' },
|
||||||
|
h('span', { class: 'filecard-ic' }, '.conf'),
|
||||||
|
h('span', { class: 't' }, h('span', { class: 'mono' }, cfg.filename), h('span', {}, 'For computers and routers')),
|
||||||
|
),
|
||||||
|
h(
|
||||||
|
'button',
|
||||||
|
{ type: 'button', class: 'btn accent sm block', onclick: () => sendFile(cfg.filename, cfg.conf) },
|
||||||
|
ic(share ? 'open' : 'download'),
|
||||||
|
h('span', {}, share ? 'Share file' : 'Download'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const conf = accordion([{ icon: glass('file'), title: 'Configuration', body: [h('div', { class: 'confbar' }, eye, cp), pre] }], {
|
||||||
|
inset: true,
|
||||||
|
});
|
||||||
|
return h('div', { class: 'step-box' }, card, conf.el);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScanLine {
|
||||||
|
el: HTMLElement;
|
||||||
|
/** Another app picked: its name and its path morph in place. */
|
||||||
|
set(app: AppId): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "In AmneziaWG: + › Create from QR code", with both phone systems' wording where they differ. */
|
||||||
|
export function scanLine(app: AppId): ScanLine {
|
||||||
|
const name = h('span', { class: 'osm-p' }, APP_NAME[app]);
|
||||||
|
const path = menuLine(scanPath(app, 'ios'), scanPath(app, 'android'));
|
||||||
|
return {
|
||||||
|
el: h('span', { class: 'scanline' }, h('span', {}, 'In ', name, ':'), path.el),
|
||||||
|
set(a) {
|
||||||
|
morphText(name, APP_NAME[a], undefined, { whole: true });
|
||||||
|
path.set(scanPath(a, 'ios'), scanPath(a, 'android'));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ConnPill {
|
||||||
|
el: HTMLElement;
|
||||||
|
/** The labels follow the app picked. */
|
||||||
|
sync(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Beside ×: the connection itself, to download or copy, where the sheet offers
|
||||||
|
* neither (a phone or a tablet set up from elsewhere). One tooltip for both
|
||||||
|
* keys, under them: the first waits a beat; once one is up the next comes at
|
||||||
|
* once and the tooltip glides across. Copied: a check, and the tooltip says so.
|
||||||
|
*/
|
||||||
|
export function connPill(get: () => { text: string; msg: string; file: string; app: string }): ConnPill {
|
||||||
|
const tt = h('span', { class: 'tt' });
|
||||||
|
const tm = h('span', { class: 'tt-m' });
|
||||||
|
const tip = h('span', { class: 'hp-tip', 'aria-hidden': 'true' }, tt, tm);
|
||||||
|
const dl = h('button', { type: 'button', class: 'hp-b', onclick: () => sendFile(get().file, get().text) }, ic('download'));
|
||||||
|
const cp = h('button', { type: 'button', class: 'hp-b' }, ic('copy'));
|
||||||
|
const el = h('div', { class: 'hpill', role: 'group', 'aria-label': 'The connection', 'data-key': 'conn' }, dl, cp, tip);
|
||||||
|
|
||||||
|
let tipFor: HTMLElement | null = null;
|
||||||
|
let tipT = 0;
|
||||||
|
let warmUntil = 0;
|
||||||
|
const words = (b: HTMLElement) => (b === cp && cp.classList.contains('done') ? 'Copied' : (b.getAttribute('aria-label') ?? ''));
|
||||||
|
// Centred under its key, but never past the sheet's edge (× and its margin to the right).
|
||||||
|
const centre = (b: HTMLElement, t: string) => {
|
||||||
|
tm.textContent = t;
|
||||||
|
const w = tm.offsetWidth + 20;
|
||||||
|
return Math.min(b.offsetLeft + b.offsetWidth / 2, el.offsetWidth + 46 - w / 2);
|
||||||
|
};
|
||||||
|
const at = (x: number) => `translateX(${x}px) translateX(-50%)`;
|
||||||
|
const glideTo = (x: number) => {
|
||||||
|
const from = getComputedStyle(tip).transform;
|
||||||
|
tip.getAnimations().forEach((a) => a.cancel());
|
||||||
|
tip.style.transform = at(x);
|
||||||
|
play(tip, [{ transform: from }, { transform: at(x) }], { duration: SMOOTH.duration, easing: SMOOTH.easing });
|
||||||
|
};
|
||||||
|
// Another key's words, or "Copied": what the two share slides, the rest morphs; the pill glides with it.
|
||||||
|
const reword = (t: string) => morphText(tt, t);
|
||||||
|
const show = (b: HTMLElement) => {
|
||||||
|
clearTimeout(tipT);
|
||||||
|
if (tipFor === b && tip.classList.contains('on')) return;
|
||||||
|
tipFor = b;
|
||||||
|
if (tip.classList.contains('on')) {
|
||||||
|
const t = words(b);
|
||||||
|
glideTo(centre(b, t));
|
||||||
|
return reword(t);
|
||||||
|
}
|
||||||
|
const up = () => {
|
||||||
|
const t = words(b);
|
||||||
|
setText(tt, t);
|
||||||
|
const x = centre(b, t);
|
||||||
|
tip.getAnimations().forEach((a) => a.cancel());
|
||||||
|
tip.style.transform = at(x);
|
||||||
|
tip.classList.add('on');
|
||||||
|
play(
|
||||||
|
tip,
|
||||||
|
[
|
||||||
|
{ opacity: 0, transform: `${at(x)} translateY(-3px) scale(.96)`, filter: 'blur(3px)' },
|
||||||
|
{ opacity: 1, transform: at(x), filter: 'blur(0px)' },
|
||||||
|
],
|
||||||
|
{
|
||||||
|
duration: 220,
|
||||||
|
easing: EASE_OUT,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
if (performance.now() < warmUntil) up();
|
||||||
|
else tipT = window.setTimeout(up, 420);
|
||||||
|
};
|
||||||
|
const hide = () => {
|
||||||
|
clearTimeout(tipT);
|
||||||
|
tipFor = null;
|
||||||
|
if (!tip.classList.contains('on')) return;
|
||||||
|
warmUntil = performance.now() + 500;
|
||||||
|
tip.classList.remove('on');
|
||||||
|
play(tip, [{ opacity: 1 }, { opacity: 0 }], { duration: 120, easing: 'ease-out' });
|
||||||
|
};
|
||||||
|
for (const b of [dl, cp]) {
|
||||||
|
b.addEventListener('pointerenter', (e) => {
|
||||||
|
if (e.pointerType === 'mouse') show(b);
|
||||||
|
});
|
||||||
|
b.addEventListener('focus', () => {
|
||||||
|
if (b.matches(':focus-visible')) show(b);
|
||||||
|
});
|
||||||
|
b.addEventListener('blur', hide);
|
||||||
|
}
|
||||||
|
el.addEventListener('pointerleave', hide);
|
||||||
|
|
||||||
|
const icon = (name: string) => {
|
||||||
|
const n = ic(name);
|
||||||
|
cp.querySelector('svg')!.replaceWith(n);
|
||||||
|
play(
|
||||||
|
n,
|
||||||
|
[
|
||||||
|
{ opacity: 0, transform: 'scale(.6)', filter: 'blur(3px)' },
|
||||||
|
{ opacity: 1, transform: 'none', filter: 'none' },
|
||||||
|
],
|
||||||
|
{ duration: POP.duration, easing: POP.easing },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
// Copied: the key shows a check and the tooltip says so, then both go back.
|
||||||
|
const sayCopy = () => {
|
||||||
|
if (tipFor !== cp || !tip.classList.contains('on')) return;
|
||||||
|
const t = words(cp);
|
||||||
|
glideTo(centre(cp, t));
|
||||||
|
reword(t);
|
||||||
|
};
|
||||||
|
let back = 0;
|
||||||
|
cp.addEventListener('click', () => {
|
||||||
|
const c = get();
|
||||||
|
void copy(c.text, c.msg);
|
||||||
|
clearTimeout(back);
|
||||||
|
if (!cp.classList.contains('done')) {
|
||||||
|
cp.classList.add('done');
|
||||||
|
icon('check');
|
||||||
|
sayCopy();
|
||||||
|
}
|
||||||
|
back = window.setTimeout(() => {
|
||||||
|
cp.classList.remove('done');
|
||||||
|
icon('copy');
|
||||||
|
sayCopy();
|
||||||
|
}, 1600);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
el,
|
||||||
|
sync() {
|
||||||
|
const app = get().app;
|
||||||
|
dl.setAttribute('aria-label', `Download ${app} config`);
|
||||||
|
cp.setAttribute('aria-label', `Copy ${app} config`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
// Setting a device up: one sheet. Its layout follows where the page is open:
|
||||||
|
// on the device itself, two steps (get the app, add the connection) with a way
|
||||||
|
// round folded under the wait; a router, its packages and the file; a phone or
|
||||||
|
// a tablet set up from elsewhere, its link as a code or the connection as a
|
||||||
|
// code for an app it has; a computer set up from elsewhere, its link or the
|
||||||
|
// connection to send there. Which app and where it comes from follow the
|
||||||
|
// server's disguise and the platform (setup.ts). The wait for the first
|
||||||
|
// connection sits on top the whole time (wait.ts).
|
||||||
|
|
||||||
|
import type { ClientConfig, Device } from '../../shared/types';
|
||||||
|
import { vpnKey, vpnQrText } from '../../shared/vpnkey';
|
||||||
|
import { ApiError, call } from '../api';
|
||||||
|
import { h, put } from '../dom';
|
||||||
|
import { SMOOTH, play } from '../motion';
|
||||||
|
import { APP_NAME, appsFor, deviceNoun, inWebview, keyFileName, sameDevice, setupLink, type AppId } from '../setup';
|
||||||
|
import { pageUrl, platform, preset, repaint } from '../state';
|
||||||
|
import { accordion } from '../ui/accordion';
|
||||||
|
import { codeRow, linkRow, type CodeRow } from '../ui/codes';
|
||||||
|
import { once, toast } from '../ui/feedback';
|
||||||
|
import { glass } from '../ui/glass';
|
||||||
|
import { morphInto, morphText } from '../ui/morph';
|
||||||
|
import { iconSeg, type IconSeg } from '../ui/seg';
|
||||||
|
import { glide, go, head, onClosed, onLeave, openSheet, sub, type View } from '../ui/sheet';
|
||||||
|
import { notice } from '../page/notices';
|
||||||
|
import { secureFirst, showSecure } from './secure';
|
||||||
|
import {
|
||||||
|
APP_ICON,
|
||||||
|
connPill,
|
||||||
|
connectKids,
|
||||||
|
filePane,
|
||||||
|
recallApp,
|
||||||
|
rememberApp,
|
||||||
|
scanLine,
|
||||||
|
type ScanLine,
|
||||||
|
sendKids,
|
||||||
|
storeBlock,
|
||||||
|
type SetupCtx,
|
||||||
|
} from './setup-parts';
|
||||||
|
import { arrive, waitWay, watchFirstConnection } from './wait';
|
||||||
|
|
||||||
|
async function getConfig(d: Device): Promise<ClientConfig | null> {
|
||||||
|
try {
|
||||||
|
return await call<ClientConfig>(`devices/${d.id}/config`);
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && e.httpsUrl) showSecure(e.httpsUrl);
|
||||||
|
else toast((e as Error).message, true);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set up a device from its card: the configuration first (the button waits for it), then the sheet. */
|
||||||
|
export async function openSetup(d: Device, from?: EventTarget | null) {
|
||||||
|
if (secureFirst()) return;
|
||||||
|
const run = async () => {
|
||||||
|
const cfg = await getConfig(d);
|
||||||
|
if (!cfg) return;
|
||||||
|
const key = await vpnKey(cfg, cfg.server);
|
||||||
|
openSheet(() => setupView(d, cfg, key));
|
||||||
|
};
|
||||||
|
if (from instanceof HTMLButtonElement) await once(from, run);
|
||||||
|
else await run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Further in a flow (Add, Reconnect): the configuration the router just sent, in the open sheet. */
|
||||||
|
export async function continueSetup(d: Device, cfg: ClientConfig) {
|
||||||
|
const key = await vpnKey(cfg, cfg.server);
|
||||||
|
go(() => setupView(d, cfg, key));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A numbered step: its number, a title, what to do. */
|
||||||
|
function step(n: string, title: Node | string, kids: (Node | null)[]): HTMLElement {
|
||||||
|
return h(
|
||||||
|
'div',
|
||||||
|
{ class: 'step' },
|
||||||
|
h('span', { class: 'step-n' }, n),
|
||||||
|
h('div', { class: 'step-b' }, typeof title === 'string' ? h('span', { class: 'step-t' }, title) : title, kids),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fold a block away (height, then gone) or bring it back; `instant` without motion. */
|
||||||
|
function foldBlock(el: HTMLElement, fold: boolean, instant: boolean) {
|
||||||
|
const cur = el.hidden ? 0 : el.getBoundingClientRect().height;
|
||||||
|
el.getAnimations().forEach((a) => a.cancel());
|
||||||
|
if (instant) {
|
||||||
|
el.hidden = fold;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.style.overflow = 'hidden';
|
||||||
|
el.hidden = false;
|
||||||
|
const to = fold ? 0 : el.getBoundingClientRect().height;
|
||||||
|
const [a, b] = fold ? [1, 0] : [0, 1];
|
||||||
|
play(
|
||||||
|
el,
|
||||||
|
[
|
||||||
|
{ height: `${cur}px`, opacity: a, filter: `blur(${4 - a * 4}px)` },
|
||||||
|
{ height: `${to}px`, opacity: b, filter: `blur(${4 - b * 4}px)` },
|
||||||
|
],
|
||||||
|
{
|
||||||
|
duration: SMOOTH.duration,
|
||||||
|
easing: SMOOTH.easing,
|
||||||
|
},
|
||||||
|
).onfinish = () => {
|
||||||
|
el.style.overflow = '';
|
||||||
|
el.hidden = fold;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type Layout = 'same' | 'router' | 'away' | 'pc-away';
|
||||||
|
|
||||||
|
export function setupView(d: Device, cfg: ClientConfig, key: string): View {
|
||||||
|
const pf = platform();
|
||||||
|
const apps = appsFor(preset());
|
||||||
|
const handheld = d.kind === 'phone' || d.kind === 'tablet';
|
||||||
|
const router = d.kind === 'router';
|
||||||
|
const same = sameDevice(d.kind, pf);
|
||||||
|
const layout: Layout = same ? 'same' : router ? 'router' : handheld ? 'away' : 'pc-away';
|
||||||
|
const there = deviceNoun(d.kind);
|
||||||
|
// A router takes AmneziaWG (or WireGuard), never AmneziaVPN.
|
||||||
|
const choices = apps.filter((a) => !router || a.id !== 'vpn');
|
||||||
|
let app: AppId = recallApp(d) ?? (router ? 'awg' : 'vpn');
|
||||||
|
if (!choices.some((a) => a.id === app)) app = choices[0].id;
|
||||||
|
const c: SetupCtx = { d, cfg, key, pf, there, app: () => app, same: () => same };
|
||||||
|
|
||||||
|
// The pickers and the boxes a pick changes live across repaints: a pick only
|
||||||
|
// refills what it changes, so the pills glide and nothing else in the sheet moves.
|
||||||
|
const segs: IconSeg<AppId>[] = [];
|
||||||
|
const picker = () => {
|
||||||
|
if (choices.length < 2) return null;
|
||||||
|
const s = iconSeg(
|
||||||
|
choices.map((a) => ({ value: a.id, label: a.name, icon: APP_ICON[a.id] })),
|
||||||
|
app,
|
||||||
|
(v) => {
|
||||||
|
app = v;
|
||||||
|
rememberApp(d, v);
|
||||||
|
segs.forEach((x) => x.sync(v));
|
||||||
|
// The sheet glides to its new height; inside, what changed morphs (morphInto).
|
||||||
|
glide(fill);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
segs.push(s);
|
||||||
|
return s.el;
|
||||||
|
};
|
||||||
|
const title1 = h('span', { class: 'step-t' });
|
||||||
|
const getBox = h('div', { class: 'step-box' });
|
||||||
|
const addBox = h('div', { class: 'step-box' });
|
||||||
|
const codeBox = h('div', { class: 'step-box' });
|
||||||
|
const sendBox = h('div', { class: 'step-box' });
|
||||||
|
let code: CodeRow | null = null;
|
||||||
|
let scan: ScanLine | null = null;
|
||||||
|
let codeApp: AppId | null = null;
|
||||||
|
const pill =
|
||||||
|
layout === 'away'
|
||||||
|
? connPill(() => ({
|
||||||
|
...(app === 'vpn'
|
||||||
|
? { text: key, msg: 'Key copied', file: keyFileName(cfg.filename) }
|
||||||
|
: { text: cfg.conf, msg: 'Configuration copied', file: cfg.filename }),
|
||||||
|
app: APP_NAME[app],
|
||||||
|
}))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
/** Everything a pick changes, refilled in place. */
|
||||||
|
function fill() {
|
||||||
|
morphText(title1, router ? `Get ${APP_NAME[app]} on the router` : `Get ${APP_NAME[app]}`, undefined, { whole: true });
|
||||||
|
morphInto(getBox, storeBlock(app, pf, router));
|
||||||
|
// The router's file is the same for either app: it stays as it is (a folded configuration stays folded).
|
||||||
|
if (!router) morphInto(addBox, connectKids(c));
|
||||||
|
else if (!addBox.firstChild) put(addBox, filePane(cfg));
|
||||||
|
const text = app === 'vpn' ? vpnQrText(key) : cfg.conf;
|
||||||
|
// Another app: its words morph in place, the code changes only when it holds something else (codes.ts).
|
||||||
|
if (code && scan && code.el.isConnected) {
|
||||||
|
if (codeApp !== app) {
|
||||||
|
code.swap(text);
|
||||||
|
scan.set(app);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scan = scanLine(app);
|
||||||
|
code = codeRow(text, [scan.el]);
|
||||||
|
codeBox.replaceChildren(code.el);
|
||||||
|
}
|
||||||
|
codeApp = app;
|
||||||
|
morphInto(sendBox, sendKids(c));
|
||||||
|
pill?.sync();
|
||||||
|
}
|
||||||
|
fill();
|
||||||
|
|
||||||
|
// Not on the device: the link goes there (as a code for a phone's camera); the page there does the rest.
|
||||||
|
const linkThere = setupLink(pageUrl(), d.id);
|
||||||
|
const linkBody = () => [
|
||||||
|
handheld
|
||||||
|
? codeRow(linkThere, [h('span', {}, 'Point its camera at the code: the link opens there.')]).el
|
||||||
|
: h('p', { class: 'desc' }, `Open this link on the ${there} to set it up there.`),
|
||||||
|
linkRow(linkThere),
|
||||||
|
];
|
||||||
|
const step1 = () => step('1', title1, [picker(), getBox]);
|
||||||
|
const step2 = () => step('2', router ? 'Import the configuration' : 'Add the connection', [addBox]);
|
||||||
|
|
||||||
|
const body = h('div', { class: 'setup' });
|
||||||
|
if (inWebview(navigator.userAgent))
|
||||||
|
body.appendChild(
|
||||||
|
notice('warn', 'shield', null, 'Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.'),
|
||||||
|
);
|
||||||
|
if (layout === 'same') {
|
||||||
|
// Opened, the way round folds the steps away: the device is not in hand.
|
||||||
|
const steps = h('div', { class: 'steps-wrap' }, h('div', { class: 'steps-gap' }), step1(), step2());
|
||||||
|
const round = accordion([{ icon: glass('link'), title: `Not on the ${there} right now?`, body: linkBody() }], {
|
||||||
|
inset: true,
|
||||||
|
onToggle: (_i, open, instant) => foldBlock(steps, open, instant),
|
||||||
|
});
|
||||||
|
body.append(round.el, steps);
|
||||||
|
} else if (layout === 'router') body.append(step1(), step2());
|
||||||
|
// A phone or a tablet set up from here: its link as a code, or the connection as a code for an app it has.
|
||||||
|
else if (layout === 'away')
|
||||||
|
body.appendChild(
|
||||||
|
accordion(
|
||||||
|
[
|
||||||
|
{ icon: glass('link'), title: `Open your link on the ${there}`, body: linkBody() },
|
||||||
|
{ icon: glass('app'), title: 'Already has the app', body: [picker(), codeBox] },
|
||||||
|
],
|
||||||
|
{ inset: true, open: 1 },
|
||||||
|
).el,
|
||||||
|
);
|
||||||
|
// A computer set up from somewhere else: its system is not known here, so the link goes there and the page there does both steps.
|
||||||
|
else
|
||||||
|
body.appendChild(
|
||||||
|
accordion(
|
||||||
|
[
|
||||||
|
{ icon: glass('link'), title: `Open your link on the ${there}`, body: linkBody() },
|
||||||
|
{ icon: glass('key'), title: 'Copy or save the connection', body: [picker(), sendBox] },
|
||||||
|
],
|
||||||
|
{ inset: true, open: 0 },
|
||||||
|
).el,
|
||||||
|
);
|
||||||
|
|
||||||
|
const way = waitWay(d);
|
||||||
|
let finished = false;
|
||||||
|
onLeave(
|
||||||
|
watchFirstConnection(
|
||||||
|
d,
|
||||||
|
() => {
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
|
void arrive(way, body, d);
|
||||||
|
},
|
||||||
|
way.gaveUp,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
// Closed before the device connected: the page shows what the polls brought.
|
||||||
|
onClosed(() => repaint());
|
||||||
|
|
||||||
|
const subline =
|
||||||
|
layout === 'same' ? 'Two steps, about a minute' : router ? 'The packages and the file for OpenWrt' : `The app goes on the ${there}.`;
|
||||||
|
const el = h('div', { class: 'view' }, head(`Set up ${d.name}`, { acts: !!pill }), sub(subline), way.el, body);
|
||||||
|
return { el, label: `Set up ${d.name}`, acts: pill?.el ?? null };
|
||||||
|
}
|
||||||