-[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/ci.yml)
-[](https://github.com/tickcount/luci-app-dawnline/actions/workflows/build.yml)
+
+
+
+
-Your OpenWrt router as a private VPN for the people you choose.
+
Dawnline
-Dawnline runs an [AmneziaWG](https://docs.amnezia.org/) server on the router
-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.
+**Your OpenWrt router as a private VPN for the people you choose.**
-Dawnline is the successor of [Liminal](https://github.com/tickcount/openwrt-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**](#-quick-start) · [Features](#-features) · [How it works](#-how-it-works) · [Screenshots](#-a-closer-look) · [FAQ](#-faq) · [Development](#-development)
-| People | A person |
+
+
+
+
+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**.
+
+
+
+
+ A person's own page: their devices and access. Adding a phone takes three steps, and the page sees it connect.
+
+
+## 💡 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: Network › Dawnline, and follow the
+ wizard. It suggests the port, the public address and the networks.
+3. **Invite** someone: Add person, 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
+
+
+
+
+
🔗 A link, not an account
+
Three words, like vpn.example.com/kamiro-telosu-bavine. The link is the key: no sign-up, no password, and a new link locks the old one out at once.
+
+
+
📱 Their own devices
+
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.
+
+
+
+
+
👥 People, not peers
+
One card per person with their devices, who is online, traffic, end date and data limit. Filter by who needs attention or is paused.
+
+
+
🧭 Who reaches what
+
The home network, the internet or both; only some networks or devices at home (a NAS, Home Assistant). Family sees family, guests see guests.
+
+
+
+
+
⏳ Limits
+
End dates, monthly or total data limits, allowed hours, a pause button. Changes apply at once, without dropping anyone else's connection.
+
+
+
🕶️ Disguise
+
Presets that make the VPN traffic harder to spot and block, with what each one needs from the apps.
+
+
+
+
+
🏠 Internet like a home device
+
People's devices go online the way the devices at home do, so your proxies, ad and DNS filters cover them too.
+
+
+
🗺️ Overview and places
+
Who is online with what, speed now, the last 30 days, and a map of where people connect from, at city level.
+
+
+
+
+
🩺 Repairs itself
+
Health checks with one-click fixes, and a watchdog that checks the tunnels, access rules and portal every minute and mends them.
+
+
+
📦 Updates and backups
+
Dawnline and AmneziaWG built for your firmware in one place; nightly backups, and export and import to move to another router.
+
+
+
+
+## 🧩 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 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
+
+
+
+
+ Overview: who is online, speed now, the last 30 days and a map of where people connect from.
+
+
+
+
+
+
+
People: online, ending soon, over the limit, outside their hours, paused.
+
+
+
+
A person: their devices, traffic, places and limits.
+
+
+
+
+## 📋 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 |
-|---|---|
-|  |  |
-
-## 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:
+## 📥 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
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,
-checks it against `sha256sums.txt`, installs AmneziaWG built for your firmware
-if it is missing, then installs Dawnline with its dependencies and checks that
-LuCI can reach it. Then open **LuCI → Network → Dawnline** and run the setup
-wizard.
+changes anything. It downloads the package for your package manager, checks it
+against `sha256sums.txt`, installs AmneziaWG built for your firmware if it is
+missing, then installs Dawnline and checks that LuCI can reach it.
-Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
-and the service state to `/etc/dawnline/installer-backups/` (the newest three
-are kept); if a step fails, it puts them back. Packages are not rolled back: to
-return to an older release, run the installer with `--tag`. Everything it does
-is logged to `/tmp/dawnline-install.log`.
+> [!NOTE]
+> Before changing anything it saves `/etc/config/{dawnline,network,firewall,dhcp,uhttpd}`
+> and the service state to `/etc/dawnline/installer-backups/` (the newest three
+> are kept), and puts them back if a step fails. Packages are not rolled back:
+> to return to an older release, run the installer with `--tag`. Everything it
+> does is logged to `/tmp/dawnline-install.log`.
+
+
+Installer options
+
+
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 |
| `-v`, `--verbose` / `-q`, `--quiet` | More detail / only warnings and errors |
| `--tag X.Y.Z` | A given release (`sh install.sh 0.3.1` works too) |
-| `--awg auto\|slava\|grey\|skip` | Where AmneziaWG comes from when it is missing: [Slava-Shchipunov](https://github.com/Slava-Shchipunov/awg-openwrt), then [2Grey](https://github.com/2Grey/awg-openwrt) (`auto`, the default), only one of them, or not at all (install it later from **Dawnline → Updates**). `DAWNLINE_AWG` does the same |
+| `--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` |
-When GitHub is slow or blocked, the installer retries downloads through
-`ghfast.top` and `gh-proxy.com` on its own. To fetch the installer itself
-through a mirror:
+
+
+
+When GitHub is slow or blocked
+
+
+
+The installer retries downloads through `ghfast.top` and `gh-proxy.com` on its
+own. To fetch the installer itself through a mirror:
```sh
sh -c "$(wget -qO- https://cdn.jsdelivr.net/gh/tickcount/luci-app-dawnline@main/install.sh)"
sh -c "$(wget -qO- https://ghfast.top/https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/install.sh)"
```
-By hand, from a [release](https://github.com/tickcount/luci-app-dawnline/releases):
+
+
+
+Installing by hand
+
+
+
+From a [release](https://github.com/tickcount/luci-app-dawnline/releases):
```sh
opkg update && opkg install ./luci-app-dawnline-0.1.0.ipk # OpenWrt 24.10
apk update && apk add --allow-untrusted ./luci-app-dawnline-0.1.0.apk # OpenWrt 25.12
```
-**Upgrade** from **Dawnline → Updates**, or run the installer again. Settings,
-keys and history are kept, and a backup is made first.
+
-**Remove** on the router:
+**Upgrade** from Dawnline › Updates, or run the installer
+again. Settings, keys and history are kept, and a backup is made first.
+
+### Remove
```sh
sh -c "$(wget -qO- https://raw.githubusercontent.com/tickcount/luci-app-dawnline/main/uninstall.sh)"
```
It backs up the configuration to `/etc/dawnline/backups`, runs Dawnline's own
-removal (the same as **Settings → Remove Dawnline from this router**), removes
-the package and cleans up what is left. AmneziaWG stays installed, since other
-tunnels may use it. After installing Dawnline again, restore the backup in
-**Settings → Backups**. With options, download it first:
+removal (the same as Settings › Remove Dawnline from this router),
+removes the package and cleans up what is left. After installing Dawnline
+again, restore the backup in Settings › Backups.
+
+> [!IMPORTANT]
+> AmneziaWG stays installed, since other tunnels may use it. Add `--remove-awg`
+> to take it away too.
+
+
+Uninstaller options
+
+
+
+With options, download it first:
```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) |
| `-n`, `--dry-run` | Show what would be removed; change nothing |
-By hand: **Settings → Remove Dawnline from this router** (keeps a backup), then
-`opkg remove luci-app-dawnline` or `apk del luci-app-dawnline`.
+By hand: Settings › Remove Dawnline from this router
+(keeps a backup), then `opkg remove luci-app-dawnline` or
+`apk del luci-app-dawnline`.
-## What Dawnline changes on the router
+
+
+## ❓ FAQ
+
+
+Which apps do people use?
+
+
+
+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.
+
+
+
+
+What happens when someone loses their link?
+
+
+
+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.
+
+
+
+
+Does it touch the rest of my router?
+
+
+
+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).
+
+
+
+
+How do I move to another router?
+
+
+
+Export JSON in Settings › Backups on the old
+one, install Dawnline on the new one and import the file there.
+
+
+
+
+Where do the places on the map come from?
+
+
+
+From the address a device connects from, looked up at city level and cached on
+the router. It can be turned off in Settings.
+
+
+
+## 🧾 What Dawnline changes on the router
Only objects it created: network interfaces tagged `_dawnline`, firewall
sections named `dawnline_*`, the `inet dawnline` nft table, `/tmp/hosts/dawnline`,
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
-one routing table, a second dnsmasq instance on port 5354
-(`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat check
-and, while the portal is on, a uhttpd instance for it. `dawnline teardown`
-removes all of them.
+latter a port of the LAN bridge, which needs `kmod-veth`), policy rules for the
+tunnel interfaces with one routing table, a second dnsmasq instance on port
+5354 (`/var/etc/dawnline-dns.conf`), a cron line for the agent's heartbeat
+check and, while the portal is on, a uhttpd instance for it.
+`dawnline teardown` removes all of them.
Data lives in `/etc/config/dawnline` (mode 0600, contains private keys) and
`/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/
@@ -203,18 +384,25 @@ npm ci
npm run format # Prettier
npm run ci # format check, types, tests, minified bundles
-scripts/lint-ucode.py # static ucode checks
-scripts/check-ucode.sh root@router # compile every ucode file on a router
-scripts/deploy.sh root@router # install the working tree (backs up configs first)
-scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
-scripts/capture-screenshots.mjs # capture docs/screenshots/raw/*.png from a router
-scripts/frame-screenshots.py # frame them for this README
+scripts/lint-ucode.py # static ucode checks
+scripts/check-ucode.sh root@router # compile every ucode file on a router
+scripts/deploy.sh root@router # install the working tree (backs up configs first)
+scripts/build-packages.sh all # .ipk and .apk with the OpenWrt SDK in Docker
+scripts/capture-screenshots.mjs --demo # README screenshots from a router, a demo cast in place of its people
+scripts/frame-screenshots.py # frame them for this README
```
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
and publishes a release with `sha256sums.txt`.
-## License
+---
-[MIT](LICENSE)
+
",_},N.createSvgTag=function(P,D,_,I){var M={};typeof arguments[0]=="object"&&(M=arguments[0],P=M.cellSize,D=M.margin,_=M.alt,I=M.title),P=P||2,D=typeof D>"u"?P*4:D,_=typeof _=="string"?{text:_}:_||{},_.text=_.text||null,_.id=_.text?_.id||"qrcode-description":null,I=typeof I=="string"?{text:I}:I||{},I.text=I.text||null,I.id=I.text?I.id||"qrcode-title":null;var j=N.getModuleCount()*P+D*2,J,V,pe,xe,ne="",De;for(De="l"+P+",0 0,"+P+" -"+P+",0 0,-"+P+"z ",ne+='",ne},N.createDataURL=function(P,D){P=P||2,D=typeof D>"u"?P*4:D;var _=N.getModuleCount()*P+D*2,I=D,M=_-D;return B(_,_,function(j,J){if(I<=j&&j"u"?P*4:D;var I=N.getModuleCount()*P+D*2,M="";return M+="",M};var O=function(P){for(var D="",_=0;_":D+=">";break;case"&":D+="&";break;case'"':D+=""";break;default:D+=I;break}}return D},X=function(P){var D=1;P=typeof P>"u"?D*2:P;var _=N.getModuleCount()*D+P*2,I=P,M=_-P,j,J,V,pe,xe,ne={"██":"█","█ ":"▀"," █":"▄"," ":" "},De={"██":"▀","█ ":"▀"," █":" "," ":" "},Ae="";for(j=0;j<_;j+=2){for(V=Math.floor((j-I)/D),pe=Math.floor((j+1-I)/D),J=0;J<_;J+=1)xe="█",I<=J&&J=M?De[xe]:ne[xe];Ae+=`
-`}return _%2&&P>0?Ae.substring(0,Ae.length-_-1)+Array(_+1).join("▀"):Ae.substring(0,Ae.length-1)};return N.createASCII=function(P,D){if(P=P||1,P<2)return X(D);P-=1,D=typeof D>"u"?P*2:D;var _=N.getModuleCount()*P+D*2,I=D,M=_-D,j,J,V,pe,xe=Array(P+1).join("██"),ne=Array(P+1).join(" "),De="",Ae="";for(j=0;j<_;j+=1){for(V=Math.floor((j-I)/P),Ae="",J=0;J<_;J+=1)pe=1,I<=J&&J>>8),z.push(S&255)):z.push(E)}}return z}};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 w=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],v=1335,y=7973,E=21522,k={},z=function(f){for(var g=0;f!=0;)g+=1,f>>>=1;return g};return k.getBCHTypeInfo=function(f){for(var g=f<<10;z(g)-z(v)>=0;)g^=v<=0;)g^=y<5&&(S+=3+W-5)}for(var T=0;T=256;)k-=255;return w[k]},E})();function s(w,v){if(typeof w.length>"u")throw w.length+"/"+v;var y=(function(){for(var k=0;k"u")throw"bad rs block @ typeNumber:"+k+"/errorCorrectionLevel:"+z;for(var g=f.length/3,S=[],T=0;T>>7-E%8&1)==1},y.put=function(E,k){for(var z=0;z>>k-z-1&1)==1)},y.getLengthInBits=function(){return v},y.putBit=function(E){var k=Math.floor(v/8);w.length<=k&&w.push(0),E&&(w[k]|=128>>>v%8),v+=1},y},c=function(w){var v=e.MODE_NUMBER,y=w,E={};E.getMode=function(){return v},E.getLength=function(f){return y.length},E.write=function(f){for(var g=y,S=0;S+2>>8&255)*192+(T&255),f.put(T,13),S+=2}if(S>>8)},v.writeBytes=function(y,E,k){E=E||0,k=k||y.length;for(var z=0;z0&&(y+=","),y+=w[E];return y+="]",y},v},h=function(){var w=0,v=0,y=0,E="",k={},z=function(g){E+=String.fromCharCode(f(g&63))},f=function(g){if(!(g<0)){if(g<26)return 65+g;if(g<52)return 97+(g-26);if(g<62)return 48+(g-52);if(g==62)return 43;if(g==63)return 47}throw"n:"+g};return k.writeByte=function(g){for(w=w<<8|g&255,v+=8,y+=1;v>=6;)z(w>>>v-6),v-=6},k.flush=function(){if(v>0&&(z(w<<6-v),w=0,v=0),y%3!=0)for(var g=3-y%3,S=0;S=v.length){if(k==0)return-1;throw"unexpected end of file./"+k}var g=v.charAt(y);if(y+=1,g=="=")return k=0,-1;if(g.match(/^\s$/))continue;E=E<<6|f(g.charCodeAt(0)),k+=6}var S=E>>>k-8&255;return k-=8,S};var f=function(g){if(65<=g&&g<=90)return g-65;if(97<=g&&g<=122)return g-97+26;if(48<=g&&g<=57)return g-48+52;if(g==43)return 62;if(g==47)return 63;throw"c:"+g};return z},C=function(w,v){var y=w,E=v,k=new Array(w*v),z={};z.setPixel=function(T,N,W){k[N*y+T]=W},z.write=function(T){T.writeString("GIF87a"),T.writeShort(y),T.writeShort(E),T.writeByte(128),T.writeByte(0),T.writeByte(0),T.writeByte(0),T.writeByte(0),T.writeByte(0),T.writeByte(255),T.writeByte(255),T.writeByte(255),T.writeString(","),T.writeShort(0),T.writeShort(0),T.writeShort(y),T.writeShort(E),T.writeByte(0);var N=2,W=g(N);T.writeByte(N);for(var q=0;W.length-q>255;)T.writeByte(255),T.writeBytes(W,q,255),q+=255;T.writeByte(W.length-q),T.writeBytes(W,q,W.length-q),T.writeByte(0),T.writeString(";")};var f=function(T){var N=T,W=0,q=0,Y={};return Y.write=function(R,K){if(R>>>K)throw"length over";for(;W+K>=8;)N.writeByte(255&(R<>>=8-W,q=0,W=0;q=R<0&&N.writeByte(q)},Y},g=function(T){for(var N=1<>6,128|i&63):i<55296||i>=57344?o.push(224|i>>12,128|i>>6&63,128|i&63):(a++,i=65536+((i&1023)<<10|r.charCodeAt(a)&1023),o.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return o}return e(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof nr=="object"&&(or.exports=n())})(function(){return tr})});function Gn(n,e){return n==null||n===!1||n===""||(Array.isArray(n)?n.forEach(r=>Gn(r,e)):e.push(n instanceof Node?n:String(n))),e}function t(n,e,r){let o=window.E,a=e!=null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Node);return!a&&r===void 0?o(n,{},Gn(e,[])):o(n,a?e:{},Gn(r,[]))}var Do={phone:'',computer:'',tablet:'',router:'',server:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',amnezia:'',amneziawg:'',wireguard:'',appstore:'',googleplay:'',github:'',openwrt:'',apple:'',windows:'',linux:'',eye:'',share:'',arrow:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function ft(n,e="dl-icon"){let r=Do[n]??Do.phone;return``}function b(n,e="dl-icon"){let r=document.createElement("span");return r.className="dl-icon-wrap",r.innerHTML=ft(n,e),r}function U(n,e="info",r=0){let o=document.querySelector(".dl-toasts");o||(o=t("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(o));let a=e==="error"?"x":e==="warning"?"alert":e==="success"?"check":null,i=()=>{s.classList.remove("show"),setTimeout(()=>s.remove(),200)},s=t("div",{class:`dl-toast ${e}`},[a?b(a):"",t("span",{},n),e==="error"?t("button",{type:"button","aria-label":"Close",click:i},b("x")):""]);o.appendChild(s),requestAnimationFrame(()=>s.classList.add("show")),setTimeout(i,r||(e==="error"?8e3:e==="warning"?5e3:2600))}function be(n){return n instanceof Error?n.message:String(n)}async function G(n,e){try{let r=await n();return e&&U(e,"success",3500),r}catch(r){U(be(r),"error",1e4);return}}function Ao(n){try{let e=n();e&&typeof e.then=="function"&&e.catch(r=>U(be(r),"error"))}catch(e){U(be(e),"error")}}function Ho(n){if(n&&typeof n=="object"){if(typeof n.error=="string")throw new Error(n.error);typeof n.warning=="string"&&n.warning&&U(n.warning,"warning",12e3)}return n}function F(n,e=[]){let r=rpc.declare({object:"luci.dawnline",method:n,params:e});return async(...o)=>Ho(await r(...o))}var Li=F("logs_clear",["person","device","category","older_days"]),Mi=(n={})=>Li(n.person??"",n.device??"",n.category??"",n.older_days??""),Si=rpc.declare({object:"luci.dawnline",method:"person_update",params:["id","name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode","paused","services","circle","home_nets","server"]});async function Ti(n,e){let o=[n,...["name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode"].map(a=>e[a]),e.paused,e.services,e.circle,e.home_nets,e.server];return Ho(await Si(...o))}var _i=F("status",["days"]),A={rev:F("rev"),personUpdate:Ti,settingsGet:F("settings_get"),portalInfo:F("portal_info"),settingsUpdate:F("settings_update",["values"]),serviceSet:F("service_set",["id","name","address","ports"]),serviceDelete:F("service_delete",["id"]),geoClear:F("geo_clear"),events:F("events",["limit","person","since"]),logsClear:Mi,interfaces:F("interfaces",["id"]),serverInterfaces:F("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like","device_mesh","mesh"]),circleSet:F("circle_set",["id","server","name","color","members"]),circleDelete:F("circle_delete",["id"]),accessCheck:F("access_check",["from","to"]),homeHosts:F("home_hosts",["id"]),usageClear:F("usage_clear",["scope","id"]),uninstall:F("uninstall",["confirm"]),status:_i,setupDefaults:F("setup_defaults"),serverCreate:F("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:F("server_obfuscation",["id","preset"]),serverUpdate:F("server_update",["id","values"]),serverPorts:F("server_ports",["id"]),endpointProbe:F("endpoint_probe",["host","id","port"]),serverDelete:F("server_delete",["id"]),personLinks:F("person_links",["id"]),personCreate:F("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:F("person_pause",["id","paused"]),personRegen:F("person_regen",["id","remove"]),personDelete:F("person_delete",["id"]),personUsage:F("person_usage",["id","days"]),deviceCreate:F("device_create",["person","name","kind"]),deviceConfig:F("device_config",["id"]),deviceUpdate:F("device_update",["id","name","disabled"]),deviceDelete:F("device_delete",["id"]),deviceRotate:F("device_rotate",["id"]),apply:F("apply"),health:F("health"),healthFix:F("health_fix",["id"]),serviceLog:F("service_log"),serviceLogClear:F("service_log_clear",["older_days"]),backupList:F("backup_list"),backupCreate:F("backup_create"),backupRestore:F("backup_restore",["name"]),backupDelete:F("backup_delete",["name"]),backupRead:F("backup_read",["name"]),backupUpload:F("backup_upload",["data"]),exportJson:F("export"),importJson:F("import",["data"]),updatesStatus:F("updates_status"),updatesRun:F("updates_run",["what"]),updatesReleases:F("updates_releases",["page"]),updatesNotes:F("updates_notes",["component","tag","build"]),updatesChanges:F("updates_changes",["from","to"])};function H(n,e,r="neutral",o={}){let{disabled:a,...i}=o,s=t("button",{class:`cbi-button cbi-button-${r}`,type:"button",...i,click:async l=>{if(l.preventDefault(),l.stopPropagation(),!s.disabled){s.disabled=!0,s.classList.add("spinning");try{await e(l)}catch(d){U(be(d),"error")}finally{s.disabled=!1,s.classList.remove("spinning")}}}},n);return s.disabled=!!a,s}function Le(n,e,r,o="neutral",a=""){return H([b(n),t("span",{class:"dl-btn-label"},e)],r,o,{title:e,class:`cbi-button cbi-button-${o} dl-icon-btn ${a}`.trim()})}function $e(n){return document.addEventListener("luci-navigate",n),()=>document.removeEventListener("luci-navigate",n)}var gt=null;function Wn(n=!1){let e=gt;gt=null,e?.(n)}function oe(n,e,r,o=""){Wn();let a=t("div",{class:`dl-modal ${o}`},e),i=t("div",{class:"button-row"},r);a.addEventListener("keydown",s=>{if(s.key==="Escape"){s.preventDefault(),s.stopPropagation(),ae();return}if(s.key!=="Enter"||s.shiftKey||s.ctrlKey||s.metaKey||s.altKey)return;let l=s.target;if(!l||["TEXTAREA","BUTTON","SELECT","A"].includes(l.tagName))return;let d=i.querySelector(".cbi-button-positive");!d||d.disabled||(s.preventDefault(),d.click())}),ui.showModal(n,[a,i])}function ae(){Wn(),ui.hideModal()}function ie(n="Cancel",e=!1){return t("button",{class:`cbi-button ${e?"cbi-button-negative":"cbi-button-neutral"}`,type:"button",click:ae},n)}function le(n,e,r="Confirm",o=!1){return new Promise(a=>{oe(n,e,[ie()," ",t("button",{class:`cbi-button ${o?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{let i=gt;gt=null,ui.hideModal(),i?.(!0)}},r)]),gt=a})}$e(()=>{gt&&(Wn(),ui.hideModal())});async function ue(n,e="Copied to clipboard",r=!1){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(n);else{let o=t("textarea",{style:"position:fixed;opacity:0"},n);document.body.appendChild(o),o.select();let a=document.execCommand("copy");if(o.remove(),!a)throw new Error("Copying is blocked here. Select the text and copy it by hand.")}return U(e,"success",2500),!0}catch(o){return r||U(be(o),"error"),!1}}function Te(n,e,r="text/plain"){let o=globalThis,a=typeof e=="string"?new o.Blob([e],{type:r}):e,i=URL.createObjectURL(a),s=t("a",{href:i,download:n,style:"display:none"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(i),s.remove()},1e3)}function Fn(n,e){return new Promise(r=>{let o=t("input",{type:"file",accept:n,style:"display:none"});o.addEventListener("cancel",()=>{o.remove(),r(null)}),o.addEventListener("change",()=>{let a=o.files?.[0];if(o.remove(),!a)return r(null);let i=new FileReader;i.onload=()=>{let s=String(i.result??"");r({name:a.name,data:e==="base64"?s.replace(/^data:[^,]*,/,""):s})},i.onerror=()=>r(null),e==="base64"?i.readAsDataURL(a):i.readAsText(a)}),document.body.appendChild(o),o.click()})}function Ce(n,e){let r=document.querySelector(".dl-dd");if(r&&(r.dlClose?r.dlClose():r.remove(),r.dlAnchor===n))return;let o=t("div",{class:"dl-dd dl-root",role:"menu"},e.map(u=>u?t("button",{type:"button",role:"menuitem",class:u.danger?"danger":u.warn?"warn":"",click:()=>{p(),Ao(u.run)}},[u.icon??"",t("span",{},u.label)]):t("hr")));document.body.appendChild(o);let a=n.getBoundingClientRect(),i=o.offsetWidth,s=o.offsetHeight;o.style.top=`${a.bottom+6+s>window.innerHeight-8&&a.top-6-s>8?a.top-6-s:a.bottom+6}px`,o.style.left=`${Math.max(8,Math.min(a.right-i,window.innerWidth-i-8))}px`;let l=u=>{!o.contains(u.target)&&!n.contains(u.target)&&p()},d=u=>{if(u.key==="Escape"||u.key==="Tab")return p();let x=[...o.querySelectorAll("button:not([disabled])")];if(!x.length||!["ArrowDown","ArrowUp","Home","End"].includes(u.key))return;u.preventDefault();let $=x.indexOf(document.activeElement),h=u.key==="Home"?0:u.key==="End"?x.length-1:u.key==="ArrowDown"?($+1)%x.length:($-1+x.length)%x.length;x[h].focus({preventScroll:!0})},c=$e(p);o.dlAnchor=n,o.dlClose=p;function p(){o.remove(),c(),document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",p,!0)}setTimeout(()=>{document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",p,!0)}),o.querySelector("button")?.focus({preventScroll:!0})}var dt=null,Je=null,qn=0;function vt(){dt&&(dt.style.display="none"),Je=null,clearInterval(qn),qn=0}function me(n,e){let r=o=>{dt??(dt=document.body.appendChild(t("div",{class:"dl-tip dl-tip-float dl-root"}))),dt.replaceChildren(...e().map(a=>typeof a=="string"?document.createTextNode(a):a)),dt.style.display="",dt.style.left=`${o.clientX}px`,dt.style.top=`${o.clientY-10}px`,Je=n,qn||(qn=window.setInterval(()=>{(!Je?.isConnected||!Je.getClientRects().length)&&vt()},400))};n.addEventListener("mouseenter",r),n.addEventListener("mousemove",r),n.addEventListener("mouseleave",vt),n.addEventListener("pointerup",o=>{o.pointerType!=="mouse"&&(Je===n?vt():r(o))})}$e(vt);window.addEventListener("scroll",()=>Je&&vt(),{capture:!0,passive:!0});document.addEventListener("pointerdown",n=>{Je&&!Je.contains(n.target)&&vt()},!0);function ee(n){if(!n||n<0)return"0 B";let e=["B","KB","MB","GB","TB"],r=0,o=n;for(;o>=1024&&r=100||r===0?Math.round(o):o.toFixed(1)} ${e[r]}`}function Oe(n){let e=n*8;return e<1e3?`${Math.round(e)} bit/s`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)} kbit/s`:e<1e9?`${(e/1e6).toFixed(e<1e7?1:0)} Mbit/s`:`${(e/1e9).toFixed(1)} Gbit/s`}function re(n,e=Date.now()/1e3){if(!n)return"never";let r=Math.max(0,Math.round(e-n));return r<60?"just now":r<3600?`${Math.floor(r/60)} min ago`:r<86400?`${Math.floor(r/3600)} h ago`:r<86400*30?`${Math.floor(r/86400)} d ago`:new Date(n*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function xt(n){if(!n||n<0)return"—";let e=Math.floor(n/86400),r=Math.floor(n%86400/3600),o=Math.floor(n%3600/60);return e?`${e}d ${r}h`:r?`${r}h ${o}m`:`${o}m`}function zt(n){let e=new Date(n*1e3),r=new Date,o=e.toDateString()===r.toDateString(),a=e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return o?a:`${e.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${a}`}function je(n){return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`}function wt(n){let[e,r,o]=n.split("-").map(Number);return new Date(e,(r||1)-1,o||1,12)}function Ue(n){return(typeof n=="string"?/^\d{4}-\d{2}-\d{2}$/.test(n)?wt(n):new Date(n):n).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Me(n){return n?Ue(n):""}function Kn(n,e){let r=o=>{let[a,i,s]=o.split("-").map(Number);return Date.UTC(a,i-1,s)};return Math.round((r(n)-r(e))/864e5)}function Ht(n,e){let r=wt(n);return r.setDate(r.getDate()+e),je(r)}function bt(n,e){let[r,o,a]=n.split("-").map(Number),i=new Date(r,o-1+e,1,12),s=new Date(i.getFullYear(),i.getMonth()+1,0).getDate();return i.setDate(Math.min(a,s)),je(i)}function Ie(n){return n?.length?n[n.length-1].day:je(new Date)}function zo(n,e,r,o,a=30){let i=n||o;return e==="day"?Ht(i,r):e==="week"?Ht(i,7*r):e==="month"?bt(i,r):e==="year"?bt(i,12*r):Ht(i,a*r)}function Ye(n,e=Date.now()){if(!n)return null;let r=typeof e=="number"?je(new Date(e)):e,o=Kn(n,r);return o>=0?o+1:o}function Ze(n,e){return e!=null&&e>0&&n.expire_warn>0&&e<=n.expire_warn}function en(n){return n<=1?"ends today":n===2?"ends tomorrow":`ends in ${n} days`}function tn(n,e,r=`${e}s`){return`${n.toLocaleString("en-GB")} ${n===1?e:r}`}function Nt(n){return n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(n<10240?1:0)} KB`:`${(n/1048576).toFixed(1)} MB`}var ct={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var No=["computer","phone","tablet","router","other"],Qe={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Ro={active:"Active",paused:"Paused",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server",server_off:"Server is turned off"};function He(n){let e=n.trim().split(/\s+/).filter(Boolean);if(!e.length)return"?";let r=e[0][0]??"",o=e.length>1?e[e.length-1][0]??"":e[0][1]??"";return(r+o).toUpperCase()}function nn(n){let e=r=>r.disabled?3:r.online?0:r.handshake?1:2;return n.map((r,o)=>[r,o]).sort((r,o)=>e(r[0])-e(o[0])||r[1]-o[1]).map(([r])=>r)}function Ee(n,e,r){return t("span",{class:`dl-pill ${n}`,title:r??null},e)}function Pi(n){return n.state==="active"?"ok":n.state==="quota"||n.state==="expired"?"bad":"warn"}function Di(n){return n.state==="server_off"&&n.paused?"paused":n.state}function Io(n){let e=Di(n);return e==="active"||e==="server_off"?"":Ee(Pi({...n,state:e}),Ro[e])}function Bo(n){let e=n.access==="both"?["lan","inet"]:n.access==="lan"?["lan"]:["inet"],r=t("span",{class:"dl-access","aria-label":ct[n.access]},e.map(o=>t("span",{class:`dl-ibadge ${o}`},b(o==="lan"?"home":"globe"))));return me(r,()=>[t("div",{class:"dl-tip-title"},ct[n.access]),n.access==="lan"&&n.services?.length?t("div",{class:"dl-muted"},`${n.services.length} home service${n.services.length===1?"":"s"} only`):""]),r}var Ai={paused:"Paused",expired:"Access ended",quota:"Data limit",hours:"Outside hours",server_off:"Server off",no_server:"No server"};function on(n,e,r="Not set up yet",o){let a=n.handshake?`Last seen ${re(n.handshake,e)} · ${new Date(n.handshake*1e3).toLocaleString()}`:"";if(n.disabled)return t("span",{class:"dl-dstat",title:a},"Disabled");if(n.online)return t("span",{class:"dl-dstat ok"},"Connected");let i=o&&Ai[o.state];return i?t("span",{class:"dl-dstat warn",title:a||"Not connected yet"},i):n.handshake?t("span",{class:"dl-dstat",title:new Date(n.handshake*1e3).toLocaleString()},`Last seen ${re(n.handshake,e)}`):t("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},r)}var rn=null;function Oo(n,e,r,o){rn?.close();let a=t("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[t("div",{class:"dl-drawer-head"},[n,t("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>c()},b("x"))]),t("div",{class:"dl-drawer-body"},e),r?t("div",{class:"dl-drawer-foot"},r):""]),i=t("div",{class:"dl-drawer-overlay dl-root",click:u=>{u.target===i&&c()}},a),s=u=>{u.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&c()},l=!1,d=$e(()=>c());function c(){l||(l=!0,d(),document.removeEventListener("keydown",s),i.classList.remove("open"),setTimeout(()=>i.remove(),220),rn===p&&(rn=null),o())}let p={close:c,panel:a};return document.addEventListener("keydown",s),document.body.appendChild(i),requestAnimationFrame(()=>i.classList.add("open")),rn=p,p}function ce(n,e,r){return t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},n),r?t("span",{class:"dl-sub"},r):""]),t("div",{class:"dl-setrow-ctl"},e)])}function he(n,e,r,o=e){let a=ce(n,o," "),i=a.querySelector(".dl-sub"),s=()=>{let l=r();i.textContent=l.text,i.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",s),a.refresh=s,a.help=r,s(),a}function ye(n,e,r,o=e){let a=t("div",{class:"dl-sub"}),i=t("div",{class:"cbi-value dl-live"},[t("div",{class:"cbi-value-title"},[t("label",{},n),a]),t("div",{class:"cbi-value-field"},o)]),s=()=>{let l=r();a.textContent=l.text,a.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",s),e.addEventListener("change",s),i.refresh=s,i.help=r,s(),i}function ze(n,e=[]){for(let r of n){let o=r.help?.();if(o?.bad)return o.text}for(let r of e){let o=r();if(o.bad)return o.text}return null}function Rt(n,e,r,o=""){return t("section",{class:`dl-setsec ${o}`},[t("div",{class:"dl-setsec-body"},[n?t("h3",{},n):"",...e]),r.length?t("div",{class:"dl-setsec-foot"},r):""])}function fe(n,e,r,o){return t("div",{class:"dl-group"},[t("div",{class:"dl-group-head"},[t("span",{class:"dl-group-ic"},b(n)),t("span",{class:"dl-stack"},[t("b",{},e),r?t("span",{class:"dl-sub"},r):""])]),t("div",{class:"dl-group-body"},o.filter(a=>a!==""))])}function Xe(n,e,r,o,a){return t("div",{class:`dl-row dl-need-row ${e}`},[e?t("span",{class:"dl-need-ic"},b(n)):b(n),t("span",{class:"dl-row-main dl-stack"},[t("b",{},r),t("span",{class:"dl-sub"},o)]),a])}function pt(n,e){let r={ok:"success",warn:"warning",error:"error",info:"notice"}[n];return t("div",{class:`alert-message ${r}`},e)}function et(n,e=""){let r=t("div",{class:e});return r.innerHTML=n,r}function Vn(n){let e=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(n.trim());if(!e)return null;let[r,o,a,i]=e.slice(1,5).map(Number),s=Number(e[5]);if([r,o,a,i].some(c=>c>255)||s<8||s>30)return null;let l=r*2**24+o*2**16+a*2**8+i,d=2**(32-s);return{net:l-l%d,size:d}}var Hi=(n,e)=>n.netVn(n));function $t(n){return n.split("/")[0].split(".").slice(0,3).join(".")}function an(n){return`${n.trim()}.0/24`}function Yn(n,e,r){let o=n.trim(),a=/^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o)?Vn(an(o)):null;if(!a)return{text:"Three numbers, like 10.77.0.",bad:!0};if(!zi.some(s=>a.net>=s.net&&a.net+a.size<=s.net+s.size))return{text:"Use a private range: 10.x.x, 172.16–31.x or 192.168.x.",bad:!0};let i=e.find(s=>{let l=Vn(s.cidr);return l!=null&&Hi(a,l)});if(i){let s=i.cidr.endsWith("/24")?`${$t(i.cidr)}.x`:i.cidr,l=r&&r!==o?` Try ${r}.`:"";return{text:`${i.name} already uses ${s}.${l}`,bad:!0}}return{text:`Devices get ${o}.2 – ${o}.254, the router ${o}.1.`,bad:!1}}var Uo=(n,e)=>e.find(r=>r.from<=n&&n<=r.to)?.who??null,Ni=n=>Number.isInteger(n)&&n>=1&&n<=65535;function It(n,e,r){if(!Ni(n))return{text:"Use a port from 1 to 65535.",bad:!0};let o=Uo(n,e);return o?{text:`Used by ${o}. Choose another port.`,bad:!0}:{text:r,bad:!1}}function sn(n,e,r){let o=r?`HTTPS here, plain HTTP for links on IP addresses on ${n+1}.`:"HTTPS on this port, opened on WAN.",a=It(n,e,o);if(a.bad||!r)return a;if(n===65535)return{text:"Links on IP addresses also need the next port: choose a lower one.",bad:!0};let i=Uo(n+1,e);return i?{text:`Links on IP addresses also need ${n+1}, used by ${i}. Choose another port.`,bad:!0}:a}var yt=n=>Array.from(n).length,jo=48,Ri=/[<>"\\\u0000-\u001f\u007f]/;function _e(n,e=[],r=""){let o=n.trim();return o?yt(n)>jo?{text:`Up to ${jo} characters (${yt(n)} now).`,bad:!0}:Ri.test(n)?{text:'Names can’t contain < > " or \\.',bad:!0}:e.some(a=>a.toLowerCase()===o.toLowerCase())?{text:`“${o}” already exists — pick another name.`,bad:!0}:{text:r,bad:!1}:{text:"Enter a name.",bad:!0}}function Go(n,e=[]){return yt(n)>32?{text:`Up to 32 characters (${yt(n)} now).`,bad:!0}:_e(n,e,"Shown on the person cards.")}var Ii=/^[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])?)*$/,Bi=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;function Ct(n){let e=Bi.exec(n);return!!e&&e.slice(1).every(r=>Number(r)<=255)}function Jn(n){return/^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(n)&&!/:::/.test(n)}function kt(n,e,r=null){let o=n.trim();if(!o)return r!=null?{text:r,bad:!1}:{text:"Enter a hostname or IP address.",bad:!0};if(/^[a-z]+:\/\//i.test(o))return{text:"Leave out https:// — just the name.",bad:!0};if(/\/.*/.test(o))return{text:"Just the name, without a path.",bad:!0};if(/^[^:\[]+:\d+$/.test(o))return{text:"Just the name, without a port (the port is on AmneziaWG).",bad:!0};if(/\s/.test(o))return{text:"A hostname has no spaces.",bad:!0};if(o.length>253||!(Ii.test(o)||Ct(o)||Jn(o)))return{text:"Use a hostname or an IP address.",bad:!0};let a=Jn(o)?`[${o}]`:o;return{text:e?`Devices connect to ${a}:${e}.`:`Links use ${a}.`,bad:!1}}function Wo(n,e){let r=n.split(/[ ,]+/).filter(Boolean);if(!r.length)return{text:`This router (${e}): queries go where your home network sends them, and home names work.`,bad:!1};let o=r.find(a=>!Ct(a)&&!Jn(a));return o?{text:`“${o}” is not an IP address. Separate several with commas.`,bad:!0}:{text:`Devices use ${r.join(" and ")} — home names and your LAN’s DNS filters no longer apply to them.`,bad:!1}}function Fo(n,e){let r=n.trim();if(!r)return{text:`Automatic by device type and disguise: ${e.computer} for computers and routers, ${e.phone} for phones and tablets.`,bad:!1};if(!/^\d{1,4}$/.test(r)||Number(r)<1280||Number(r)>1500)return{text:"MTU must be 1280–1500, or empty for automatic.",bad:!0};let o=Number(r);return{text:`Computers and routers get ${o}, phones and tablets ${Math.min(o,1280)}.`,bad:!1}}function qo(n){let e=n.trim();return e?!/^\d{1,3}$/.test(e)||Number(e)>600?{text:"Use 0–600 seconds.",bad:!0}:Number(e)===0?{text:"Off: NAT may close the tunnel when idle, and “Connected” lags.",bad:!1}:{text:`Devices send a packet every ${e} s to keep NAT open (a little battery on phones).`,bad:!1}:{text:"Default: a packet every 25 s keeps NAT open and “Connected” accurate.",bad:!1}}function ln(n,e=0){let r=n.trim();if(!/^\d{1,2}$/.test(r)||Number(r)<1||Number(r)>32)return{text:"Use 1–32.",bad:!0};let o=Number(r);return e>o?{text:`Already has ${e} devices: remove ${e-o===1?"one":`${e-o}`} first, or allow more.`,bad:!0}:{text:`They can add ${o} device${o===1?"":"s"} themselves.`,bad:!1}}function dn(n,e=!0){let r=n.trim();if(!r)return{text:"Optional. No data limit.",bad:!1};let o=Number(r);return!/^\d+(\.\d+)?$/.test(r)||o<0||o>1e5?{text:"A number of GB, up to 100000.",bad:!0}:o===0?{text:"Optional. No data limit.",bad:!1}:{text:e?`Paused after ${r} GB this month, resumed on the 1st.`:`Paused after ${r} GB in total.`,bad:!1}}function Ko(n,e,r,o){let a=n.trim();if(!a)return{text:"Optional. No end date.",bad:!1};let i=r(a,e);return i==null?{text:"Use a date.",bad:!0}:i<0?{text:"That date has passed: access would end at once.",bad:!0}:{text:i===1?`Access ends today (${o(a)}).`:`Access ends in ${i} days (${o(a)}).`,bad:!1}}function Vo(n,e=null){let r=n.trim();return r?Ct(r)?e&&!e(r)?{text:`${r} is not in any home network of this server: nobody would reach it.`,bad:!1}:{text:"",bad:!1}:{text:"Use an IPv4 address, like 192.168.1.10.",bad:!0}:{text:"The device’s address at home.",bad:!0}}function Jo(n){let e=n.split(/[ ,]+/).filter(Boolean);if(!e.length)return{text:"All ports.",bad:!1};let r=e.find(o=>!/^\d{1,5}$/.test(o)||Number(o)<1||Number(o)>65535);return r?{text:`“${r}” is not a port (1–65535).`,bad:!0}:{text:`Port${e.length===1?"":"s"} ${e.join(", ")}.`,bad:!1}}function Yo(n){let e=n.trim();return e?/^https?:\/\//i.test(e)?e.length>300||!/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(e)?{text:"Not a usable address (no spaces or quotes).",bad:!0}:{text:"Wrong links are sent there instead of a “Not found”.",bad:!1}:{text:"Must start with http:// or https://.",bad:!0}:{text:"Wrong links get a bare “Not found”.",bad:!1}}function Zo(n){return yt(n)>64?{text:`Up to 64 characters (${yt(n)} now).`,bad:!0}:/[\u0000-\u001f\u007f]/.test(n)?{text:"One line, please.",bad:!0}:{text:"Shown in the browser tab and at the top of the portal.",bad:!1}}function Qo(n,e="phone.myata"){let r=n.trim();return r?/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(r)?{text:`Devices get names like ${e}.${r}.`,bad:!1}:{text:/[A-Z]/.test(r)?"Lowercase only.":"Lowercase letters, digits, dashes and dots.",bad:!0}:{text:`The default, lan: devices get names like ${e}.lan.`,bad:!1}}function Xo(n){let e=n.trim();return e?Ct(e)?{text:`${e} takes over when the tunnel is down.`,bad:!1}:{text:"Use an IPv4 address, or leave it empty.",bad:!0}:{text:"None: without the tunnel those devices have no DNS.",bad:!1}}function er(n){let e=n.trim();return/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(e)?{text:`Runs within an hour after ${e} (router time).`,bad:!1}:{text:"Use HH:MM, 00:00–23:59.",bad:!0}}function Zn(n,e,r,o={}){let a=0,i="",s=null;return{help:()=>{let{host:c,port:p}=n(),u=kt(c,p,o.empty??null);if(u.bad||!c.trim())return u;if(s&&s.host===c.trim())return{text:s.text,bad:s.bad};let x=o.idle?.();return{text:x?`${x} Checking where it points…`:`${u.text} Checking where it points…`,bad:!1}},schedule:()=>{let{host:c}=n(),p=kt(c,n().port,o.empty??null);p.bad||!c.trim()||c.trim()===s?.host||(clearTimeout(a),a=window.setTimeout(async()=>{let u=c.trim();i=u;try{let{id:x,port:$}=n(),h=await e(u,x,$);if(i!==u)return;s={host:u,text:h.text,bad:h.status==="error"}}catch{if(i!==u)return;s={host:u,text:p.text,bad:!1}}r()},700))}}}var ir=Ei(rr(),1),Oi=n=>``,ar="#0a0a0a",Qn="#f2f2f2",ji=n=>n.length>300,Et=n=>+n.toFixed(2);function Xn(n,e,r,o,a){return`M${Et(n+a)} ${Et(e)}h${Et(r-2*a)}a${a} ${a} 0 0 1 ${a} ${a}v${Et(o-2*a)}a${a} ${a} 0 0 1 -${a} ${a}h-${Et(r-2*a)}a${a} ${a} 0 0 1 -${a} -${a}v-${Et(o-2*a)}a${a} ${a} 0 0 1 ${a} -${a}z`}function Lt(n,e=3,r=!0,o="plain"){let a=ji(n),i=o==="night",s=(0,ir.default)(0,a?"L":"H");s.addData(n,"Byte"),s.make();let l=s.getModuleCount(),d=l+e*2,c=r&&!a?Math.round(l*.22):0;c&&(l-c)%2&&c++;let p=(l-c)/2,u=p+c,x=(w,v)=>c>0&&w>=p&&w=p&&vi&&(v<7&&w<7||v<7&&w>=l-7||v>=l-7&&w<7),h="";if(i){let w=a?.48:.42;for(let v=0;v${Oi(i?ar:"#fff")}`}let B=``:`${B}${C}`}var Ui={connect:"connections",disconnect:"connections",roam:"connections",device_added:"people",device_removed:"people",devices_removed:"people",device_changed:"people",device_keys:"people",link_changed:"people",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",expiring:"people",expired_kept:"people",portal_blocked:"problems"},Mt=["connections","people","problems"],ut={connections:"Connections",people:"People",problems:"Problems"},sr={connections:"Connects, disconnects and IP changes",people:"People and their devices added, changed, paused, removed",problems:"Blocked portal sign-ins (tunnels and services are in the service log)"},Bt=n=>Ui[n]??"problems",Ot={awg:"AmneziaWG",dawnline:"Dawnline",portal:"Portal"},Gi=["person_added","person_removed","person_changed"];function Ne(n){return n.by?n.by:Gi.includes(n.type)||n.detail==="by admin"||n.detail?.endsWith(" (admin)")?"admin":n.detail?.endsWith(" (portal)")?"portal":null}function lr(n){return(n.detail??"").replace(/ \((admin|portal)\)$/,"").replace(/^by admin$/,"")}var cn=n=>n.sys?["error","repair","down"].includes(n.sys.level):Bt(n.ev.type)==="problems";function pn(n){let e=n.keep_days>0?`${n.keep_days} day${n.keep_days===1?"":"s"}`:"no age limit",r=n.persist==="off"?"kept in memory only (lost on reboot)":`saved to flash ${n.persist==="10min"?"every 10 minutes":"hourly"}`;return`Kept for ${e}, up to ${n.max.toLocaleString("en-GB")} events, ${r}.`}function dr(n,e=120,r=26,o=je(new Date)){let a=Math.max(1,...n),i=t("div",{class:"dl-spark"});return i.style.width=`${e}px`,i.style.height=`${r}px`,n.forEach((s,l)=>{let d=t("i");d.style.height=`${Math.max(6,s/a*100)}%`,s||d.classList.add("zero");let c=n.length-1-l;me(d,()=>[t("div",{class:"dl-tip-title"},c===0?"Today":c===1?"Yesterday":wt(Ht(o,-c)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),t("div",{class:"dl-muted"},ee(s))]),i.appendChild(d)}),i}function Wi(n){let e=n==null?"":String(n);return/^[=+\-@\t\r]/.test(e)&&(e=`'${e}`),/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function cr(n,e){return[n.join(","),...e.map(r=>n.map(o=>Wi(r[o])).join(","))].join(`
-`)}function Fi(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=Fi(n),s=[...e.map(p=>({ts:p.ts,category:Bt(p.type),type:p.type,person:p.person?i.people.get(p.person)??p.pname??p.person:"",device:p.device?i.devices.get(p.device)??p.dname??p.device:"",detail:p.detail??"",where:p.where??"",by:Ne(p)??""})),...a.map(p=>({ts:p.ts,category:"system",type:`${p.src}.${p.level}`,person:"",device:"",detail:`${p.who?`${p.who} `:""}${p.msg}${p.detail?`
-${p.detail}`:""}`,where:Ot[p.src]??p.src,by:""}))].sort((p,u)=>p.ts-u.ts).map(({ts:p,...u})=>({time:new Date(p*1e3).toISOString(),...u})),l=new Date().toISOString().slice(0,10),d=`dawnline-activity${o?`-${o}`:""}-${l}.${r}`;if(r==="json"){Te(d,JSON.stringify(s,null,2),"application/json");return}Te(d,cr(["time","category","type","person","device","detail","where","by"],s),"text/csv")}var qi=[["","Everything"],["7","Older than 7 days"],["30","Older than 30 days"],["90","Older than 90 days"]],pr=n=>n?`${n} event${n===1?"":"s"} removed`:"Nothing matched";function tt(n,e,r,o,a,i=!1){let s=t("select",{class:"cbi-input-select"},[t("option",{value:""},"All categories"),...Mt.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"},qi.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()," ",H("Clear",async()=>{let d=0;if(s.value!=="system")try{d+=(await A.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 A.serviceLogClear(l.value)).removed}catch(c){ae(),U(`${s.value==="system"?"":`Activity: ${pr(d).toLowerCase()}. `}The service log was not cleared: ${be(c)}`,"error",1e4),o();return}ae(),U(pr(d),"success",3e3),o()},"negative")])}function St(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()," ",H("Reset",async()=>{await G(()=>A.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 un(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 Ki={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:""},Vi={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 Ji(n){let e={};for(let[r,o]of Object.entries(Vi))n[r]!=null&&n[r]!==""&&(e[o]=String(n[r]));return e}function Yi(n,e){let r=n.amnezia,o=r.obfuscation??{},a=d=>o[d]!=null&&o[d]!==""?String(o[d]):Ki[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"),...Ji(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: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 Zi(n){let e="";for(let r=0;r"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(Yi(n,e))),a=r?await Qi(o):null;return`vpn://${Zi(a??o)}`}var mr=[{id:"off",title:"Off",ic:"zap",stealth:0,speed:4,text:"Plain WireGuard-compatible traffic. Fastest, but easy to recognise and block.",apps:"Any WireGuard app",short:"Any WireGuard app"},{id:"balanced",title:"Balanced",ic:"shield",stealth:3,speed:4,needs:"v2",text:"AmneziaWG 2.0: junk packets, padded packets and a first packet that looks like DNS. For networks that learned to spot 1.0-style junk.",apps:"AmneziaVPN 4.8.12 or newer, AmneziaWG 2.0+ apps",short:"AmneziaWG 2.0+ apps"},{id:"max",title:"Maximum",ic:"lock",stealth:4,speed:3,needs:"v3",text:"AmneziaWG 3.1: encrypted packet headers, random tails and sizes, jittered timing, and a first packet that looks like DNS.",apps:"Apps with AmneziaWG 3.1 (current AmneziaVPN)",short:"AmneziaWG 3.1 apps"}],jt=n=>mr.find(e=>e.id===n),mn=n=>n.v3?"max":n.v2?"balanced":"off",Ut=n=>n==="standard"?"Standard (old)":n==="strong"?"Strong (old)":null,Xi={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)."},es={v2:"Needs AmneziaWG on the router.",v3:"Needs AmneziaWG 3.1 on the router: install it first."};function ur(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:rdom.content(i,mr.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"},b(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"},[ur(l.stealth,"Stealth"),ur(l.speed,"Speed")]),t("div",{class:"dl-method-foot"},d?[b(l.id==="off"?"wireguard":"amneziawg"),t("span",{},l.apps)]:[b("alert"),t("span",{},(a?Xi:es)[l.needs])])])}));return s(),i}function hr(n,e){return t("div",{class:"dl-corehead"},[t("h3",{},n),e?t("span",{class:"dl-sub"},e):""])}var fr=[["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 ts(n){let e=c=>n[c]!=null&&n[c]!=="",r=fr.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 $=fr.filter(([h])=>x.includes(h)&&e(h));return $.length?t("div",{class:"dl-pgroup"},[t("div",{class:"dl-pgroup-head"},[b(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(`
-`),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",{},[b("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(),ue(l,"Parameters copied")}},"Copy as config")]),d])}function gr(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 ns(n){let e=!1,r=t("pre",{class:"dl-conf"}),o=()=>dom.content(r,n.conf.split(`
+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;_=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>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>>_&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=0?So.getAt(To):0}}for(var _o=0,te=0;teJ*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"u"?A*4:N;var S="";S+='
",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.text=S.text||null,S.id=S.text?S.id||"qrcode-description":null,O=typeof O=="string"?{text:O}:O||{},O.text=O.text||null,O.id=O.text?O.id||"qrcode-title":null;var j=z.getModuleCount()*A+N*2,Y,J,ue,xe,te="",De;for(De="l"+A+",0 0,"+A+" -"+A+",0 0,-"+A+"z ",te+='",te},z.createDataURL=function(A,N){A=A||2,N=typeof N>"u"?A*4:N;var S=z.getModuleCount()*A+N*2,O=N,_=S-N;return R(S,S,function(j,Y){if(O<=j&&j<_&&O<=Y&&Y<_){var J=Math.floor((j-O)/A),ue=Math.floor((Y-O)/A);return z.isDark(ue,J)?0:1}else return 1})},z.createImgTag=function(A,N,S){A=A||2,N=typeof N>"u"?A*4:N;var O=z.getModuleCount()*A+N*2,_="";return _+="",_};var ne=function(A){for(var N="",S=0;S":N+=">";break;case"&":N+="&";break;case'"':N+=""";break;default:N+=O;break}}return N},pe=function(A){var N=1;A=typeof A>"u"?N*2:A;var S=z.getModuleCount()*N+A*2,O=A,_=S-A,j,Y,J,ue,xe,te={"██":"█","█ ":"▀"," █":"▄"," ":" "},De={"██":"▀","█ ":"▀"," █":" "," ":" "},Ae="";for(j=0;j=_?De[xe]:te[xe];Ae+=`
+`}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>>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<=0;)g^=y<5&&(M+=3+W-5)}for(var T=0;T=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"u")throw"bad rs block @ typeNumber:"+b+"/errorCorrectionLevel:"+H;for(var g=f.length/3,M=[],T=0;T>>7-w%8&1)==1},y.put=function(w,b){for(var H=0;H>>b-H-1&1)==1)},y.getLengthInBits=function(){return k},y.putBit=function(w){var b=Math.floor(k/8);C.length<=b&&C.push(0),w&&(C[b]|=128>>>k%8),k+=1},y},c=function(C){var k=e.MODE_NUMBER,y=C,w={};w.getMode=function(){return k},w.getLength=function(f){return y.length},w.write=function(f){for(var g=y,M=0;M+2>>8&255)*192+(T&255),f.put(T,13),M+=2}if(M>>8)},k.writeBytes=function(y,w,b){w=w||0,b=b||y.length;for(var H=0;H0&&(y+=","),y+=C[w];return y+="]",y},k},h=function(){var C=0,k=0,y=0,w="",b={},H=function(g){w+=String.fromCharCode(f(g&63))},f=function(g){if(!(g<0)){if(g<26)return 65+g;if(g<52)return 97+(g-26);if(g<62)return 48+(g-52);if(g==62)return 43;if(g==63)return 47}throw"n:"+g};return b.writeByte=function(g){for(C=C<<8|g&255,k+=8,y+=1;k>=6;)H(C>>>k-6),k-=6},b.flush=function(){if(k>0&&(H(C<<6-k),C=0,k=0),y%3!=0)for(var g=3-y%3,M=0;M=k.length){if(b==0)return-1;throw"unexpected end of file./"+b}var g=k.charAt(y);if(y+=1,g=="=")return b=0,-1;if(g.match(/^\s$/))continue;w=w<<6|f(g.charCodeAt(0)),b+=6}var M=w>>>b-8&255;return b-=8,M};var f=function(g){if(65<=g&&g<=90)return g-65;if(97<=g&&g<=122)return g-97+26;if(48<=g&&g<=57)return g-48+52;if(g==43)return 62;if(g==47)return 63;throw"c:"+g};return H},E=function(C,k){var y=C,w=k,b=new Array(C*k),H={};H.setPixel=function(T,z,W){b[z*y+T]=W},H.write=function(T){T.writeString("GIF87a"),T.writeShort(y),T.writeShort(w),T.writeByte(128),T.writeByte(0),T.writeByte(0),T.writeByte(0),T.writeByte(0),T.writeByte(0),T.writeByte(255),T.writeByte(255),T.writeByte(255),T.writeString(","),T.writeShort(0),T.writeShort(0),T.writeShort(y),T.writeShort(w),T.writeByte(0);var z=2,W=g(z);T.writeByte(z);for(var q=0;W.length-q>255;)T.writeByte(255),T.writeBytes(W,q,255),q+=255;T.writeByte(W.length-q),T.writeBytes(W,q,W.length-q),T.writeByte(0),T.writeString(";")};var f=function(T){var z=T,W=0,q=0,Z={};return Z.write=function(I,V){if(I>>>V)throw"length over";for(;W+V>=8;)z.writeByte(255&(I<>>=8-W,q=0,W=0;q=I<0&&z.writeByte(q)},Z},g=function(T){for(var z=1<>6,128|i&63):i<55296||i>=57344?o.push(224|i>>12,128|i>>6&63,128|i&63):(a++,i=65536+((i&1023)<<10|r.charCodeAt(a)&1023),o.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}return o}return e(n)}})();(function(n){typeof define=="function"&&define.amd?define([],n):typeof Uo=="object"&&(Go.exports=n())})(function(){return jo})});function Wn(n,e){return n==null||n===!1||n===""||(Array.isArray(n)?n.forEach(r=>Wn(r,e)):e.push(n instanceof Node?n:String(n))),e}function t(n,e,r){let o=window.E,a=e!=null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Node);return!a&&r===void 0?o(n,{},Wn(e,[])):o(n,a?e:{},Wn(r,[]))}var Do={phone:'',computer:'',tablet:'',router:'',server:'',other:'',ethernet:'',bridge:'',wifi:'',tunnel:'',plus:'',chart:'',reset:'',package:'',code:'',plug:'',sunrise:'',refresh:'',archive:'',qr:'',copy:'',download:'',link:'',amnezia:'',amneziawg:'',wireguard:'',appstore:'',googleplay:'',github:'',openwrt:'',apple:'',windows:'',linux:'',eye:'',share:'',arrow:'',trash:'',edit:'',pause:'',play:'',key:'',out:'',admin:'',shield:'',shieldplus:'',lock:'',zap:'',check:'',alert:'',x:'',globe:'',home:'',open:'',file:'',network:'',moon:'',chevron:'',clock:'',calendar:'',minus:'',more:'',pin:'',activity:''};function ft(n,e="dl-icon"){let r=Do[n]??Do.phone;return``}function v(n,e="dl-icon"){let r=document.createElement("span");return r.className="dl-icon-wrap",r.innerHTML=ft(n,e),r}function U(n,e="info",r=0){let o=document.querySelector(".dl-toasts");o||(o=t("div",{class:"dl-toasts dl-root",role:"status","aria-live":"polite"}),document.body.appendChild(o));let a=e==="error"?"x":e==="warning"?"alert":e==="success"?"check":null,i=()=>{s.classList.remove("show"),setTimeout(()=>s.remove(),200)},s=t("div",{class:`dl-toast ${e}`},[a?v(a):"",t("span",{},n),e==="error"?t("button",{type:"button","aria-label":"Close",click:i},v("x")):""]);o.appendChild(s),requestAnimationFrame(()=>s.classList.add("show")),setTimeout(i,r||(e==="error"?8e3:e==="warning"?5e3:2600))}function be(n){return n instanceof Error?n.message:String(n)}async function G(n,e){try{let r=await n();return e&&U(e,"success",3500),r}catch(r){U(be(r),"error",1e4);return}}function Ao(n){try{let e=n();e&&typeof e.then=="function"&&e.catch(r=>U(be(r),"error"))}catch(e){U(be(e),"error")}}function Ho(n){if(n&&typeof n=="object"){if(typeof n.error=="string")throw new Error(n.error);typeof n.warning=="string"&&n.warning&&U(n.warning,"warning",12e3)}return n}function K(n,e=[]){let r=rpc.declare({object:"luci.dawnline",method:n,params:e});return async(...o)=>Ho(await r(...o))}var Ei=K("logs_clear",["person","device","category","older_days"]),Li=(n={})=>Ei(n.person??"",n.device??"",n.category??"",n.older_days??""),Mi=rpc.declare({object:"luci.dawnline",method:"person_update",params:["id","name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode","paused","services","circle","home_nets","server"]});async function Si(n,e){let o=[n,...["name","access","device_limit","expires","expire_action","expire_warn","quota_gb","quota_period","bonus_gb","hours","note","dns_mode"].map(a=>e[a]),e.paused,e.services,e.circle,e.home_nets,e.server];return Ho(await Mi(...o))}var Ti=K("status",["days"]),P={rev:K("rev"),personUpdate:Si,settingsGet:K("settings_get"),portalInfo:K("portal_info"),settingsUpdate:K("settings_update",["values"]),serviceSet:K("service_set",["id","name","address","ports"]),serviceDelete:K("service_delete",["id"]),geoClear:K("geo_clear"),events:K("events",["limit","person","since"]),logsClear:Li,interfaces:K("interfaces",["id"]),serverInterfaces:K("server_interfaces",["id","auto_wan","wan_device","auto_lan","lan_devices","lan_like","device_mesh","mesh"]),circleSet:K("circle_set",["id","server","name","color","members"]),circleDelete:K("circle_delete",["id"]),accessCheck:K("access_check",["from","to"]),homeHosts:K("home_hosts",["id"]),usageClear:K("usage_clear",["scope","id"]),uninstall:K("uninstall",["confirm"]),status:Ti,setupDefaults:K("setup_defaults"),serverCreate:K("server_create",["id","name","ifname","port","subnet","endpoint","mtu","preset","lan_zone","wan_zone","lan_like","portal_enabled","portal_port"]),serverObfuscation:K("server_obfuscation",["id","preset"]),serverUpdate:K("server_update",["id","values"]),serverPorts:K("server_ports",["id"]),endpointProbe:K("endpoint_probe",["host","id","port"]),serverDelete:K("server_delete",["id"]),personLinks:K("person_links",["id"]),personCreate:K("person_create",["name","slug","server","access","device_limit","expires","quota_gb","quota_period"]),personPause:K("person_pause",["id","paused"]),personRegen:K("person_regen",["id","remove"]),personDelete:K("person_delete",["id"]),personUsage:K("person_usage",["id","days"]),deviceCreate:K("device_create",["person","name","kind"]),deviceConfig:K("device_config",["id"]),deviceUpdate:K("device_update",["id","name","disabled"]),deviceDelete:K("device_delete",["id"]),deviceRotate:K("device_rotate",["id"]),apply:K("apply"),health:K("health"),healthFix:K("health_fix",["id"]),serviceLog:K("service_log"),serviceLogClear:K("service_log_clear",["older_days"]),backupList:K("backup_list"),backupCreate:K("backup_create"),backupRestore:K("backup_restore",["name"]),backupDelete:K("backup_delete",["name"]),backupRead:K("backup_read",["name"]),backupUpload:K("backup_upload",["data"]),exportJson:K("export"),importJson:K("import",["data"]),updatesStatus:K("updates_status"),updatesRun:K("updates_run",["what"]),updatesReleases:K("updates_releases",["page"]),updatesNotes:K("updates_notes",["component","tag","build"]),updatesChanges:K("updates_changes",["from","to"])};function D(n,e,r="neutral",o={}){let{disabled:a,...i}=o,s=t("button",{class:`cbi-button cbi-button-${r}`,type:"button",...i,click:async l=>{if(l.preventDefault(),l.stopPropagation(),!s.disabled){s.disabled=!0,s.classList.add("spinning");try{await e(l)}catch(d){U(be(d),"error")}finally{s.disabled=!1,s.classList.remove("spinning")}}}},n);return s.disabled=!!a,s}function Le(n,e,r,o="neutral",a=""){return D([v(n),t("span",{class:"dl-btn-label"},e)],r,o,{title:e,class:`cbi-button cbi-button-${o} dl-icon-btn ${a}`.trim()})}function $e(n){return document.addEventListener("luci-navigate",n),()=>document.removeEventListener("luci-navigate",n)}var gt=null;function Fn(n=!1){let e=gt;gt=null,e?.(n)}function oe(n,e,r,o=""){Fn();let a=t("div",{class:`dl-modal ${o}`},e),i=t("div",{class:"button-row"},r);a.addEventListener("keydown",s=>{if(s.key==="Escape"){s.preventDefault(),s.stopPropagation(),ae();return}if(s.key!=="Enter"||s.shiftKey||s.ctrlKey||s.metaKey||s.altKey)return;let l=s.target;if(!l||["TEXTAREA","BUTTON","SELECT","A"].includes(l.tagName))return;let d=i.querySelector(".cbi-button-positive");!d||d.disabled||(s.preventDefault(),d.click())}),ui.showModal(n,[a,i])}function ae(){Fn(),ui.hideModal()}function ie(n="Cancel",e=!1){return t("button",{class:`cbi-button ${e?"cbi-button-negative":"cbi-button-neutral"}`,type:"button",click:ae},n)}function se(n,e,r="Confirm",o=!1){return new Promise(a=>{oe(n,e,[ie()," ",t("button",{class:`cbi-button ${o?"cbi-button-negative":"cbi-button-positive"}`,type:"button",click:()=>{let i=gt;gt=null,ui.hideModal(),i?.(!0)}},r)]),gt=a})}$e(()=>{gt&&(Fn(),ui.hideModal())});async function me(n,e="Copied to clipboard",r=!1){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(n);else{let o=t("textarea",{style:"position:fixed;opacity:0"},n);document.body.appendChild(o),o.select();let a=document.execCommand("copy");if(o.remove(),!a)throw new Error("Copying is blocked here. Select the text and copy it by hand.")}return U(e,"success",2500),!0}catch(o){return r||U(be(o),"error"),!1}}function Te(n,e,r="text/plain"){let o=globalThis,a=typeof e=="string"?new o.Blob([e],{type:r}):e,i=URL.createObjectURL(a),s=t("a",{href:i,download:n,style:"display:none"});document.body.appendChild(s),s.click(),setTimeout(()=>{URL.revokeObjectURL(i),s.remove()},1e3)}function qn(n,e){return new Promise(r=>{let o=t("input",{type:"file",accept:n,style:"display:none"});o.addEventListener("cancel",()=>{o.remove(),r(null)}),o.addEventListener("change",()=>{let a=o.files?.[0];if(o.remove(),!a)return r(null);let i=new FileReader;i.onload=()=>{let s=String(i.result??"");r({name:a.name,data:e==="base64"?s.replace(/^data:[^,]*,/,""):s})},i.onerror=()=>r(null),e==="base64"?i.readAsDataURL(a):i.readAsText(a)}),document.body.appendChild(o),o.click()})}function Ce(n,e){let r=document.querySelector(".dl-dd");if(r&&(r.dlClose?r.dlClose():r.remove(),r.dlAnchor===n))return;let o=t("div",{class:"dl-dd dl-root",role:"menu"},e.map(u=>u?t("button",{type:"button",role:"menuitem",class:u.danger?"danger":u.warn?"warn":"",click:()=>{p(),Ao(u.run)}},[u.icon??"",t("span",{},u.label)]):t("hr")));document.body.appendChild(o);let a=n.getBoundingClientRect(),i=o.offsetWidth,s=o.offsetHeight;o.style.top=`${a.bottom+6+s>window.innerHeight-8&&a.top-6-s>8?a.top-6-s:a.bottom+6}px`,o.style.left=`${Math.max(8,Math.min(a.right-i,window.innerWidth-i-8))}px`;let l=u=>{!o.contains(u.target)&&!n.contains(u.target)&&p()},d=u=>{if(u.key==="Escape"||u.key==="Tab")return p();let x=[...o.querySelectorAll("button:not([disabled])")];if(!x.length||!["ArrowDown","ArrowUp","Home","End"].includes(u.key))return;u.preventDefault();let $=x.indexOf(document.activeElement),h=u.key==="Home"?0:u.key==="End"?x.length-1:u.key==="ArrowDown"?($+1)%x.length:($-1+x.length)%x.length;x[h].focus({preventScroll:!0})},c=$e(p);o.dlAnchor=n,o.dlClose=p;function p(){o.remove(),c(),document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",d,!0),window.removeEventListener("scroll",p,!0)}setTimeout(()=>{document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",d,!0),window.addEventListener("scroll",p,!0)}),o.querySelector("button")?.focus({preventScroll:!0})}var lt=null,Je=null,Kn=0;function vt(){lt&&(lt.style.display="none"),Je=null,clearInterval(Kn),Kn=0}function he(n,e){let r=o=>{lt??(lt=document.body.appendChild(t("div",{class:"dl-tip dl-tip-float dl-root"}))),lt.replaceChildren(...e().map(a=>typeof a=="string"?document.createTextNode(a):a)),lt.style.display="",lt.style.left=`${o.clientX}px`,lt.style.top=`${o.clientY-10}px`,Je=n,Kn||(Kn=window.setInterval(()=>{(!Je?.isConnected||!Je.getClientRects().length)&&vt()},400))};n.addEventListener("mouseenter",r),n.addEventListener("mousemove",r),n.addEventListener("mouseleave",vt),n.addEventListener("pointerup",o=>{o.pointerType!=="mouse"&&(Je===n?vt():r(o))})}$e(vt);window.addEventListener("scroll",()=>Je&&vt(),{capture:!0,passive:!0});document.addEventListener("pointerdown",n=>{Je&&!Je.contains(n.target)&&vt()},!0);function X(n){if(!n||n<0)return"0 B";let e=["B","KB","MB","GB","TB"],r=0,o=n;for(;o>=1024&&r=100||r===0?Math.round(o):o.toFixed(1)} ${e[r]}`}function Oe(n){let e=n*8;return e<1e3?`${Math.round(e)} bit/s`:e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)} kbit/s`:e<1e9?`${(e/1e6).toFixed(e<1e7?1:0)} Mbit/s`:`${(e/1e9).toFixed(1)} Gbit/s`}function re(n,e=Date.now()/1e3){if(!n)return"never";let r=Math.max(0,Math.round(e-n));return r<60?"just now":r<3600?`${Math.floor(r/60)} min ago`:r<86400?`${Math.floor(r/3600)} h ago`:r<86400*30?`${Math.floor(r/86400)} d ago`:new Date(n*1e3).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function xt(n){if(!n||n<0)return"—";let e=Math.floor(n/86400),r=Math.floor(n%86400/3600),o=Math.floor(n%3600/60);return e?`${e}d ${r}h`:r?`${r}h ${o}m`:`${o}m`}function Ht(n){let e=new Date(n*1e3),r=new Date,o=e.toDateString()===r.toDateString(),a=e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});return o?a:`${e.toLocaleDateString("en-GB",{day:"numeric",month:"short"})} ${a}`}function je(n){return`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`}function wt(n){let[e,r,o]=n.split("-").map(Number);return new Date(e,(r||1)-1,o||1,12)}function Ue(n){return(typeof n=="string"?/^\d{4}-\d{2}-\d{2}$/.test(n)?wt(n):new Date(n):n).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}function Me(n){return n?Ue(n):""}function Vn(n,e){let r=o=>{let[a,i,s]=o.split("-").map(Number);return Date.UTC(a,i-1,s)};return Math.round((r(n)-r(e))/864e5)}function At(n,e){let r=wt(n);return r.setDate(r.getDate()+e),je(r)}function bt(n,e){let[r,o,a]=n.split("-").map(Number),i=new Date(r,o-1+e,1,12),s=new Date(i.getFullYear(),i.getMonth()+1,0).getDate();return i.setDate(Math.min(a,s)),je(i)}function Ie(n){return n?.length?n[n.length-1].day:je(new Date)}function zo(n,e,r,o,a=30){let i=n||o;return e==="day"?At(i,r):e==="week"?At(i,7*r):e==="month"?bt(i,r):e==="year"?bt(i,12*r):At(i,a*r)}function Ye(n,e=Date.now()){if(!n)return null;let r=typeof e=="number"?je(new Date(e)):e,o=Vn(n,r);return o>=0?o+1:o}function Ze(n,e){return e!=null&&e>0&&n.expire_warn>0&&e<=n.expire_warn}function Xt(n){return n<=1?"ends today":n===2?"ends tomorrow":`ends in ${n} days`}function en(n,e,r=`${e}s`){return`${n.toLocaleString("en-GB")} ${n===1?e:r}`}function zt(n){return n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(n<10240?1:0)} KB`:`${(n/1048576).toFixed(1)} MB`}var dt={lan:"Home network",internet:"Internet",both:"Home network + Internet"};var No=["computer","phone","tablet","router","other"],Qe={computer:"PC",phone:"Phone",tablet:"Tablet",router:"Router",other:"Other"},Ro={active:"Active",paused:"Paused",expired:"Expired",quota:"Data limit reached",hours:"Outside allowed hours",no_server:"No server",server_off:"Server is turned off"};function He(n){let e=n.trim().split(/\s+/).filter(Boolean);if(!e.length)return"?";let r=e[0][0]??"",o=e.length>1?e[e.length-1][0]??"":e[0][1]??"";return(r+o).toUpperCase()}function tn(n){let e=r=>r.disabled?3:r.online?0:r.handshake?1:2;return n.map((r,o)=>[r,o]).sort((r,o)=>e(r[0])-e(o[0])||r[1]-o[1]).map(([r])=>r)}function Ee(n,e,r){return t("span",{class:`dl-pill ${n}`,title:r??null},e)}function _i(n){return n.state==="active"?"ok":n.state==="quota"||n.state==="expired"?"bad":"warn"}function Pi(n){return n.state==="server_off"&&n.paused?"paused":n.state}function Io(n){let e=Pi(n);return e==="active"||e==="server_off"?"":Ee(_i({...n,state:e}),Ro[e])}function Bo(n){let e=n.access==="both"?["lan","inet"]:n.access==="lan"?["lan"]:["inet"],r=t("span",{class:"dl-access","aria-label":dt[n.access]},e.map(o=>t("span",{class:`dl-ibadge ${o}`},v(o==="lan"?"home":"globe"))));return he(r,()=>[t("div",{class:"dl-tip-title"},dt[n.access]),n.access==="lan"&&n.services?.length?t("div",{class:"dl-muted"},`${n.services.length} home service${n.services.length===1?"":"s"} only`):""]),r}var Di={paused:"Paused",expired:"Access ended",quota:"Data limit",hours:"Outside hours",server_off:"Server off",no_server:"No server"};function nn(n,e,r="Not set up yet",o){let a=n.handshake?`Last seen ${re(n.handshake,e)} · ${new Date(n.handshake*1e3).toLocaleString()}`:"";if(n.disabled)return t("span",{class:"dl-dstat",title:a},"Disabled");if(n.online)return t("span",{class:"dl-dstat ok"},"Connected");let i=o&&Di[o.state];return i?t("span",{class:"dl-dstat warn",title:a||"Not connected yet"},i):n.handshake?t("span",{class:"dl-dstat",title:new Date(n.handshake*1e3).toLocaleString()},`Last seen ${re(n.handshake,e)}`):t("span",{class:"dl-dstat warn",title:"Waiting for the first connection"},r)}var on=null;function Oo(n,e,r,o){on?.close();let a=t("aside",{class:"dl-drawer",role:"dialog","aria-modal":"true"},[t("div",{class:"dl-drawer-head"},[n,t("button",{type:"button",class:"dl-drawer-x","aria-label":"Close",click:()=>c()},v("x"))]),t("div",{class:"dl-drawer-body"},e),r?t("div",{class:"dl-drawer-foot"},r):""]),i=t("div",{class:"dl-drawer-overlay dl-root",click:u=>{u.target===i&&c()}},a),s=u=>{u.key==="Escape"&&!document.body.classList.contains("modal-overlay-active")&&c()},l=!1,d=$e(()=>c());function c(){l||(l=!0,d(),document.removeEventListener("keydown",s),i.classList.remove("open"),setTimeout(()=>i.remove(),220),on===p&&(on=null),o())}let p={close:c,panel:a};return document.addEventListener("keydown",s),document.body.appendChild(i),requestAnimationFrame(()=>i.classList.add("open")),on=p,p}function ce(n,e,r){return t("div",{class:"dl-setrow"},[t("div",{class:"dl-stack"},[t("span",{class:"dl-setrow-label"},n),r?t("span",{class:"dl-sub"},r):""]),t("div",{class:"dl-setrow-ctl"},e)])}function ge(n,e,r,o=e){let a=ce(n,o," "),i=a.querySelector(".dl-sub"),s=()=>{let l=r();i.textContent=l.text,i.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",s),a.refresh=s,a.help=r,s(),a}function ye(n,e,r,o=e){let a=t("div",{class:"dl-sub"}),i=t("div",{class:"cbi-value dl-live"},[t("div",{class:"cbi-value-title"},[t("label",{},n),a]),t("div",{class:"cbi-value-field"},o)]),s=()=>{let l=r();a.textContent=l.text,a.classList.toggle("bad",l.bad),e.classList.toggle("cbi-input-invalid",l.bad)};return e.addEventListener("input",s),e.addEventListener("change",s),i.refresh=s,i.help=r,s(),i}function ze(n,e=[]){for(let r of n){let o=r.help?.();if(o?.bad)return o.text}for(let r of e){let o=r();if(o.bad)return o.text}return null}function Nt(n,e,r,o=""){return t("section",{class:`dl-setsec ${o}`},[t("div",{class:"dl-setsec-body"},[n?t("h3",{},n):"",...e]),r.length?t("div",{class:"dl-setsec-foot"},r):""])}function fe(n,e,r,o){return t("div",{class:"dl-group"},[t("div",{class:"dl-group-head"},[t("span",{class:"dl-group-ic"},v(n)),t("span",{class:"dl-stack"},[t("b",{},e),r?t("span",{class:"dl-sub"},r):""])]),t("div",{class:"dl-group-body"},o.filter(a=>a!==""))])}function Xe(n,e,r,o,a){return t("div",{class:`dl-row dl-need-row ${e}`},[e?t("span",{class:"dl-need-ic"},v(n)):v(n),t("span",{class:"dl-row-main dl-stack"},[t("b",{},r),t("span",{class:"dl-sub"},o)]),a])}function ct(n,e){let r={ok:"success",warn:"warning",error:"error",info:"notice"}[n];return t("div",{class:`alert-message ${r}`},e)}function yt(n,e=""){let r=t("div",{class:e});return r.innerHTML=n,r}var qo=Ci(Wo(),1),Ai=n=>``,Fo="#0a0a0a",Hi="#f2f2f2",zi={night:[Fo,Hi],day:["#ffffff",Fo]},Ni=n=>n.length>300,kt=n=>+n.toFixed(2);function Jn(n,e,r,o,a){return`M${kt(n+a)} ${kt(e)}h${kt(r-2*a)}a${a} ${a} 0 0 1 ${a} ${a}v${kt(o-2*a)}a${a} ${a} 0 0 1 -${a} ${a}h-${kt(r-2*a)}a${a} ${a} 0 0 1 -${a} -${a}v-${kt(o-2*a)}a${a} ${a} 0 0 1 ${a} -${a}z`}function rn(n,e=3,r=!0,o="plain"){let a=Ni(n),i=o!=="plain",[s,l]=i?zi[o]:["#fff","#000"],d=(0,qo.default)(0,a?"L":"H");d.addData(n,"Byte"),d.make();let c=d.getModuleCount(),p=c+e*2,u=r&&!a?Math.round(c*.22):0;u&&(c-u)%2&&u++;let x=(c-u)/2,$=x+u,h=(y,w)=>u>0&&y>=x&&y<$&&w>=x&&w<$,m=(y,w)=>i&&(w<7&&y<7||w<7&&y>=c-7||w>=c-7&&y<7),E="";if(i){let y=a?.48:.42;for(let w=0;w${Ai(i?s:"#fff")}`}let k=``:`${k}${C}`}function pt(){let n=document.documentElement.getAttribute("data-darkmode");return n!=null?n==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}function an(n){let e=pt();return yt(rn(n,3,!0,e?"night":"day"),`dl-qr${e?"":" light"}`)}function Yn(n){let e=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/.exec(n.trim());if(!e)return null;let[r,o,a,i]=e.slice(1,5).map(Number),s=Number(e[5]);if([r,o,a,i].some(c=>c>255)||s<8||s>30)return null;let l=r*2**24+o*2**16+a*2**8+i,d=2**(32-s);return{net:l-l%d,size:d}}var Ri=(n,e)=>n.netYn(n));function Ct(n){return n.split("/")[0].split(".").slice(0,3).join(".")}function ln(n){return`${n.trim()}.0/24`}function Qn(n,e,r){let o=n.trim(),a=/^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(o)?Yn(ln(o)):null;if(!a)return{text:"Three numbers, like 10.77.0.",bad:!0};if(!Ii.some(s=>a.net>=s.net&&a.net+a.size<=s.net+s.size))return{text:"Use a private range: 10.x.x, 172.16–31.x or 192.168.x.",bad:!0};let i=e.find(s=>{let l=Yn(s.cidr);return l!=null&&Ri(a,l)});if(i){let s=i.cidr.endsWith("/24")?`${Ct(i.cidr)}.x`:i.cidr,l=r&&r!==o?` Try ${r}.`:"";return{text:`${i.name} already uses ${s}.${l}`,bad:!0}}return{text:`Devices get ${o}.2 – ${o}.254, the router ${o}.1.`,bad:!1}}var Vo=(n,e)=>e.find(r=>r.from<=n&&n<=r.to)?.who??null,Bi=n=>Number.isInteger(n)&&n>=1&&n<=65535;function Rt(n,e,r){if(!Bi(n))return{text:"Use a port from 1 to 65535.",bad:!0};let o=Vo(n,e);return o?{text:`Used by ${o}. Choose another port.`,bad:!0}:{text:r,bad:!1}}function dn(n,e,r){let o=r?`HTTPS here, plain HTTP for links on IP addresses on ${n+1}.`:"HTTPS on this port, opened on WAN.",a=Rt(n,e,o);if(a.bad||!r)return a;if(n===65535)return{text:"Links on IP addresses also need the next port: choose a lower one.",bad:!0};let i=Vo(n+1,e);return i?{text:`Links on IP addresses also need ${n+1}, used by ${i}. Choose another port.`,bad:!0}:a}var sn=n=>Array.from(n).length,Ko=48,Oi=/[<>"\\\u0000-\u001f\u007f]/;function _e(n,e=[],r=""){let o=n.trim();return o?sn(n)>Ko?{text:`Up to ${Ko} characters (${sn(n)} now).`,bad:!0}:Oi.test(n)?{text:'Names can’t contain < > " or \\.',bad:!0}:e.some(a=>a.toLowerCase()===o.toLowerCase())?{text:`“${o}” already exists — pick another name.`,bad:!0}:{text:r,bad:!1}:{text:"Enter a name.",bad:!0}}function Jo(n,e=[]){return sn(n)>32?{text:`Up to 32 characters (${sn(n)} now).`,bad:!0}:_e(n,e,"Shown on the person cards.")}var ji=/^[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])?)*$/,Ui=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;function Et(n){let e=Ui.exec(n);return!!e&&e.slice(1).every(r=>Number(r)<=255)}function Zn(n){return/^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/.test(n)&&!/:::/.test(n)}function $t(n,e,r=null){let o=n.trim();if(!o)return r!=null?{text:r,bad:!1}:{text:"Enter a hostname or IP address.",bad:!0};if(/^[a-z]+:\/\//i.test(o))return{text:"Leave out https:// — just the name.",bad:!0};if(/\/.*/.test(o))return{text:"Just the name, without a path.",bad:!0};if(/^[^:\[]+:\d+$/.test(o))return{text:"Just the name, without a port (the port is on AmneziaWG).",bad:!0};if(/\s/.test(o))return{text:"A hostname has no spaces.",bad:!0};if(o.length>253||!(ji.test(o)||Et(o)||Zn(o)))return{text:"Use a hostname or an IP address.",bad:!0};let a=Zn(o)?`[${o}]`:o;return{text:e?`Devices connect to ${a}:${e}.`:`Links use ${a}.`,bad:!1}}function Yo(n,e){let r=n.split(/[ ,]+/).filter(Boolean);if(!r.length)return{text:`This router (${e}): queries go where your home network sends them, and home names work.`,bad:!1};let o=r.find(a=>!Et(a)&&!Zn(a));return o?{text:`“${o}” is not an IP address. Separate several with commas.`,bad:!0}:{text:`Devices use ${r.join(" and ")} — home names and your LAN’s DNS filters no longer apply to them.`,bad:!1}}function Zo(n,e){let r=n.trim();if(!r)return{text:`Automatic by device type and disguise: ${e.computer} for computers and routers, ${e.phone} for phones and tablets.`,bad:!1};if(!/^\d{1,4}$/.test(r)||Number(r)<1280||Number(r)>1500)return{text:"MTU must be 1280–1500, or empty for automatic.",bad:!0};let o=Number(r);return{text:`Computers and routers get ${o}, phones and tablets ${Math.min(o,1280)}.`,bad:!1}}function Qo(n){let e=n.trim();return e?!/^\d{1,3}$/.test(e)||Number(e)>600?{text:"Use 0–600 seconds.",bad:!0}:Number(e)===0?{text:"Off: NAT may close the tunnel when idle, and “Connected” lags.",bad:!1}:{text:`Devices send a packet every ${e} s to keep NAT open (a little battery on phones).`,bad:!1}:{text:"Default: a packet every 25 s keeps NAT open and “Connected” accurate.",bad:!1}}function cn(n,e=0){let r=n.trim();if(!/^\d{1,2}$/.test(r)||Number(r)<1||Number(r)>32)return{text:"Use 1–32.",bad:!0};let o=Number(r);return e>o?{text:`Already has ${e} devices: remove ${e-o===1?"one":`${e-o}`} first, or allow more.`,bad:!0}:{text:`They can add ${o} device${o===1?"":"s"} themselves.`,bad:!1}}function pn(n,e=!0){let r=n.trim();if(!r)return{text:"Optional. No data limit.",bad:!1};let o=Number(r);return!/^\d+(\.\d+)?$/.test(r)||o<0||o>1e5?{text:"A number of GB, up to 100000.",bad:!0}:o===0?{text:"Optional. No data limit.",bad:!1}:{text:e?`Paused after ${r} GB this month, resumed on the 1st.`:`Paused after ${r} GB in total.`,bad:!1}}function Xo(n,e,r,o){let a=n.trim();if(!a)return{text:"Optional. No end date.",bad:!1};let i=r(a,e);return i==null?{text:"Use a date.",bad:!0}:i<0?{text:"That date has passed: access would end at once.",bad:!0}:{text:i===1?`Access ends today (${o(a)}).`:`Access ends in ${i} days (${o(a)}).`,bad:!1}}function er(n,e=null){let r=n.trim();return r?Et(r)?e&&!e(r)?{text:`${r} is not in any home network of this server: nobody would reach it.`,bad:!1}:{text:"",bad:!1}:{text:"Use an IPv4 address, like 192.168.1.10.",bad:!0}:{text:"The device’s address at home.",bad:!0}}function tr(n){let e=n.split(/[ ,]+/).filter(Boolean);if(!e.length)return{text:"All ports.",bad:!1};let r=e.find(o=>!/^\d{1,5}$/.test(o)||Number(o)<1||Number(o)>65535);return r?{text:`“${r}” is not a port (1–65535).`,bad:!0}:{text:`Port${e.length===1?"":"s"} ${e.join(", ")}.`,bad:!1}}function nr(n){let e=n.trim();return e?/^https?:\/\//i.test(e)?e.length>300||!/^https?:\/\/[A-Za-z0-9.-]+(:[0-9]+)?(\/[^\s"'<>]*)?$/.test(e)?{text:"Not a usable address (no spaces or quotes).",bad:!0}:{text:"Wrong links are sent there instead of a “Not found”.",bad:!1}:{text:"Must start with http:// or https://.",bad:!0}:{text:"Wrong links get a bare “Not found”.",bad:!1}}function or(n,e="phone.myata"){let r=n.trim();return r?/^[a-z0-9-]{1,32}(\.[a-z0-9-]{1,32})*$/.test(r)?{text:`Devices get names like ${e}.${r}.`,bad:!1}:{text:/[A-Z]/.test(r)?"Lowercase only.":"Lowercase letters, digits, dashes and dots.",bad:!0}:{text:`The default, lan: devices get names like ${e}.lan.`,bad:!1}}function rr(n){let e=n.trim();return e?Et(e)?{text:`${e} takes over when the tunnel is down.`,bad:!1}:{text:"Use an IPv4 address, or leave it empty.",bad:!0}:{text:"None: without the tunnel those devices have no DNS.",bad:!1}}function ar(n){let e=n.trim();return/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(e)?{text:`Runs within an hour after ${e} (router time).`,bad:!1}:{text:"Use HH:MM, 00:00–23:59.",bad:!0}}function Xn(n,e,r,o={}){let a=0,i="",s=null;return{help:()=>{let{host:c,port:p}=n(),u=$t(c,p,o.empty??null);if(u.bad||!c.trim())return u;if(s&&s.host===c.trim())return{text:s.text,bad:s.bad};let x=o.idle?.();return{text:x?`${x} Checking where it points…`:`${u.text} Checking where it points…`,bad:!1}},schedule:()=>{let{host:c}=n(),p=$t(c,n().port,o.empty??null);p.bad||!c.trim()||c.trim()===s?.host||(clearTimeout(a),a=window.setTimeout(async()=>{let u=c.trim();i=u;try{let{id:x,port:$}=n(),h=await e(u,x,$);if(i!==u)return;s={host:u,text:h.text,bad:h.status==="error"}}catch{if(i!==u)return;s={host:u,text:p.text,bad:!1}}r()},700))}}}var Gi={connect:"connections",disconnect:"connections",roam:"connections",device_added:"people",device_removed:"people",devices_removed:"people",device_changed:"people",device_keys:"people",link_changed:"people",person_added:"people",person_removed:"people",person_changed:"people",paused:"people",resumed:"people",expiring:"people",expired_kept:"people",portal_blocked:"problems"},Lt=["connections","people","problems"],ut={connections:"Connections",people:"People",problems:"Problems"},ir={connections:"Connects, disconnects and IP changes",people:"People and their devices added, changed, paused, removed",problems:"Blocked portal sign-ins (tunnels and services are in the service log)"},It=n=>Gi[n]??"problems",Bt={awg:"AmneziaWG",dawnline:"Dawnline",portal:"Portal"},Wi=["person_added","person_removed","person_changed"];function Ne(n){return n.by?n.by:Wi.includes(n.type)||n.detail==="by admin"||n.detail?.endsWith(" (admin)")?"admin":n.detail?.endsWith(" (portal)")?"portal":null}function sr(n){return(n.detail??"").replace(/ \((admin|portal)\)$/,"").replace(/^by admin$/,"")}var un=n=>n.sys?["error","repair","down"].includes(n.sys.level):It(n.ev.type)==="problems";function mn(n){let e=n.keep_days>0?`${n.keep_days} day${n.keep_days===1?"":"s"}`:"no age limit",r=n.persist==="off"?"kept in memory only (lost on reboot)":`saved to flash ${n.persist==="10min"?"every 10 minutes":"hourly"}`;return`Kept for ${e}, up to ${n.max.toLocaleString("en-GB")} events, ${r}.`}function lr(n,e=120,r=26,o=je(new Date)){let a=Math.max(1,...n),i=t("div",{class:"dl-spark"});return i.style.width=`${e}px`,i.style.height=`${r}px`,n.forEach((s,l)=>{let d=t("i");d.style.height=`${Math.max(6,s/a*100)}%`,s||d.classList.add("zero");let c=n.length-1-l;he(d,()=>[t("div",{class:"dl-tip-title"},c===0?"Today":c===1?"Yesterday":wt(At(o,-c)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})),t("div",{class:"dl-muted"},X(s))]),i.appendChild(d)}),i}function Fi(n){let e=n==null?"":String(n);return/^[=+\-@\t\r]/.test(e)&&(e=`'${e}`),/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function dr(n,e){return[n.join(","),...e.map(r=>n.map(o=>Fi(r[o])).join(","))].join(`
+`)}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: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: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"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:rdom.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(`
+`),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?[`
-`,gr(s,e)]:[gr(s,e)])),a=t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),e=!e,dom.content(a,[b(e?"x":"key"),e?"Hide key":"Show key"]),o()}},[b("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 · import it in the app`)]),H([b("download")," Download"],()=>Te(n.filename,n.conf,"application/octet-stream"),"positive")]),t("details",{class:"dl-params"},[t("summary",{},[b("chevron"),t("span",{},"Configuration"),t("span",{class:"dl-spacer"}),a,t("button",{type:"button",class:"dl-chipbtn",click:s=>{s.preventDefault(),ue(n.conf,"Configuration copied")}},[b("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 os(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"},[et(Lt(n.conf),"dl-qr"),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),H("Copy",()=>ue(r,"Key copied"))]),t("span",{class:"dl-sub"},"AmneziaVPN → Add server → Insert key. Keep it private.")]),file:()=>ns(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 rs(n,e,r,o){let a=jt(r),s=n.st.people.filter(d=>d.server===e.id).reduce((d,c)=>d+c.devices.length,0);await le(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(()=>A.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 as(n,e){let r=n.st,o=se(String(e.port),{inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),a=se(e.mtu?String(e.mtu):"",{placeholder:"Auto",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),i=se(String(e.keepalive??""),{placeholder:"25",inputmode:"numeric",class:"cbi-input-text dl-w-port dl-mono"}),s=jt(e.preset)?e.preset:void 0,l=s??mn(r.awg),d=H("",()=>rs(n,e,l,l===s),"neutral"),c=()=>dom.content(d,l===s?[b("reset")," Generate new values"]:[`Switch to ${jt(l).title}`]);c();let p=r.awg_state?.tools!==!1,u=[],x=he("UDP port",o,()=>It(Number(o.value),u,`Opened on the WAN firewall automatically.${Number(o.value)===4500?" 4500 is IPsec’s port: most networks let it through.":""}`));A.serverPorts(e.id).then(m=>{u=m.udp_taken??[],x.refresh()}).catch(()=>{});let $=he("MTU",a,()=>Fo(a.value,e.mtus)),h=he("Keep-alive",i,()=>qo(i.value));return Rt("",[hr("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",[Ut(e.preset)?pt("warn",[t("b",{},Ut(e.preset))," is AmneziaWG 1.0 junk only, which networks learned to spot; it is not offered any more. Switch to ",t("b",{},"Balanced")," or ",t("b",{},"Maximum"),": devices import their configuration again."]):"",hn(r.awg,l,m=>{l=m,c()},s,p),p&&!r.awg.v3?pt("info",["This router runs an older AmneziaWG. ",t("b",{},"Maximum")," becomes available with kmod-amneziawg and amneziawg-tools 3.1."]):"",ts(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",{},[b("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",{class:"dl-keyrow"},[t("code",{class:"dl-mono"},e.public_key),H([b("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."),H("Save",()=>{let m=ze([x,$,h]);if(m){U(m,"warning");return}return n.save({port:o.value,mtu:a.value,keepalive:i.value},"AmneziaWG saved")},"positive")])}function is(n){let e=jt(n.preset),r=n.obf??{},o=(s,l)=>t("span",{class:`dl-segs ${l}`},[0,1,2,3].map(d=>t("i",{class:d+r[s]).map(s=>`${s.toUpperCase()} ${r[s]}`);return i.length&&a.push(i.slice(0,2).join(" · ")+(i.length>2?` +${i.length-2}`:"")),["h1","h2","h3","h4"].some(s=>r[s]&&r[s]!==String(["h1","h2","h3","h4"].indexOf(s)+1))&&a.push("H1–H4 random"),r.i1&&a.push(/0x(8580|0100)0001/.test(r.i1)?"DNS-like first packets":"Signature packets"),r.header_protection_key&&a.push("Encrypted headers"),a.length||a.push(e?.id==="off"?"Plain WireGuard":"No values yet"),t("div",{class:"dl-bento-tile dl-disg"},[t("div",{class:"dl-bento-head"},[t("span",{class:"dl-metric-label"},"Disguise"),t("a",{href:`${L.url("admin/network/dawnline/server")}?server=${encodeURIComponent(n.id)}§ion=awg`},"Change")]),t("div",{class:"dl-disg-id"},[t("span",{class:`dl-disg-ic${e?.id==="off"?" off":""}`},b(e?.ic??"shield")),t("span",{class:"dl-stack"},[t("b",{},e?e.title:Ut(n.preset)??"Custom"),t("span",{class:"dl-sub"},e?e.short:Ut(n.preset)?"Switch to Balanced or Maximum":"Set by hand")])]),e?t("div",{class:"dl-disg-meters"},[t("span",{},"Stealth"),o(e.stealth,"acc"),t("span",{},"Speed"),o(e.speed,"ok")]):"",t("div",{class:"dl-disg-chips"},a.map(s=>t("span",{},s)))])}var oo={id:"awg",label:"AmneziaWG",settingsCard:as,overviewTile:is,connectBlock:os,qrText:n=>n.conf,appKey:{label:"Copy AmneziaVPN key",make:n=>to(n,n.server)},file:{label:"Download .conf",make:n=>({name:n.filename,text:n.conf})}};var ss={awg:oo};function Be(n){return ss[n?.core||"awg"]??oo}function Tt(n,e){return Be(n.find(r=>r.id===e))}var ls=2,Gt=new Set,ro=null,fn=null;async function vr(){if(document.visibilityState!=="visible"||!Gt.size)return;let n=await A.rev().catch(()=>null);if(!n)return;let e=ro!=null&&n.rev!==ro;ro=n.rev,n.version&&(fn&&n.version!==fn?(U(`Dawnline was updated to ${n.version}: reload the page.`,"warning",15e3),fn=null):fn??(fn=n.version)),e&&Gt.forEach(r=>r())}function gn(n){return Gt.add(n),poll.add(vr,ls),()=>{Gt.delete(n),Gt.size||poll.remove(vr)}}function wr(n,e,r,o,a=0){let i=[],s=null,l=p=>{s&&p>s.from&&i.push({...s,to:p}),s=null},d=n.filter(p=>p.device===e).sort((p,u)=>p.ts-u.ts);for(let p of d)if(p.type==="connect")l(p.ts),p.detail&&(s={ip:p.detail,from:p.ts,to:p.ts,live:!1});else if(p.type==="roam"){let u=p.detail?.split("→")[1]?.trim();l(p.ts),u&&(s={ip:u,from:p.ts,to:p.ts,live:!1})}else p.type==="disconnect"&&l(p.ts);let c=s;return c&&o?i.push({...c,to:Math.max(r,c.from),live:!0}):l(Math.min(r,a)),i}function Ke(n){return`${n.city||`${n.lat.toFixed(1)},${n.lon.toFixed(1)}`}|${n.cc}`}function yr(n,e,r,o){let a=new Map;for(let s of e)(s.device===r||!a.has(s.ip))&&a.set(s.ip,s);let i=[];for(let s of n){let l=a.get(s.ip);!l||s.to<=o||i.push({key:Ke(l),point:l,from:Math.max(s.from,o),to:s.to,live:s.live})}return i}function kr(n){let e=new Map,r=0;for(let o of n)e.set(o.key,(e.get(o.key)??0)+(o.to-o.from)),r+=o.to-o.from;return new Map([...e].map(([o,a])=>[o,r?a/r:0]))}function br(n,e=2700){let r=[];for(let o of n){let a=r[r.length-1];if(a&&o.key!==a.key&&!o.live&&o.to-o.from{i&&(r.push({kind:"move",k:i,start:o,ms:e}),o+=e);let s=Math.min(1100,Math.max(350,(a.to-a.from)/3600*45));r.push({kind:"stay",k:i,start:o,ms:s}),o+=s}),{steps:r,total:o}}function Lr(n,e,r){let o=e.findIndex(l=>r>=l.start&&rr>=s.from&&rs.kind==="stay"&&s.k===o),i=n[o];return a.start+a.ms*Math.min(.999,Math.max(0,(r-i.from)/Math.max(1,i.to-i.from)))}var ds=n=>n<=0?0:n>=1?1:n<.5?2*n*n:1-(-2*n+2)**2/2;function Sr(n){return-ao/2+(1+ao)*ds((n-xr)/(1-xr))}var Tr=n=>n+Cr>=1;function _r(n){return["interpolate",["linear"],["abs",["-",["get","pos"],n]],0,1,Cr,1,ao/2,0]}function Pr(n,e){let r=n==="24h"?86400:n==="7d"?604800:2592e3,o=e-r,a=[],i=(l,d)=>{let c=(l-o)/r;c>.02&&c<.98&&a.push([c,d])},s=new Date(o*1e3);if(n==="24h")for(s.setMinutes(0,0,0);s.getTime()/1e3<=e;)s.getHours()%6===0&&i(s.getTime()/1e3,`${String(s.getHours()).padStart(2,"0")}:00`),s.setHours(s.getHours()+1);else if(n==="7d")for(s.setHours(12,0,0,0);s.getTime()/1e3<=e;s.setDate(s.getDate()+1))i(s.getTime()/1e3,s.toLocaleDateString("en-GB",{weekday:"short"}));else{let l=new Date(e*1e3);l.setHours(0,0,0,0);for(let d=0;d<5;d++){let c=new Date(l);c.setDate(l.getDate()-7*d),i(c.getTime()/1e3,c.toLocaleDateString("en-GB",{day:"numeric",month:"short"}))}a.reverse()}return a}var vn=n=>new Date(n*1e3).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});function Dr(n,e){let r=o=>new Date(o*1e3).toDateString();return r(n)===r(e)?"Today":r(n)===r(e-86400)?"Yesterday":new Date(n*1e3).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}var so="https://unpkg.com/maplibre-gl@6.14.0/dist",Ar={module:"sha384-q26X6R1yFeg0QR9SHHn6U3Nb0ddRRTtwxsahubv5R89/v5nijKpk9KviUp9ZLySk",css:"sha384-1TZtfVz7qtwR5vD7cMwjGT+9uiK4lqE3pbUOPwYO6OCpb+TYP0S9vLIhG02JCU04"},Hr="https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",zr="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",cs={online:0,"24h":86400,"7d":7*86400,"30d":30*86400},Wt=null;function ps(n){if(n.appendChild(t("link",{rel:"stylesheet",href:`${so}/maplibre-gl.css`,integrity:Ar.css,crossorigin:"anonymous"})),Wt)return Wt;let e=`${so}/maplibre-gl.mjs`;return Wt=new Promise((o,a)=>{let i=t("link",{rel:"modulepreload",href:e,integrity:Ar.module,crossorigin:"anonymous"});i.addEventListener("load",()=>o()),i.addEventListener("error",()=>a(new Error("integrity"))),document.head.appendChild(i)}).then(()=>import(e)).then(o=>(o.getWorkerUrl()||o.setWorkerUrl(`${so}/maplibre-gl-worker.mjs`),o),o=>{throw Wt=null,new Error(o?.message==="integrity"?"The map library from the CDN is not the expected file: not loading it.":"Could not load the map library (no internet access from this browser?)")}),Wt}function bn(){let n=document.documentElement.getAttribute("data-darkmode");return n!=null?n==="true":window.matchMedia?.("(prefers-color-scheme: dark)").matches??!1}var us=10,Nr=30,ms=62,hs=4,Rr=4.5,fs=7,xn="#3b82f6",lo="#8a8a8a";function Ir(n,e,r=.2,o=64){let[a,i]=n,[s,l]=e,d=s-a,c=d>180?s-360:d<-180?s+360:s,p=c-a,u=l-i,x=Math.hypot(p,u);if(x===0||r===0)return[n,[c,l]];let $=-u/x,h=p/x,m=x*r,C=(a+c)/2+$*m,B=(i+l)/2+h*m,w=[],v=Math.max(2,Math.floor(o));for(let y=0;y<=v;y+=1){let E=y/v,k=1-E;w.push([k*k*a+2*k*E*C+E*E*c,k*k*i+2*k*E*B+E*E*l])}return w}function co(n,e){let r=new Map;for(let o of n.geo.points){if(n.person&&o.person!==n.person||n.device&&o.device!==n.device||(e==="online"?!o.online:n.now-o.ts>cs[e]))continue;let a=n.device?Ke(o):n.person?`${o.device}|${o.city}|${o.cc}`:o.device,i=r.get(a);(!i||o.online&&!i.online||o.online===i.online&&o.ts>i.ts)&&r.set(a,o)}return[...r.values()]}function po(n,e){let r=0;return co(n,e).sort((o,a)=>Number(a.online)-Number(o.online)||a.ts-o.ts).map(o=>({...o,n:o.online?0:++r}))}var nt=class{constructor(e,r="online",o=380){this.cb=e;this.map=null;this.gl=null;this.markers=[];this.popup=null;this.theme=null;this.resize=null;this.fitBlind=!1;this.data=null;this.fitted=!1;this.fitKey=null;this.people=[];this.slots=[];this.merged=[];this.piles=new Map;this.dock=null;this.dockKey="";this.dockQuiet=!1;this.piledKeys=new Set;this.foldedKeys=new Set;this.targetZoom=null;this.before=null;this.hiddenKey="";this.focused=null;this.dead=!1;this.places=new Map;this.replaying=null;this.bandDots=[];this.range=r,this.status=t("div",{class:"dl-map-status"}),this.card=t("div",{class:"dl-map-card","aria-live":"polite"}),this.el=t("div",{class:"dl-geomap",style:`height:${o}px`},[this.status,this.card])}async mount(e){this.data=e;try{this.gl=await ps(this.el)}catch(o){this.status.textContent=o.message;return}if(this.dead)return;this.map=new this.gl.Map({container:this.el,style:bn()?Hr:zr,center:[e.geo.home?.lon??20,e.geo.home?.lat??50],zoom:1,renderWorldCopies:!1,attributionControl:{compact:!0},minZoom:1}),this.map.on("style.load",()=>this.layers()),this.map.on("move",()=>this.declutter()),this.map.once("idle",()=>{let o=this.el.querySelector(".maplibregl-ctrl-attrib");o?.classList.remove("maplibregl-compact-show"),o?.removeAttribute("open")}),this.resize=new ResizeObserver(()=>{!this.map||!this.el.clientWidth||!this.el.clientHeight||(this.map.resize(),this.fitBlind&&(this.fitKey=null,this.draw()))}),this.resize.observe(this.el);let r=bn();this.theme=new MutationObserver(()=>{!this.map||bn()===r||(r=bn(),this.map.setStyle(r?Hr:zr))}),this.theme.observe(document.documentElement,{attributes:!0,attributeFilter:["data-darkmode"]})}layers(){if(this.map){this.hiddenKey="",this.map.setProjection({type:"globe"}),this.map.addSource("dl-areas",{type:"geojson",data:{type:"FeatureCollection",features:[]}}),this.map.addLayer({id:"dl-area",type:"circle",source:"dl-areas",paint:{"circle-radius":["interpolate",["exponential",2],["zoom"],2,6,6,26,9,140,12,900],"circle-color":["case",["get","online"],xn,lo],"circle-opacity":["case",["get","online"],.12,.06],"circle-stroke-width":1,"circle-stroke-color":["case",["get","online"],xn,lo],"circle-stroke-opacity":["case",["get","online"],.35,.15]}}),this.map.addSource("dl-band",{type:"geojson",data:{type:"FeatureCollection",features:this.bandDots}}),this.map.addLayer({id:"dl-band",type:"circle",source:"dl-band",paint:{"circle-radius":1.4,"circle-color":xn,"circle-opacity":0}}),this.map.addSource("dl-arcs",{type:"geojson",data:{type:"FeatureCollection",features:[]}});for(let e of[!1,!0])this.map.addLayer({id:e?"dl-arc-live":"dl-arc-recent",type:"line",source:"dl-arcs",filter:["==",["get","online"],e],layout:{"line-join":"round","line-cap":"round"},paint:{"line-color":e?xn:lo,"line-width":2,"line-opacity":.85,"line-dasharray":[2,2]}});this.draw()}}setRange(e){this.range=e,this.fitKey=null,this.draw()}update(e){this.data=e,this.draw()}destroy(){this.dead=!0,this.dropCard();for(let e of this.piles.values())e.marker.remove();this.piles.clear(),this.theme?.disconnect(),this.resize?.disconnect(),this.map?.remove(),this.map=null}groups(e){let r=new Map;for(let o of e){let a=`${o.person}|${Ke(o)}`,i=r.get(a);i||(i={key:a,person:o.person,lat:o.lat,lon:o.lon,city:o.city,country:o.country,cc:o.cc,asn:o.asn,org:o.org,online:!1,ts:0,points:[]},r.set(a,i)),i.points.push(o),i.online||(i.online=o.online),i.ts=Math.max(i.ts,o.ts)}return[...r.values()]}draw(){if(!this.map||!this.data||!this.map.getSource("dl-arcs"))return;let e=this.data,r=this.groups(co(e,this.range)),o=e.person||e.device?null:e.geo.home;for(let d of this.markers)d.remove();this.markers=[];let a=e.person||e.device?null:vs(r,o),i=r.map(d=>({g:d,at:a?.get(d.key)??[d.lon,d.lat]}));if(this.slots=[],this.map.getSource("dl-areas").setData({type:"FeatureCollection",features:i.map(({g:d})=>({type:"Feature",properties:{online:d.online,key:d.key},geometry:{type:"Point",coordinates:[d.lon,d.lat]}}))}),this.map.getSource("dl-arcs").setData({type:"FeatureCollection",features:o?i.map(({g:d,at:c})=>({type:"Feature",properties:{online:d.online,person:d.person,key:d.key},geometry:{type:"LineString",coordinates:Ir([o.lon,o.lat],c)}})):[]}),o){let d=t("span",{class:"dl-mk-host"});d.innerHTML=`${ft("server","dl-mk-host-ic")}`,this.dock=d.appendChild(t("span",{class:"dl-mk-dock"})),this.dockQuiet=this.dockKey!=="",this.dockKey="";let c=t("div",{class:"dl-mk-hub",title:`Home router${o.city?` · ${o.city}`:""}${o.org?` · ${o.org}`:""}`},[d,t("span",{class:"dl-mk-label chip"},o.city||"Home")]);c.addEventListener("mouseenter",()=>this.showMerged(o.city||"the server")),c.addEventListener("mouseleave",()=>this.focus(this.focused)),c.addEventListener("click",()=>this.zoomToMerged()),this.add(c,[o.lon,o.lat],!0)}let s=new Map(e.device?po(e,this.range).map(d=>[Ke(d),d.n]):[]);this.people=[],this.places.clear();for(let{g:d,at:c}of i){let p=d.points.length,u=e.people.find(m=>m.id===d.person);if(e.person){let m=e.device?this.deviceMarker(d,c,u,s.get(Ke(d))??0):this.placeMarker(d,c,u);this.add(m,c);continue}let x=d.points.map(m=>u?.devices.find(C=>C.id===m.device)?.kind??"other"),$=t("span",{class:"dl-mk-badge"});$.innerHTML=p<=2?x.map(m=>ft(m,"dl-mk-badge-ic")).join(""):String(p);let h=t("button",{type:"button",class:`dl-mk${d.online?" online":""}`,"aria-label":`${u?.name??"Someone"}: ${p} device${p===1?"":"s"} in ${d.city||"an unknown city"}`},[t("span",{class:"dl-mk-av"},[He(u?.name??"?"),$]),t("span",{class:"dl-mk-label below"},d.city||d.cc||"?")]);h.addEventListener("mouseenter",()=>this.focus(d.person)),h.addEventListener("mouseleave",()=>this.focus(null)),this.people.push({el:h,person:d.person}),h.addEventListener("click",m=>{m.stopPropagation(),this.openPopup(d,c,h)}),this.add(h,c,!1,u?.name??"Someone",`${d.city||d.cc||"?"} · ${d.online?"now":re(d.ts,e.now)}`,d.key,d)}this.declutter();let l=i.map(d=>d.g.key).sort().join(";");if(l!==this.fitKey&&!this.popup){let d=this.fitted&&!this.fitBlind;if(this.fitBlind=!this.el.clientWidth||!this.el.clientHeight,this.fitKey=l,this.fitted=!0,o&&!i.length){let c={center:[o.lon,o.lat],zoom:12};d?this.glide(12,()=>this.map.flyTo({...c,duration:1200})):this.map.jumpTo(c)}else{let c=i.map(p=>p.at);o&&(c.length===0||this.range!=="online"||i.some(p=>p.g.online))&&c.push([o.lon,o.lat]),this.fit(c,d)}}this.status.textContent=i.length||o?"":"No locations yet",this.status.style.display=this.status.textContent?"":"none",this.focus(this.focused&&this.people.some(d=>d.person===this.focused)?this.focused:null)}add(e,r,o=!1,a,i,s,l){s&&this.foldedKeys.has(s)&&e.classList.add("merged"),s&&this.piledKeys.has(s)&&e.classList.add("piled"),e.dataset.key=s??"",e.classList.add("dl-mk-new"),requestAnimationFrame(()=>requestAnimationFrame(()=>e.classList.remove("dl-mk-new")));let d=new this.gl.Marker({element:e}).setLngLat(r).addTo(this.map);this.markers.push(d),this.slots.push({marker:d,el:e,at:r,fixed:o,who:a,where:i,g:l})}declutter(){if(!this.map)return;let e=this.map.getZoom();this.el.classList.toggle("dl-lod-far",e=Rr&&e{let l=this.map.project(s.at),d=s.el.querySelector(":scope > .dl-mk-host, :scope > .dl-mk-av, :scope > .dl-mk-tile");return{x:l.x,y:l.y,r:(d?.offsetWidth||24)/2+3,fixed:s.fixed}}),o=r.filter(s=>s.fixed);this.merged=[],this.foldedKeys.clear();let a=this.targetZoom==null?1:Math.min(1,2**(this.targetZoom-this.map.getZoom()));r.forEach((s,l)=>{if(s.fixed)return;let d=this.slots[l],c=d.el.classList.contains("merged")?12:6,p=o.find(u=>Math.hypot(u.x-s.x,u.y-s.y)*a{let c=this.slots[d];!c||c.fixed||(r[d].fixed&&([s,l]=[0,0]),c.marker.setOffset([s,l]),xs(c.el,s,l))})}closePopup(e=!1){let r=this.popup;if(!r||r.card.classList.contains("leaving"))return;r.card.classList.add("leaving"),setTimeout(()=>{this.popup===r&&this.dropCard()},140);let o=this.before;if(this.before=null,!o)return;let a=()=>this.map?.flyTo({...o,duration:800});if(!e)return a();let i=!1,s=()=>{i||(i=!0,window.removeEventListener("pointerup",s,!0),window.removeEventListener("pointercancel",s,!0),setTimeout(a,0))};window.addEventListener("pointerup",s,!0),window.addEventListener("pointercancel",s,!0),setTimeout(s,1500)}dropCard(){this.popup?.off(),this.popup?.card.remove(),this.popup=null}showMerged(e){this.merged.length&&(dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},`Near ${e}`)," · click to zoom in"]),...this.merged.map(r=>t("div",{class:"dl-map-card-row"},[t("span",{},r.who),t("span",{class:"dl-faint"},r.where)]))]),this.card.classList.add("on"))}paintDock(){let e=this.dock;if(!e)return;let r=this.merged.map(a=>`${a.key}:${a.online?1:0}`).join("|");if(r===this.dockKey)return;this.dockKey=r,e.parentElement?.classList.toggle("docked",this.merged.length>0);let o=this.slots.find(a=>a.fixed).at;this.merged.length&&Or(e,this.merged,this.faceActions(()=>[o]),this.dockQuiet),this.dockQuiet=!1}faceActions(e){return{click:(r,o)=>this.openFace(r,o,e()),hover:r=>this.focus(r?.g?.person??null)}}pileUp(e){let r=new Set;if(!this.data?.person&&!this.data?.device){let o=e.flatMap((l,d)=>!l.fixed&&this.slots[d].el.querySelector(":scope > .dl-mk-av")?[d]:[]),a=new Map(o.map(l=>[l,l])),i=l=>a.get(l)===l?l:i(a.get(l));for(let l of o)for(let d of o){if(d<=l)continue;let c=this.slots[l].el.classList.contains("piled")&&this.slots[d].el.classList.contains("piled");Math.hypot(e[l].x-e[d].x,e[l].y-e[d].y)this.slots[m]),c=d.map(Br),p=c.map(m=>m.key).sort().join(",");r.add(p);let u=[d.reduce((m,C)=>m+C.at[0],0)/d.length,d.reduce((m,C)=>m+C.at[1],0)/d.length],x=this.piles.get(p);if(!x){let m=t("span",{class:"dl-mk-pile-box"}),C=[...new Set(d.map(v=>v.g?.city||v.g?.cc||"?"))],B=t("div",{class:"dl-mk-pile"},[m,t("span",{class:"dl-mk-label below"},C.length===1?C[0]:`${d.length} people`)]);x={marker:new this.gl.Marker({element:B}).setLngLat(u).addTo(this.map),el:B,box:m,faces:c},B.addEventListener("mouseleave",()=>this.focus(this.focused));let w=x;B.addEventListener("click",v=>{v.stopPropagation(),this.zoomInTo(w.faces.map(y=>y.at),!1)}),this.piles.set(p,x)}x.faces=c;let $=x;Or(x.box,c,this.faceActions(()=>$.faces.map(m=>m.at)));for(let m of l)this.slots[m].el.classList.add("piled"),Object.assign(e[m],{r:0,fixed:!0});let h=this.map.project(u);e.push({x:h.x,y:h.y,r:(x.el.offsetWidth||60)/2+3,fixed:!0})}}this.piledKeys=new Set(this.slots.filter(o=>o.el.classList.contains("piled")).map(o=>o.el.dataset.key??"")),this.slots.forEach((o,a)=>{(!e[a].fixed||o.fixed||o.el.classList.contains("merged"))&&o.el.classList.remove("piled")});for(let[o,a]of this.piles)r.has(o)||(this.piles.delete(o),a.el.classList.add("out"),setTimeout(()=>a.marker.remove(),200))}zoomToMerged(){!this.map||!this.merged.length||this.zoomInTo([this.slots.find(e=>e.fixed).at,...this.merged.map(e=>e.at)],!1)}openFace(e,r,o){if(!e.g)return;if(o.every(i=>wn(i,e.at)<1))return this.openPopup(e.g,e.at,r);let a=()=>{let i=this.slots.find(s=>s.el.dataset.key===e.key);i?.g&&!i.el.classList.contains("merged")&&!i.el.classList.contains("piled")&&this.openPopup(i.g,i.at,i.el)};this.zoomInTo(this.nearby(e.at),!0)?this.map.once("moveend",a):a()}nearby(e){return[e,...this.slots.filter(r=>!r.fixed&&r.at!==e&&wn(r.at,e)<=Nr).map(r=>r.at)]}zoomInTo(e,r){let o=new this.gl.LngLatBounds;for(let p of e)o.extend(p);let a=e.some(p=>e.some(u=>wn(p,u)>Nr)),i=this.map.cameraForBounds(o,{padding:50,maxZoom:a?12:us}),s=this.map.getZoom(),l=e.map(p=>this.map.project(p)),d=0;l.forEach((p,u)=>l.slice(u+1).forEach(x=>{let $=Math.hypot(p.x-x.x,p.y-x.y),h=s+Math.log2(ms/Math.max($,1e-6));h<=12&&(d=Math.max(d,h))}));let c=Math.min(12,Math.max(i?.zoom??0,d));return c<=s+.05?!1:(r&&!this.before&&(this.before={center:this.map.getCenter().toArray(),zoom:s}),this.map.flyTo({center:i?.center??o.getCenter(),zoom:c,duration:800}),!0)}placeMarker(e,r,o){let a=this.data.now,i=[...e.points].sort((u,x)=>Number(x.online)-Number(u.online)||x.ts-u.ts)[0],s=o?.devices.find(u=>u.id===i.device)?.kind??"other",l=e.points.length,d=t("span",{class:"dl-mk-tile"});d.innerHTML=ft(s,"dl-mk-tile-ic")+(l>1?`${l}`:"");let c=e.online?"now":re(e.ts,a),p=t("button",{type:"button",class:`dl-mk place${e.online?" online":""}`,style:e.online?null:`--dl-mk-fade:${Math.max(.4,1-.6*(a-e.ts)/(30*86400)).toFixed(2)}`,"aria-label":`${l} device${l===1?"":"s"} in ${e.city||"an unknown city"}, ${c}`},[d,t("span",{class:"dl-mk-label below"},[e.city||e.cc||"?",t("span",{class:"dl-mk-when"},c)])]);return p.addEventListener("click",u=>{u.stopPropagation(),this.openPopup(e,r,p)}),p}deviceMarker(e,r,o,a){let i=o?.devices.find(p=>p.id===e.points[0].device)?.kind??"other",s=t("span",{class:"dl-mk-tile"}),l=t("span",{class:"dl-mk-label below"}),d=t("button",{type:"button",class:"dl-mk place step"},[s,l]);d.addEventListener("click",p=>{p.stopPropagation(),this.openPopup(e,r,d)});let c=Ke(e);return this.places.set(c,{el:d,tile:s,label:l,when:null,g:e,n:a,kind:i}),this.paintPlace(c,!1),d}paintPlace(e,r){let o=this.places.get(e);if(!o)return;let a=this.replaying,i=a?a.active===e:o.g.online,s=o.el.classList.contains("online"),l=o.g.city||o.g.cc||"?";o.el.classList.toggle("online",i),o.el.classList.toggle("faded",!!a&&!i),o.tile.classList.toggle("sm",!i),i||!o.n?o.tile.innerHTML=ft(o.kind,"dl-mk-tile-ic"):o.tile.textContent=String(o.n),o.when=null,i?(o.when=t("span",{class:`dl-mk-when${a?" inline":""}`},a?a.when:"now"),o.label.replaceChildren(l,a?" · ":"",o.when)):o.label.replaceChildren(`${l} · ${o.g.online?"now":re(o.g.ts,this.data.now)}`);let d=i?a?a.when:"now":o.g.online?"now":re(o.g.ts,this.data.now);o.el.setAttribute("aria-label",`${o.n?`${o.n}: `:""}${o.g.city||"an unknown city"}, ${d}`),r&&i&&!s&&(o.el.classList.remove("arrive"),o.el.offsetWidth,o.el.classList.add("arrive"),setTimeout(()=>o.el.classList.remove("arrive"),500))}replay(e,r=!0){let o=this.replaying;if(this.replaying=e,o&&e&&o.active===e.active){let a=e.active?this.places.get(e.active):null;a?.when&&(a.when.textContent=e.when);return}for(let a of this.places.keys())a!==e?.active&&this.paintPlace(a,r);e?.active&&this.paintPlace(e.active,r),this.declutter(),setTimeout(()=>this.declutter(),320)}hoverPlace(e){for(let[r,o]of this.places)o.el.classList.toggle("hl",r===e)}band(e,r){if(this.bandDots=[],this.map&&e&&r){let o=Ir(e,r),a=o.map(c=>this.map.project(c)),i=[0];for(let c=1;ci[d]?(p-i[d])/(i[d+1]-i[d]):0,x=[o[d][0]+(o[d+1][0]-o[d][0])*u,o[d][1]+(o[d+1][1]-o[d][1])*u];this.bandDots.push({type:"Feature",properties:{pos:c/l},geometry:{type:"Point",coordinates:x}})}}this.map?.getLayer("dl-band")&&(this.map.setPaintProperty("dl-band","circle-opacity",0),this.map.getSource("dl-band").setData({type:"FeatureCollection",features:this.bandDots}))}bandAt(e){this.map?.getLayer("dl-band")&&this.map.setPaintProperty("dl-band","circle-opacity",_r(e))}focus(e){this.focused=e;for(let s of this.people)s.el.classList.toggle("dim",!!e&&s.person!==e),s.el.classList.toggle("hl",s.person===e);let r=e?["case",["==",["get","person"],e],.85,.15]:.85;for(let s of["dl-arc-live","dl-arc-recent"])this.map?.getLayer(s)&&this.map.setPaintProperty(s,"line-opacity",r);if(this.card.classList.toggle("on",!!e),!e||!this.data)return;let o=this.data,a=o.people.find(s=>s.id===e),i=co(o,this.range).filter(s=>s.person===e).sort((s,l)=>Number(l.online)-Number(s.online)||l.ts-s.ts);dom.content(this.card,[t("div",{class:"dl-map-card-head"},[t("b",{},a?.name??e),` · ${i.length} device${i.length===1?"":"s"}`]),...i.map(s=>t("div",{class:"dl-map-card-row"},[t("span",{},a?.devices.find(l=>l.id===s.device)?.name??"Device"),t("span",{class:"dl-faint"},`${s.city||s.cc||"?"} · ${s.online?"now":re(s.ts,o.now)}`)]))])}fit(e,r=!1){if(!e.length)return;let o=(p,u)=>{let x=Math.PI/180,$=(u[1]-p[1])*x,h=(u[0]-p[0])*x,m=Math.sin($/2)**2+Math.cos(p[1]*x)*Math.cos(u[1]*x)*Math.sin(h/2)**2;return 12742*Math.asin(Math.sqrt(m))},a=[e.reduce((p,u)=>p+u[0],0)/e.length,e.reduce((p,u)=>p+u[1],0)/e.length],i=e;if(e.length>=5){let p=[...e].sort((u,x)=>o(a,u)-o(a,x));i=p.slice(0,Math.ceil(p.length*.9))}let s=new this.gl.LngLatBounds(i[0],i[0]);i.forEach(p=>s.extend(p));let l=this.el.clientHeight||380,d=!!this.data?.person,c={padding:{top:this.data?.device?Math.min(56,l/4):Math.min(60,l/5),bottom:d?Math.min(52,l/4):Math.min(40,l/8),left:48,right:48},maxZoom:this.data?.person?11:12};r?this.glide(this.map.cameraForBounds(s,c)?.zoom??null,()=>this.map.fitBounds(s,{...c,duration:1200})):this.map.fitBounds(s,{...c,duration:0})}glide(e,r){this.targetZoom=e,this.declutter(),this.map.once("moveend",()=>{this.targetZoom=null,this.declutter()}),r()}openPopup(e,r,o){let a=this.data,i=[e.city,e.cc||e.country].filter(Boolean).join(", "),s=[...new Set(e.points.map(v=>v.person))],l=e.points.sort((v,y)=>Number(y.online)-Number(v.online)||y.ts-v.ts).map(v=>{let y=a.people.find(k=>k.id===v.person),E=y?.devices.find(k=>k.id===v.device);return t("button",{type:"button",class:"dl-pop-row",click:()=>this.cb.openDevice(v.person,v.device)},[t("span",{class:`dl-pop-dot${v.online?" on":""}`}),t("span",{class:"dl-pop-name"},[t("b",{},y?.name??v.person),` · ${E?.name??"device"}`]),t("span",{class:"dl-faint dl-nowrap"},v.online?"now":re(v.ts,a.now))])}),d=t("div",{class:"dl-pop"},[t("div",{class:"dl-pop-head"},[t("span",{class:"dl-pop-net"},b("globe")),t("div",{class:"dl-stack"},[t("strong",{},e.org||"Unknown network"),t("span",{class:"dl-faint"},[e.asn?`AS${e.asn} · `:"",i?`${i} · approximate`:"approximate location"])])]),t("div",{class:"dl-pop-list"},l),s.length===1?t("div",{class:"dl-pop-actions"},[t("button",{type:"button",class:"cbi-button cbi-button-positive important",click:()=>this.cb.openPerson(s[0])},`Open ${a.people.find(v=>v.id===s[0])?.name??"person"}`)]):""]);this.zoomInTo(this.nearby(r),!0),this.dropCard();let c=t("div",{class:"dl-root dl-popcard",role:"dialog"},[t("span",{class:"dl-popcard-tip"}),d]);document.body.appendChild(c);let p=this.el,u=o?.querySelector(".dl-mk-av, .dl-mk-tile")??o??null,x=()=>{if(!u)return;let v=u.getBoundingClientRect(),y=p.getBoundingClientRect(),E=v.left+v.width/2,k=v.top+v.height/2;c.classList.toggle("away",Ey.right||ky.bottom);let z=c.offsetWidth,f=c.offsetHeight,g=v.top-f-12>=8||v.top>window.innerHeight-v.bottom,S=Math.min(Math.max(8,E-z/2),window.innerWidth-z-8);c.classList.toggle("above",g),c.classList.toggle("below",!g),c.style.left=`${S}px`,c.style.top=`${g?v.top-f-12:v.bottom+12}px`,c.style.setProperty("--tip-x",`${E-S}px`)},$=v=>{v.target?.closest(".dl-popcard, .maplibregl-marker")||this.closePopup(!0)},h=v=>{v.key==="Escape"&&this.closePopup()},m=v=>{v.target instanceof Element&&v.target.closest(".dl-popcard")||this.closePopup()},C=()=>this.closePopup();this.map.on("move",x),window.addEventListener("scroll",m,{capture:!0,passive:!0}),window.addEventListener("resize",x),document.addEventListener("pointerdown",$,!0),document.addEventListener("keydown",h);let B=$e(C);window.addEventListener("pagehide",C),this.popup={card:c,off:()=>{this.map?.off("move",x),window.removeEventListener("scroll",m,!0),window.removeEventListener("resize",x),document.removeEventListener("pointerdown",$,!0),document.removeEventListener("keydown",h),B(),window.removeEventListener("pagehide",C)}};let w=window.setInterval(()=>{if(this.popup?.card!==c)return clearInterval(w);(!p.isConnected||!p.getClientRects().length)&&this.dropCard()},400);x()}};function gs(n,e=6){let r=n.map(o=>({x:o.x,y:o.y}));for(let o=0;o<16;o++){let a=!1;for(let i=0;i[o.x-n[a].x,o.y-n[a].y])}function vs(n,e){let r=new Map,o=e?[[e.lon,e.lat]]:[],a=i=>o.some(s=>wn(i,s)<1.3);for(let i of[...n].sort((s,l)=>s.key>>12)/1048575),d=(s&4095)/4096*2*Math.PI,c=[i.lon,i.lat];for(let p=0;p<24;p++){let u=d+p*2.39996,x=Math.min(8,l+p*.25);if(c=[i.lon+x*Math.sin(u)/(111.32*Math.cos(i.lat*Math.PI/180)),i.lat+x*Math.cos(u)/111.32],!a(c))break}o.push(c),r.set(i.key,c)}return r}function bs(n){let e=2166136261;for(let r=0;r>>0}function Br(n){return{key:n.el.dataset.key??"",who:n.who??"Someone",where:n.where??"",online:!!n.g?.online,at:n.at,badge:n.el.querySelector(".dl-mk-badge")?.innerHTML??"",g:n.g}}function Or(n,e,r,o=!1){let a=e.length>3,i=()=>[...n.children].filter(h=>!h.classList.contains("out")),s=new Map(i().map(h=>[h,h.getBoundingClientRect().left])),l=n.getBoundingClientRect().width,d=new Map;n.querySelectorAll(".dl-mk-face:not(.out)").forEach(h=>d.set(h.dataset.key??"",h));let c=n.querySelector(".dl-mk-more:not(.out)"),p=h=>{Object.assign(h.style,{position:"absolute",left:`${h.offsetLeft}px`,top:`${h.offsetTop}px`,transform:""}),h.classList.add("out"),setTimeout(()=>h.remove(),200)},u=[];for(let h of e.slice(0,a?2:3)){let m=d.get(h.key);if(d.delete(h.key),!m){let w=t("button",{type:"button",class:`dl-mk-face${o?"":" in"}`,"data-key":h.key},[t("span",{class:"dl-mk-av"},He(h.who)),t("span",{class:"dl-mk-badge"})]);w.addEventListener("animationend",()=>w.classList.remove("in"),{once:!0}),m=w}let C=m,B=C.querySelector(".dl-mk-badge");B.innerHTML!==h.badge&&(B.innerHTML=h.badge),C.title=`${h.who} · ${h.where}`,C.setAttribute("aria-label",`${h.who}, ${h.where}`),C.classList.toggle("on",h.online),C.onclick=w=>{w.stopPropagation(),r.click(h,C)},C.onmouseenter=()=>r.hover(h),C.onmouseleave=()=>r.hover(null),u.push(C)}for(let h of d.values())p(h);if(a){if(!c){c=t("span",{class:`dl-mk-more${o?"":" in"}`});let h=c;h.addEventListener("animationend",()=>h.classList.remove("in"),{once:!0})}c.textContent=`+${e.length-2}`,u.push(c)}else c&&p(c);let x=null;for(let h of u)(x?x.nextElementSibling:n.firstElementChild)!==h&&(x?x.after(h):n.prepend(h)),x=h;for(let h of u){let m=s.get(h);if(m==null)continue;let C=m-h.getBoundingClientRect().left;Math.abs(C)<.5||(h.style.transition="none",h.style.transform=`translateX(${C}px)`,h.offsetWidth,h.style.transition="",h.style.transform="")}n.style.width="";let $=n.getBoundingClientRect().width;if(l&&Math.abs($-l)>.5){n.style.width=`${l}px`,n.offsetWidth,n.style.width=`${$}px`;let h=()=>{n.style.width="",n.removeEventListener("transitionend",h)};n.addEventListener("transitionend",h),setTimeout(h,400)}}function wn(n,e){let r=Math.PI/180,o=Math.sin((e[1]-n[1])*r/2)**2+Math.cos(n[1]*r)*Math.cos(e[1]*r)*Math.sin((e[0]-n[0])*r/2)**2;return 12742*Math.asin(Math.min(1,Math.sqrt(o)))}function xs(n,e,r){let o=n.querySelector(":scope > .dl-mk-ptr"),a=Math.hypot(e,r);if(a<1){o?.remove();return}o||(o=t("span",{class:"dl-mk-ptr"},[t("i",{class:"line"}),t("i",{class:"spot"})]),n.prepend(o));let i=o.firstElementChild,s=o.lastElementChild;i.style.width=`${a}px`,i.style.transform=`rotate(${Math.atan2(-r,-e)}rad)`,s.style.transform=`translate(${-e}px, ${-r}px)`}function _t(n,e,r=!0){let o=[["online","Online now"],["24h","24h"],["7d","7 days"],["30d","30 days"]],a=t("div",{class:"dl-seg",role:"tablist"});for(let[i,s]of o)i==="online"&&!r||a.appendChild(t("button",{type:"button",role:"tab",class:i===n?"on":"","data-v":i,click:()=>{a.querySelectorAll("button").forEach(l=>l.classList.toggle("on",l.dataset.v===i)),e(i)}},s));return a}var jr={"24h":86400,"7d":7*86400,"30d":30*86400},uo=(n,e)=>`${(n/e*100).toFixed(3)}%`,yn=class{constructor(e,r,o){this.map=e;this.range=r;this.el=t("div",{class:"dl-dplaces"});this.controls=t("div",{class:"dl-map-replay"});this.pending=null;this.rows=new Map;this.st=[];this.steps=[];this.total=0;this.ms=0;this.stepI=-1;this.on=!1;this.playing=!1;this.raf=0;this.last=0;this.endTimer=0;this.play=t("button",{type:"button",class:"dl-map-btn"});this.chip=t("span",{class:"dl-map-chip"});this.stop=t("button",{type:"button",class:"dl-map-btn",title:"Back to now","aria-label":"Back to now"},b("x"));this.reduced=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;this.data=o,this.play.addEventListener("click",()=>this.toggle()),this.stop.addEventListener("click",()=>this.end()),this.paint()}mapData(){let e=this.data;return{geo:e.geo,people:[e.person],now:e.now,person:e.person.id,device:e.device.id}}update(e){let r={...this.pending??this.data,...e};if(this.on){this.pending=r;return}this.data=r,this.map.update(this.mapData()),this.paint()}setRange(e){this.end(),this.range=e,this.map.setRange(e),this.paint()}destroy(){cancelAnimationFrame(this.raf),clearTimeout(this.endTimer)}paint(){let e=this.data,r=jr[this.range],o=e.now-r,a=yr(wr(e.events??[],e.device.id,e.now,e.device.online,e.device.handshake),e.geo.points,e.device.id,o),i=kr(a);this.st=$r(a);let s=po(this.mapData(),this.range),l=a.length>0;this.el.classList.toggle("strips",l),this.el.classList.toggle("can-replay",this.st.length>1),this.rows.clear(),dom.content(this.el,s.length?[...s.map(d=>{let c=Ke(d),p=i.get(c),u=l?t("div",{class:`dl-dplace-strip${d.online?" live":""}`},a.filter($=>$.key===c).map($=>t("i",{style:`left:${uo($.from-o,r)};width:${uo($.to-$.from,r)}`}))):"",x=t("div",{class:"dl-dplace-row"},[t("span",{class:`dl-dplace-n${d.online?" live":""}`},d.online?b(e.device.kind):String(d.n)),t("span",{class:"dl-row-main dl-stack"},[t("span",{},[d.city||d.cc||"Unknown city",d.org?t("span",{class:"dl-muted"},` · ${d.org}`):""]),t("span",{class:"dl-faint"},[t("span",{class:"dl-mono"},d.ip),p!=null?` · ${p>0&&p<.005?"<1":Math.round(p*100)}% of the time`:""])]),t("span",{class:d.online?"dl-dplace-now":"dl-faint dl-nowrap"},d.online?"now":re(d.ts,e.now)),u]);if(x.addEventListener("mouseenter",()=>this.map.hoverPlace(c)),x.addEventListener("mouseleave",()=>this.map.hoverPlace(null)),u){let $=h=>{let m=u.getBoundingClientRect();this.seek(o+r*Math.min(1,Math.max(0,(h.clientX-m.left)/m.width)))};u.addEventListener("pointerdown",h=>{u.setPointerCapture(h.pointerId),$(h)}),u.addEventListener("pointermove",h=>h.buttons&&$(h))}return this.rows.set(c,x),x}),l?t("div",{class:"dl-dplace-axis"},Pr(this.range,e.now).map(([d,c])=>t("span",{style:`left:${(d*100).toFixed(2)}%`},c))):""]:t("div",{class:"dl-sub"},"No locations in this period.")),this.paintControls()}paintControls(){dom.content(this.play,b(this.playing?"pause":"play")),this.play.title=this.playing?"Pause":"Replay this period",this.play.setAttribute("aria-label",this.play.title),dom.content(this.controls,this.on?[this.play,this.chip,this.stop]:this.st.length>1?[this.play]:[])}begin(){this.on=!0,{steps:this.steps,total:this.total}=Er(this.st,this.reduced?400:io),this.ms=0,this.stepI=-1,this.map.replay({active:null,when:""},!0)}toggle(){if(this.playing){this.playing=!1,cancelAnimationFrame(this.raf),this.paintControls();return}clearTimeout(this.endTimer),(!this.on||this.ms>=this.total)&&this.begin(),this.playing=!0,this.last=performance.now(),this.paintControls(),this.raf=requestAnimationFrame(e=>this.frame(e))}frame(e){if(this.playing){if(this.ms=Math.min(this.total,this.ms+(e-this.last)),this.last=e,this.show(!0),this.msthis.frame(r));return}this.playing=!1,this.paintControls(),this.endTimer=window.setTimeout(()=>this.end(),1500)}}seek(e){this.st.length<2||(clearTimeout(this.endTimer),this.on||this.begin(),this.ms=Mr(this.st,this.steps,e),this.stepI=-1,this.show(!1),this.paintControls())}show(e){let r=Lr(this.st,this.steps,this.ms),o=this.st[r.step.k];if(r.step.kind==="move"){let s=this.st[r.step.k-1];r.i!==this.stepI&&(this.map.replay({active:null,when:""},e),this.map.band([s.point.lon,s.point.lat],[o.point.lon,o.point.lat]));let l=Sr(r.q);this.reduced||this.map.bandAt(l),(this.reduced?r.q>=.5:Tr(l))&&this.map.replay({active:o.key,when:vn(r.t)},e)}else r.i!==this.stepI&&this.map.band(),this.map.replay({active:o.key,when:vn(r.t)},e);this.stepI=r.i;let a=this.data,i=a.now-jr[this.range];this.el.classList.add("replay"),this.el.style.setProperty("--at",uo(r.t-i,a.now-i));for(let[s,l]of this.rows)l.classList.toggle("cur",s===o.key);this.chip.textContent=`${Dr(r.t,a.now)}, ${vn(r.t)} · ${o.point.city||o.point.cc||"?"}`}end(){if(cancelAnimationFrame(this.raf),clearTimeout(this.endTimer),!!this.on){this.on=!1,this.playing=!1,this.ms=0,this.stepI=-1,this.map.band(),this.map.replay(null,!1),this.el.classList.remove("replay");for(let e of this.rows.values())e.classList.remove("cur");this.pending?(this.data=this.pending,this.pending=null,this.map.update(this.mapData()),this.paint()):this.paintControls()}}};function Pt(n){return`${L.url("admin/network/dawnline/server")}?${n?`server=${encodeURIComponent(n)}&`:""}section=people`}function ke(n,e){return`${L.url("admin/network/dawnline/person")}?id=${encodeURIComponent(n)}${e?`&device=${encodeURIComponent(e)}`:""}`}function ws(n){return n?new Date(n*1e3).toLocaleString("en-GB",{day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function mo(n,e,r=!1){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("button",{type:"button",class:`dl-kvrow-v copy${r?" dl-mono":""}`,title:"Copy",click:()=>ue(e,`${n} copied`)},[t("span",{},e),b("copy")])])}function kn(n,e){return t("div",{class:"dl-kvrow"},[t("span",{class:"dl-kvrow-k"},n),t("span",{class:"dl-kvrow-v"},e)])}var Ur={connect:["ok","Connected","plug"],disconnect:["","Went offline","plug"],roam:["","Changed network","network"],device_added:["ok","Added","plus"],device_removed:["","Removed","trash"],device_keys:["","New keys","reset"]};function ys(n,e,r){let o=n.filter(a=>a.device===e&&Ur[a.type]).reverse().slice(0,12);return o.length?t("div",{class:"dl-dev-log"},o.map(a=>{let[i,s,l]=Ur[a.type],d=a.type==="connect"?[a.detail?t("span",{class:"dl-muted"},` from ${a.detail}`):"",a.where?t("span",{class:"dl-muted"},` · ${a.where}`):""]:a.type==="roam"?[t("span",{class:"dl-muted"},` · ${a.detail??""}`)]:a.type==="device_added"||a.type==="device_removed"||a.type==="device_keys"?[t("span",{class:"dl-muted"},Ne(a)==="portal"?" on the portal":Ne(a)==="admin"?" by you":"")]:[],c=new Date(a.ts*1e3);return t("div",{class:`dl-dev-log-row${Ne(a)==="admin"?" dl-ev-by-admin":""}`},[Ne(a)==="admin"?t("span",{class:"dl-ev-tile",title:"Done by you in LuCI"},b("admin")):t("span",{class:`dl-ev-tile ev ${i}`},b(l)),t("span",{class:"dl-row-main"},[t("span",{},s),...d]),t("span",{class:"dl-faint dl-nowrap",title:c.toLocaleString()},re(a.ts,r))])})):t("div",{class:"dl-sub"},"No activity yet.")}async function Gr(n,e,r){let o=await A.status(1).catch(()=>null),a=o?.people.find(s=>s.id===n),i=a?.devices.find(s=>s.id===e);o&&a&&i&&Ge(a,i,{...r,geo:o.geo,now:o.now,today:Ie(o.series),core:Tt(o.servers,a.server)})}async function Ge(n,e,r){let o=await G(()=>A.deviceConfig(e.id));if(!o)return;let a=r.core??Be(null),i=e,s=n,l=r.geo,d=r.now,c=r.today??je(new Date),p=await a.connectBlock(o,e.kind==="phone"||e.kind==="tablet"?"qr":"file"),u=t("div",{class:"dl-drawer-title"}),x=t("div",{}),$=t("div",{}),h=t("div",{},t("div",{class:"dl-sub"},"Loading…")),m=[],C=Q=>{m=Q.filter(te=>te.device===i.id),dom.content(h,ys(Q,i.id,d)),y?.update({events:Q})},B=async(Q=!1)=>{let te=r.events?.();if(te&&!Q)return C(te);let ge=await A.events(2e3,n.id).catch(()=>null);ge&&C(ge.events)},w="30d",v=null,y=null,E=()=>{dom.content(u,[t("span",{class:`dl-dcard-ic${i.online?" on":""}`},b(i.kind)),t("div",{class:"dl-stack"},[t("div",{class:"dl-title-row"},[t("h3",{},i.name),H([b("edit")],()=>f(),"neutral",{title:"Rename",class:"cbi-button cbi-button-neutral dl-icon-only sm"})]),t("span",{class:"dl-sub"},`${s.name} · ${Qe[i.kind]}`)])]);let Q=i.spark.reduce((te,ge)=>te+ge,0);dom.content(x,t("div",{class:"dl-dstats"},[t("div",{class:"dl-dstats-cell wide"},[t("span",{class:"dl-metric-label"},"Status"),on(i,d,"Waiting for the first connection",s)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},"This month"),t("b",{},ee(i.month[0]+i.month[1])),t("span",{class:"dl-sub dl-mono"},`↓ ${ee(i.month[1])} ↑ ${ee(i.month[0])}`)]),t("div",{class:"dl-dstats-cell"},[t("span",{class:"dl-metric-label"},"Last 7 days"),t("b",{},ee(Q)),dr(i.spark,120,22,c)])])),dom.content($,t("div",{class:"dl-kv2"},[mo("Tunnel address",i.address),i.hostname&&s.access!=="internet"?mo("Local address",i.hostname):"",i.endpoint&&!l?.points.some(te=>te.device===i.id&&te.ip===i.endpoint)?kn("Client IP",i.endpoint):"",kn("Total",t("span",{class:"dl-kv-act"},[`↓ ${ee(i.total[1])} · ↑ ${ee(i.total[0])}`,t("button",{type:"button",class:"dl-linkbtn danger",click:()=>St("device",i.id,i.name,()=>setTimeout(z,300))},"Reset")])),kn("Added",`${ws(i.created)} · ${i.created_by==="portal"?"from the portal":"by you"}`),o.amnezia.client_pub_key?mo("Public key",o.amnezia.client_pub_key):kn("Public key","—")])),dom.content(g,[H([b(i.disabled?"play":"pause"),i.disabled?" Enable":" Disable"],async()=>{await G(()=>A.deviceUpdate(i.id,void 0,!i.disabled),i.disabled?"Device enabled":"Device disabled")&&await z()},"neutral",i.disabled?{}:{class:"cbi-button cbi-button-neutral dl-btn-warn"}),H([b("key")," New keys"],async()=>{if(!await le("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0))return;await G(()=>A.deviceRotate(i.id),"New keys generated")&&(r.refresh(),de.close(),await Gr(s.id,i.id,r))}),t("span",{class:"dl-spacer"}),H([b("trash")," Remove"],async()=>{await le(`Remove ${i.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await G(()=>A.deviceDelete(i.id),"Device removed")&&(de.close(),r.refresh())},"negative")])},k=async()=>{let Q=await A.status(1).catch(()=>null),te=Q?.people.find(O=>O.id===s.id),ge=te?.devices.find(O=>O.id===i.id);!Q||!te||!ge||(s=te,i=ge,l=Q.geo,d=Q.now,c=Ie(Q.series),E(),y?.update({geo:Q.geo,now:Q.now,person:s,device:i}))},z=async()=>{await k(),r.refresh()},f=()=>{let Q=t("input",{type:"text",class:"cbi-input-text",value:i.name,maxlength:48}),te=s.devices.filter(O=>O.id!==i.id).map(O=>O.name),ge=ye("Name",Q,()=>_e(Q.value,te,"Shown in the portal and in the app."));oe(`Rename ${i.name}`,[ge],[ie()," ",H("Save",async()=>{let O=ge.help();if(O.bad){U(O.text,"warning");return}await G(()=>A.deviceUpdate(i.id,Q.value,void 0),"Renamed")&&(ae(),await z())},"positive")]),setTimeout(()=>Q.select(),50)},g=t("div",{class:"dl-drawer-actions"}),S=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Connect")]),i.config_stale?t("div",{class:"dl-note warn"},[b("alert"),t("span",{},"This device has an older configuration: networks or DNS changed since it was set up. Import it again with the QR code, key or file below.")]):"",p]),T=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Activity"),t("div",{class:"dl-dsec-actions"},[t("button",{type:"button",class:"dl-linkbtn",click:()=>Fe({people:[s]},m,"csv",i.id)},"Export"),t("button",{type:"button",class:"dl-linkbtn danger",click:()=>tt(`Clear ${i.name}'s activity`,`Removes events about ${i.name}.`,{device:i.id},()=>{B(!0),r.refresh()})},"Clear"),t("a",{href:`${L.url("admin/network/dawnline/diagnostics")}?tab=log`},"All activity")])]),h]),N=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},t("h4",{},"Details")),$]),W="";if(l?.enabled){v=new nt({openPerson:te=>location.href=ke(te),openDevice:(te,ge)=>location.href=ke(te,ge)},w,220);let Q=y=new yn(v,w,{geo:l,now:d??Date.now()/1e3,person:s,device:i,events:r.events?.()??null});W=t("section",{class:"dl-dsec"},[t("div",{class:"dl-dsec-head"},[t("h4",{},"Locations"),_t(w,te=>{w=te,Q.setRange(te)},!1)]),t("div",{class:"dl-dmap"},[v.el,Q.controls]),Q.el])}let q=!i.handshake||i.config_stale,Y=t("div",{class:"dl-stack gap16"},q?[x,S,N,W,T]:[x,N,W,T,S]);B();let R=()=>{k(),B()},K=gn(R),Z=window.setInterval(R,3e4),de=Oo(u,Y,g,()=>{clearInterval(Z),K(),y?.destroy(),v?.destroy()});E(),v&&y&&requestAnimationFrame(()=>y&&v?.mount(y.mapData()))}function Wr(n,e,r,o){let a=o.core??Be(null),i=()=>G(()=>A.deviceConfig(r.id)),s=[{label:"Show QR code",icon:b("qr"),run:async()=>{let l=await i();l&&oe(`${r.name} · QR code`,t("div",{class:"dl-qr-pane"},[et(Lt(a.qrText(l)),"dl-qr"),t("span",{class:"dl-sub"},no(l)?"Scan with AmneziaVPN or any WireGuard app on the device.":"Scan with AmneziaVPN or AmneziaWG on the device.")]),ie("Close"))}},{label:a.file.label,icon:b("download"),run:async()=>{let l=await i();if(!l)return;let d=a.file.make(l);Te(d.name,d.text,"application/octet-stream")}},a.appKey?{label:a.appKey.label,icon:b("copy"),run:async()=>{let l=await i();l&&ue(await a.appKey.make(l),"Key copied")}}:null,null,{label:"Rename",icon:b("edit"),run:()=>Ge(e,r,o)},{label:"New keys",icon:b("key"),run:async()=>{await le("Generate new keys?","The current configuration on this device stops working until it is imported again.","Generate",!0)&&await G(()=>A.deviceRotate(r.id),"New keys generated")&&o.refresh()}},{label:r.disabled?"Enable":"Disable",icon:b(r.disabled?"play":"pause"),warn:!r.disabled,run:async()=>{await G(()=>A.deviceUpdate(r.id,void 0,!r.disabled),r.disabled?"Device enabled":"Device disabled")&&o.refresh()}},{label:"Delete",icon:b("trash"),danger:!0,run:async()=>{await le(`Remove ${r.name}?`,"The device is disconnected immediately and its configuration stops working.","Remove",!0)&&await G(()=>A.deviceDelete(r.id),"Device removed")&&o.refresh()}}];Ce(n,s)}function ot(n,e){let r=n.devices.map(c=>c.name),o=c=>{let p=Qe[c],u=1,x=p;for(;r.some($=>$.toLowerCase()===x.toLowerCase());)x=`${p} ${++u}`;return x},a="phone",i=t("input",{type:"text",class:"cbi-input-text",placeholder:o(a),maxlength:48}),s=ye("Name",i,()=>i.value.trim()?_e(i.value,r,"Shown in the portal and in the app."):{text:`Named after its type: ${o(a)}.`,bad:!1}),l=t("div",{class:"dl-kinds",role:"radiogroup","aria-label":"Type"},No.map(c=>t("button",{type:"button",role:"radio",class:c===a?"on":"","aria-checked":c===a?"true":"false","data-kind":c,click:()=>{a=c,l.querySelectorAll("button").forEach(p=>{let u=p.dataset.kind===c;p.classList.toggle("on",u),p.setAttribute("aria-checked",u?"true":"false")}),i.placeholder=o(c),s.refresh()}},[b(c),t("span",{},Qe[c])]))),d=n.devices.length>=n.device_limit;oe(`Add a device for ${n.name}`,[d?t("p",{class:"dl-hint"},`${n.name} already has ${n.devices.length} of ${n.device_limit} devices. As admin you can still add one.`):"",t("div",{class:"dl-fld"},[t("span",{class:"dl-fld-label"},"Type"),l]),s],[ie()," ",H("Add device",async()=>{let c=s.help();if(c.bad){U(c.text,"warning");return}let p=i.value.trim()||o(a),u=await G(()=>A.deviceCreate(n.id,p,a));u&&(ae(),U(`${p} added`,"success",3e3),e.refresh(),await Gr(n.id,u.id,e))},"positive")]),setTimeout(()=>i.focus(),50)}var Ve=1080,qt=1512,We=96,ks="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",$s="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",Ft=n=>n.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e]);function Cs(n,e,r){let o=new URL(r),a=o.pathname.slice(1),i=Math.min(92,Math.floor((Ve-2*We)/(.58*(4+n.name.length)))),s=Ve-2*We,l=392,d=40,c=Lt(r,2).replace("`}var br={opacity:1,filter:"blur(0px)",transform:"none"},Jo={opacity:0,filter:"blur(5px)",transform:"scale(.86)"},wr={opacity:0,filter:"blur(5px)",transform:"scale(.6)"},Mr={duration:180,easing:J,fill:"forwards"},Re={duration:340,delay:70,easing:Y,fill:"backwards"},Cr=Re.delay+Re.duration,Ne=new WeakMap;function un(t){let e=getComputedStyle(t);return{opacity:e.opacity,filter:e.filter==="none"?"blur(0px)":e.filter,transform:e.transform}}function kr(t){var e;for(let n of[...t.childNodes])n.nodeType===Node.TEXT_NODE&&((e=n.textContent)!=null&&e.trim())&&n.replaceWith(i("span",{},n.textContent));return[...t.children].filter(n=>!n.classList.contains("orb"))}function Er(t,e){var r;let n=(r=Ne.get(t))!=null?r:[];Ne.set(t,e),n.forEach(o=>o.cancel())}function Lr(t){var o;(o=t.querySelector(":scope > .orb"))==null||o.remove();let e=kr(t),n=e.map(un),r=i("span",{class:"orb","aria-hidden":"true"},i("i"),i("i"));t.append(r),t.classList.add("busy"),t.setAttribute("aria-busy","true"),Er(t,[...e.map((a,c)=>_(a,[n[c],Jo],Mr)),_(r,[wr,br],Re)])}function Tr(t){let e=t.querySelector(":scope > .orb"),n=kr(t),r=[...e?[_(e,[un(e),wr],Mr)]:[],...n.map(o=>_(o,[un(o),br],Re))];Er(t,r),t.removeAttribute("aria-busy"),Promise.all(r.map(o=>o.finished)).then(()=>{Ne.get(t)===r&&(Ne.delete(t),r.forEach(o=>o.cancel()),e==null||e.remove(),t.classList.remove("busy"))},()=>{})}var Ar=t=>[...t].map(e=>i("i",{},e)),ne=new WeakMap,ge=t=>{var e,n,r;return(r=(n=(e=ne.get(t))==null?void 0:e.text)!=null?n:t.textContent)!=null?r:""};function hn(t){let e=document.createRange();return e.selectNodeContents(t),e.getBoundingClientRect()}function Sr(t){var a;let e=t.firstChild;if(!e||e.nodeType!==Node.TEXT_NODE)return[];let n=document.createRange(),r=[],o=0;for(let c of(a=e.textContent)!=null?a:"")n.setStart(e,o),n.setEnd(e,o+c.length),r.push(n.getBoundingClientRect().left),o+=c.length;return r.map(c=>c-r[0])}function $r(t,e){let n=[...t.children];if(!n.length)return;let r=n[0].getBoundingClientRect().left;n.forEach((o,a)=>{if(!a||e[a]===void 0)return;let c=r+e[a]-o.getBoundingClientRect().left;Math.abs(c)>.01&&(o.style.marginLeft=`${c}px`)})}function Zo(t,e){let n=0;for(;nnew Array(a.length+1).fill(0));for(let v=o.length-1;v>=0;v--)for(let u=a.length-1;u>=0;u--)c[v][u]=o[v]===a[u]?c[v+1][u+1]+1:Math.max(c[v+1][u],c[v][u+1]);let g=[];for(let v=0;v=c[v][u+1]?v++:u++;for(let v=r;v>0;v--)g.push([t.length-v,e.length-v]);return g}function Ie(t){let e=ne.get(t);e&&(clearTimeout(e.timer),ne.delete(t),t.getAnimations().forEach(n=>n.cancel()),t.classList.remove("mt","mt-ib"),t.textContent=e.text)}function bt(t,e){Ie(t),t.textContent=e}function Z(t,e,n=ge(t),r={}){var ot,it;let{whole:o=!1,at:a}=r,c=((ot=r.glide)!=null?ot:!0)&&!a,g=ne.has(t)?t.getBoundingClientRect().width:null;if(Ie(t),n===e||Lt()||!t.getClientRects().length){t.textContent=e;return}let v=getComputedStyle(t),u=o&&v.display==="inline";v.display==="inline"&&!o&&t.classList.add("mt-ib"),v.position==="static"&&t.classList.add("mt");let M=null,b=a!=null?a:null,A=[];b||(t.textContent=n,M=t.getBoundingClientRect(),b=hn(t),A=Sr(t)),t.textContent=e;let O=t.getBoundingClientRect(),B=Sr(t),P=(it=g!=null?g:M==null?void 0:M.width)!=null?it:O.width,H=c&&!u&&!!M&&Math.abs(O.width-P)>.5,$=!H||!M||Math.abs(O.left-M.left)<.5?"start":Math.abs(O.right-M.right)<.5?"end":"middle",d=i("span",{class:o?"mt-new w":"mt-new"},o?e:Ar(e)),m=i("span",{class:o?"mt-old w":"mt-old","aria-hidden":"true"},o?n:Ar(n));o&&(m.style.width=`${b.width+1}px`),t.replaceChildren(d,m),H&&_(t,[{width:`${P}px`},{width:`${O.width}px`}],{duration:U.duration,easing:U.easing,fill:"forwards"});let s=t.getBoundingClientRect(),h=(G,V)=>{m.style.top=`${V}px`,$==="end"?m.style.right=`${-G}px`:$==="middle"?(m.style.left="50%",m.style.translate=`calc(-50% + ${G}px) 0`):m.style.left=`${G}px`},f=$==="end"?b.right-s.right:$==="middle"?(b.left+b.right-s.left-s.right)/2:b.left-s.left;h(f,b.top-s.top);let E=hn(m);if(h(f+b.left-E.left,b.top-s.top+b.top-E.top),o){_(m,[{opacity:1,filter:"blur(0px)"},{opacity:0,filter:"blur(4px)"}],{duration:180,easing:J,fill:"forwards"}),_(d,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"blur(0px)"}],{duration:280,delay:60,easing:Y,fill:"backwards"});let G=Math.max(340,H?U.duration:0)+40;ne.set(t,{text:e,timer:window.setTimeout(()=>Ie(t),G)});return}$r(d,B),$r(m,A);let p=[...m.children],l=[...d.children],L=Zo([...n],[...e]),x=new Set(L.map(([G])=>G)),C=new Set(L.map(([,G])=>G));L.forEach(([G,V])=>{let $t=p[G].getBoundingClientRect(),lt=l[V].getBoundingClientRect();p[G].style.visibility="hidden",(Math.abs($t.left-lt.left)>.5||Math.abs($t.top-lt.top)>.5)&&_(l[V],[{transform:`translate(${$t.left-lt.left}px, ${$t.top-lt.top}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing})});let R=p.filter((G,V)=>!x.has(V)),I=l.filter((G,V)=>!C.has(V)),z=Math.min(12,160/Math.max(1,R.length)),Q=Math.min(22,260/Math.max(1,I.length));R.forEach((G,V)=>_(G,[{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:"blur(4px)",transform:"translateY(-0.45em)"}],{duration:220,delay:V*z,easing:J,fill:"forwards"})),I.forEach((G,V)=>_(G,[{opacity:0,filter:"blur(4px)",transform:"translateY(0.45em)"},{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:380,delay:120+V*Q,easing:Y,fill:"backwards"}));let et=Math.max(220+R.length*z,I.length?120+I.length*Q+380:0,H||L.length?U.duration:0)+40;ne.set(t,{text:e,timer:window.setTimeout(()=>Ie(t),et)})}function Fe(t){return new Map([...t.querySelectorAll("[data-t]")].map(e=>[e.dataset.t,ge(e)]))}function Ke(t,e){t.querySelectorAll("[data-t]").forEach(n=>{var a;let r=e.get(n.dataset.t),o=(a=n.textContent)!=null?a:"";r!==void 0&&r!==o&&Z(n,o,r)})}var _r=t=>`${t.tagName}.${[...t.classList].filter(e=>e!=="mt"&&e!=="mt-ib").join(" ")}`,Pr=t=>t.outerHTML.replace(/\bgl\d+/g,"gl");function ti(t){let e=new Map,n=(r,o)=>r.childNodes.forEach((a,c)=>{var M,b;let g=`${o}/${c}`;if(a.nodeType===Node.TEXT_NODE){if((M=a.textContent)!=null&&M.trim()){let A=document.createRange();A.selectNodeContents(a);let O=A.getBoundingClientRect();e.set(g,{kind:"#text",text:a.textContent,svg:"",at:O,words:O,node:a})}return}if(!(a instanceof Element))return;let v=a instanceof SVGElement?Pr(a):"",u=a instanceof HTMLElement&&!v?hn((b=a.querySelector(":scope > .mt-new"))!=null?b:a):null;e.set(g,{kind:_r(a),text:a instanceof HTMLElement?ge(a):"",svg:v,at:a.getBoundingClientRect(),words:u,node:a}),v||n(a,g)});return n(t,""),e}var pn=t=>_(t,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"blur(0px)"}],{duration:280,delay:60,easing:Y,fill:"backwards"});function qe(t,e){var O;let n=ti(t),r=t.getBoundingClientRect();if(Rt(t,e),!n.size||Lt())return;let o=t.getBoundingClientRect(),a=B=>B&&new DOMRect(B.left-r.left+o.left,B.top-r.top+o.top,B.width,B.height),c=[],g=[],v=new Set,u=(B,P,H)=>{var m;let $=B.parentElement,d=H?(m=n.get(H))==null?void 0:m.at:r;P!=null&&P.at&&P.node instanceof Element&&g.push($&&d?[P.node,P.at,$,d]:[P.node,P.at,t,r]),c.push(()=>pn(B))},M=(B,P,H)=>{let $=B.getBoundingClientRect(),d=P.left-r.left-($.left-o.left),m=P.top-r.top-($.top-o.top),s=d-H[0],h=m-H[1];return(Math.abs(s)>.5||Math.abs(h)>.5)&&_(B,[{transform:`translate(${s}px, ${h}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing}),[d,m]},b=(B,P,H)=>[...B.childNodes].forEach(($,d)=>{var E,p;let m=`${P}/${d}`;v.add(m);let s=n.get(m);if($.nodeType===Node.TEXT_NODE){let l=(E=$.textContent)!=null?E:"";if(!l.trim()||(s==null?void 0:s.kind)==="#text"&&s.text===l)return;let L=i("span",{},l);$.replaceWith(L),s!=null&&s.at&&M(L,s.at,H),c.push(()=>{var x;return(s==null?void 0:s.kind)==="#text"&&l.length<=40&&s.text.length<=40?Z(L,l,s.text,{whole:!0,at:(x=a(s.words))!=null?x:void 0}):pn(L)});return}if(!($ instanceof Element))return;let h=$.getBoundingClientRect();if(!s||s.kind!==_r($)||s.at&&Math.abs(s.at.height-h.height)>1&&!($ instanceof SVGElement))return u($,s,P);let f=s.at?M($,s.at,H):H;if($ instanceof SVGElement){s.svg!==Pr($)&&c.push(()=>pn($));return}if(!$.children.length&&$ instanceof HTMLElement){let l=(p=$.textContent)!=null?p:"";l!==s.text&&c.push(()=>{var L;return l.length<=40&&s.text.length<=40?Z($,l,s.text,{whole:!0,at:(L=a(s.words))!=null?L:void 0}):u($,s,P)});return}b($,m,f)});b(t,"",[0,0]);for(let[B,P]of n)!v.has(B)&&B.lastIndexOf("/")===0&&P.at&&P.node instanceof Element&&g.push([P.node,P.at,t,r]);c.forEach(B=>B());let A=new Map;for(let[,,B]of g)!A.has(B)&&getComputedStyle(B).position==="static"&&B.classList.add("mt"),A.set(B,((O=A.get(B))!=null?O:0)+1);for(let[B,P,H,$]of g){let d=B;d.style.position="absolute",d.style.margin="0",d.style.left=`${P.left-$.left-H.clientLeft}px`,d.style.top=`${P.top-$.top-H.clientTop}px`,d.style.width=`${P.width}px`,d.style.pointerEvents="none",d.setAttribute("aria-hidden","true"),H.appendChild(d),_(d,[{opacity:1,filter:"blur(0px)"},{opacity:0,filter:"blur(4px)"}],{duration:180,easing:J,fill:"forwards"}).onfinish=()=>{d.remove();let m=A.get(H)-1;A.set(H,m),m||H.classList.remove("mt")}}}var ei='',fn=()=>[F("apple"),_t(ei)];function ni(t,e){if(t===e)return["",t,t,""];let n=t.split(" "),r=e.split(" "),o=0;for(;ov?d[2]:d[1],M=d=>i("span",{class:"osm-p"},d),b=()=>{c=o.findIndex(d=>d[1]!==d[2]),c<0&&(v=0),a=o.map(d=>({pre:M(d[0]),word:M(u(d)),suf:M(d[3])})),g=c>=0?i("span",{class:"osm-ic"},fn()[v]):null,n.replaceChildren(...a.flatMap((d,m)=>[m?i("span",{class:"arr"},"›"):null,d.pre,m===c?g:null,d.word,d.suf]).filter(d=>!!d))},A={width:"1.05em",marginRight:"0.25em"},O=d=>_(d,[{opacity:1,filter:"blur(0px)",...A},{opacity:0,filter:"blur(3px)",width:"0px",marginRight:"0px"}],{duration:220,easing:J,fill:"forwards"}).onfinish=()=>d.remove(),B=d=>_(d,[{opacity:0,filter:"blur(3px)",width:"0px",marginRight:"0px"},{opacity:1,filter:"blur(0px)",...A}],{duration:U.duration,easing:U.easing}),P=(d,m)=>{r.setAttribute("aria-label",(d===m?d:`${d} (Android: ${m.split(" → ").pop()})`).replace(/ → /g," › "));let s=d.split(" → "),h=m.split(" → "),f=s.map((p,l)=>{var L;return ni(p,(L=h[l])!=null?L:p)});if(!a.length||f.length!==o.length)return o=f,b();let E=c;o=f,c=o.findIndex(p=>p[1]!==p[2]),c<0&&(v=0),o.forEach((p,l)=>{Z(a[l].pre,p[0],void 0,{whole:!0}),Z(a[l].word,u(p),void 0,{whole:!0}),Z(a[l].suf,p[3],void 0,{whole:!0})}),c!==E&&(g&&O(g),g=c>=0?i("span",{class:"osm-ic"},fn()[v]):null,g&&(a[c].word.before(g),B(g)))};P(t,e);let H=()=>{if(!r.isConnected)return clearInterval($);if(c<0||!g||!r.offsetParent)return;v=1-v,Z(a[c].word,u(o[c]));let d=g.firstElementChild,m=fn()[v];if(Lt()){d.replaceWith(m);return}g.appendChild(m),_(d,[{opacity:1,filter:"blur(0px)",transform:"none"},{opacity:0,filter:"blur(3px)",transform:"scale(.5) rotate(-40deg)"}],{duration:200,easing:J,fill:"forwards"}).onfinish=()=>d.remove(),_(m,[{opacity:0,filter:"blur(3px)",transform:"scale(.5) rotate(40deg)"},{opacity:1,filter:"blur(0px)",transform:"none"}],{duration:yt.duration,delay:80,easing:yt.easing,fill:"backwards"})},$=window.setInterval(H,3e3);return{el:r,set:P}}var Ge=null,ve=null,Br=0,Hr=(t,e,n)=>_(t,e,{duration:n,easing:J,fill:"forwards"}).onfinish=()=>t.remove();function wt(t,e=!1){Ge!=null||(Ge=document.body.appendChild(i("div",{class:"toasts"}))),ve&&Hr(ve,[{opacity:1},{opacity:0,transform:"scale(.96)",filter:"blur(4px)"}],140);let n=i("div",{class:`toast${e?" bad":""}`,role:"status"},F(e?"alert":"check"),i("span",{},t));Ge.appendChild(n),ve=n,_(n,[{opacity:0,transform:"translateY(18px) scale(.9)",filter:"blur(6px)"},{opacity:1,transform:"none",filter:"none"}],{duration:kt.duration,easing:kt.easing}),clearTimeout(Br),Br=window.setTimeout(()=>{ve===n&&(ve=null,Hr(n,[{opacity:1},{opacity:0,transform:"translateY(6px) scale(.96)",filter:"blur(4px)"}],180))},2400)}function ri(t){var a;if(t.classList.contains("copied"))return;let e=t.querySelector("svg.i"),n=t.querySelector(".lbl, .b-main"),r=n?ge(n):"";t.classList.add("copied");let o=null;e&&(o=F("check",(a=e.getAttribute("class"))!=null?a:"i"),e.replaceWith(o),_(o,[{opacity:0,transform:"scale(.6)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:yt.duration,easing:yt.easing})),n&&/^Copy/.test(r)&&Z(n,"Copied"),setTimeout(()=>{o&&e&&o.replaceWith(e),n&&/^Copy/.test(r)&&Z(n,r),t.classList.remove("copied")},1600)}async function pt(t,e="Copied",n){try{await navigator.clipboard.writeText(t)}catch{let r=i("textarea",{class:"offscreen"},t);document.body.appendChild(r),r.select();let o=document.execCommand("copy");if(r.remove(),!o)return wt("Copying is blocked here. Select the text and copy it by hand.",!0)}n instanceof Element&&ri(n),wt(e)}function Wt(t,e){var o;let n=navigator;if(He()!=="ios"||typeof n.share!="function"||typeof File=="undefined")return null;let r=new File([e],t,{type:"application/octet-stream"});return(o=n.canShare)!=null&&o.call(n,{files:[r]})?async()=>{try{await n.share({files:[r]})}catch(a){(a==null?void 0:a.name)!=="AbortError"&&Ue(t,e)}}:null}function Ue(t,e){let n=URL.createObjectURL(new Blob([e],{type:"application/octet-stream"})),r=i("a",{href:n,download:t,class:"offscreen"});document.body.appendChild(r),r.click(),setTimeout(()=>{URL.revokeObjectURL(n),r.remove()},1e3)}function ye(t,e){let n=Wt(t,e);n?n():Ue(t,e)}async function zt(t,e){if(t.disabled)return;t.disabled=!0,Lr(t);let n=performance.now();try{await e()}finally{let r=Lt()?0:Cr-(performance.now()-n);r>0&&await new Promise(o=>setTimeout(o,r)),Tr(t),t.disabled=!1}}var mn=matchMedia("(prefers-color-scheme: light)"),oi=()=>mn.matches?"day":"night";function gn(t,e){var n,r;t.dataset.qr=e,t.classList.toggle("dense",dn(e)),t.classList.toggle("light",mn.matches),t.innerHTML=xr(e,3,!0,oi()),t.dataset.mods=String((r=(n=t.firstElementChild)==null?void 0:n.viewBox.baseVal.width)!=null?r:0)}function xe(t,e=!1){let n=i("div",{class:`qrbox${e?" big":""}`});return gn(n,t),n}mn.addEventListener("change",()=>document.querySelectorAll(".qrbox[data-qr]").forEach(t=>{var e;(e=t.querySelector("svg.old"))==null||e.remove(),gn(t,t.dataset.qr)}));function vn(t,e){let n=xe(t),r=i("div",{class:"words"},e),o=i("div",{class:"side"},r),a=i("div",{class:`coderow${n.classList.contains("dense")?" stacked":""}`},n,o);return{el:a,swap(c,g){let v=n.dataset.qr===c?null:n.querySelector("svg");if(v){gn(n,c),a.classList.toggle("stacked",n.classList.contains("dense"));let M=n.querySelector("svg");v.classList.add("old"),n.appendChild(v),_(M,[{opacity:0},{opacity:1}],{duration:200,easing:Y}),_(v,[{opacity:1},{opacity:0}],{duration:220,delay:110,easing:J,fill:"forwards"}).onfinish=()=>v.remove()}if(!g)return;let u=r;r=i("div",{class:"words"},g),o.appendChild(r),u.classList.add("old"),_(r,[{opacity:0,filter:"blur(3px)"},{opacity:1,filter:"blur(0px)"}],{duration:220,easing:Y}),_(u,[{opacity:1,filter:"blur(0px)"},{opacity:0,filter:"blur(3px)"}],{duration:200,delay:90,easing:J,fill:"forwards"}).onfinish=()=>u.remove()}}}function re(t){let e=typeof navigator.share=="function";return i("div",{class:"linkrow"},i("span",{class:"mono"},t.replace(/^https?:\/\//,"")),i("button",{type:"button",class:"knob","aria-label":"Copy the link",onclick:n=>pt(t,"Link copied",n.currentTarget)},F("copy")),e?i("button",{type:"button",class:"knob","aria-label":"Share the link",onclick:()=>navigator.share({url:t,title:Ut()}).catch(()=>{})},F("share")):null)}var Vt=null,Dt=null,be=()=>!!Vt;function Bt(t=!1){let e=Vt;if(e){if(Vt=null,Dt==null||Dt.setAttribute("aria-expanded","false"),Dt=null,t){e.remove();return}_(e,[{opacity:1},{opacity:0,transform:"scale(.96)",filter:"blur(3px)"}],{duration:120,easing:J,fill:"forwards"}).onfinish=()=>e.remove()}}function Or(t,e){var u;if(Dt===t&&Vt)return Bt();Bt(!0);let n=e.filter((M,b)=>M||b>0&&e[b-1]&&e.slice(b+1).some(Boolean)),r=i("span",{class:"menu-hl"}),o=i("div",{class:"menu",role:"menu"},r);for(let M of n){if(!M){o.appendChild(i("div",{class:"menu-sep"}));continue}let b=i("button",{type:"button",role:"menuitem",class:`mi ${(u=M.tone)!=null?u:""}`,onclick:()=>{Bt(),M.run()}},F(M.icon),i("span",{},M.label));b.addEventListener("pointerenter",()=>{var A;r.className=`menu-hl${r.style.opacity==="1"?" moving":""} ${(A=M.tone)!=null?A:""}`,r.style.transform=`translateY(${b.offsetTop-6}px)`,r.style.opacity="1"}),o.appendChild(b)}o.addEventListener("pointerleave",()=>r.style.opacity="0"),document.body.appendChild(o);let a=t.getBoundingClientRect(),c=o.offsetWidth,g=o.offsetHeight,v=a.bottom+8+g{let e=t.target;Vt&&!Vt.contains(e)&&!(Dt!=null&&Dt.contains(e))&&Bt()});addEventListener("scroll",()=>Bt(),{passive:!0});var st,At,W,Rr,ae,Ft,rt,It=[],We=null,yn=null,we=!1,oe=null,St=()=>!!(st!=null&&st.classList.contains("open")),se=400,Nr=80,ii=3.2,le=()=>matchMedia("(min-width: 760px)").matches,ie=se,xn=null;function ce(){var o;if(!st||!St())return null;if(!le())return W.style.maxWidth&&(W.style.maxWidth=""),ie=se,null;let t=[...rt.querySelectorAll(".qrbox.dense")].find(a=>{let c=a.closest(".acc-row");return a.offsetWidth&&(!c||c.classList.contains("open"))&&!a.closest(".leaving")}),e=se;if(t){let a=Math.min(innerWidth-32-Nr,innerHeight-120);e=Math.max(se,Math.round(Math.min(+((o=t.dataset.mods)!=null?o:0)*ii,a)+Nr))}let n=t&&t!==xn?t:null;if(xn=t!=null?t:null,Math.abs(e-ie)<8)return n?{from:e,want:e,reveal:n}:null;let r=parseFloat(getComputedStyle(W).maxWidth)||ie;return ie=e,W.getAnimations().filter(a=>{var c;return(c=a.effect)==null?void 0:c.getKeyframes().some(g=>"maxWidth"in g)}).forEach(a=>a.cancel()),W.style.maxWidth=`${e}px`,{from:r,want:e,reveal:n}}function de(t){if(!t)return;Math.abs(t.from-t.want)>1&&_(W,[{maxWidth:`${t.from}px`},{maxWidth:`${t.want}px`}],{duration:U.duration,easing:U.easing});let e=t.reveal;e&&setTimeout(()=>{if(!e.isConnected)return;let n=Ft.getBoundingClientRect(),r=e.getBoundingClientRect(),o=r.bottom>n.bottom-16?r.bottom-n.bottom+16:r.topft()},F("x")),ae=i("div",{class:"sheet-acts"}),rt=i("div",{class:"vp"}),Ft=i("div",{class:"sheet-scroll"},rt),W=i("div",{class:"sheet",role:"dialog","aria-modal":"true"},Rr,ae,Ft),At=i("div",{class:"scrim",onclick:()=>ft()}),st=i("div",{class:"sheet-root","aria-hidden":"true"},At,W),document.body.appendChild(st),new ResizeObserver(()=>de(ce())).observe(rt),li()}function Ir(t){W.setAttribute("aria-label",t.label),W.setAttribute("role",t.asks?"alertdialog":"dialog")}function ze(){let t=yn;yn=null,t==null||t()}function Fr(t){yn=t}function Yt(t){We=t}function ht(t){if(st||ai(),Bt(!0),ze(),St()){It=[t],bn(t());return}oe=document.activeElement instanceof HTMLElement?document.activeElement:null,It=[t],We=null,ie=se,xn=null,W.style.maxWidth="",W.classList.remove("arrived");let e=t();rt.replaceChildren(e.el),Kr(e,!1),Ir(e),st.classList.add("open"),st.setAttribute("aria-hidden","false"),document.body.classList.add("locked");let n=ce();if(n&&de({...n,from:n.want}),W.getAnimations().forEach(r=>r.cancel()),At.getAnimations().forEach(r=>r.cancel()),W.style.transform="",le()?_(W,[{opacity:0,transform:"scale(.9)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:Et.duration,easing:Et.easing}):_(W,[{transform:"translateY(calc(100% + 40px))"},{transform:"none"}],{duration:500,easing:an}),_(At,[{opacity:0},{opacity:1}],le()?{duration:Et.duration,easing:Et.easing}:{duration:420,easing:"ease-out"}),!we)try{history.pushState({sheet:!0},""),we=!0}catch{}}function ft(t=!1){if(!St()||st.dataset.closing)return;ze(),we&&(we=!1,history.back()),document.body.classList.remove("locked");let e=()=>{st.classList.remove("open"),st.setAttribute("aria-hidden","true"),delete st.dataset.closing,W.style.transform="",At.style.opacity="",W.getAnimations().forEach(a=>a.cancel()),At.getAnimations().forEach(a=>a.cancel()),rt.getAnimations().forEach(a=>a.cancel()),rt.replaceChildren(),ae.replaceChildren(),W.classList.remove("arrived"),W.style.maxWidth="",ie=se,It=[],oe!=null&&oe.isConnected&&oe.focus({preventScroll:!0}),oe=null;let o=We;We=null,o==null||o()};if(t)return e();st.dataset.closing="1";let n=getComputedStyle(W).transform;W.getAnimations().forEach(o=>o.cancel()),_(At,[{opacity:getComputedStyle(At).opacity},{opacity:0}],le()?{duration:120,easing:J,fill:"forwards"}:{duration:320,easing:"ease-out",fill:"forwards"});let r=n==="none"?"none":n;_(W,le()?[{opacity:1,transform:r,filter:"blur(0px)"},{opacity:0,transform:`${r==="none"?"":r} scale(.96)`.trim(),filter:"blur(3px)"}]:[{transform:r},{transform:"translateY(calc(100% + 40px))"}],le()?{duration:120,easing:J,fill:"forwards"}:{duration:420,easing:an,fill:"forwards"}).onfinish=e}addEventListener("popstate",()=>{St()&&(we=!1,ft())});function Kr(t,e=!0){var o;let n=(o=t.acts)!=null?o:null,r=ae.firstElementChild;if(n!==r){if(!e||r&&n&&r.dataset.key===n.dataset.key)return ae.replaceChildren(...n?[n]:[]);r&&(Object.assign(r.style,{position:"absolute",right:"0",top:"0",pointerEvents:"none"}),_(r,[{opacity:1,transform:"none",filter:"none"},{opacity:0,transform:"scale(.9)",filter:"blur(3px)"}],{duration:180,easing:"cubic-bezier(.2,0,0,1)",fill:"forwards"}).onfinish=()=>r.remove()),n&&(ae.appendChild(n),_(n,[{opacity:0,transform:"scale(.9)",filter:"blur(3px)"},{opacity:1,transform:"none",filter:"none"}],{duration:260,delay:110,easing:"cubic-bezier(.2,0,0,1)",fill:"backwards"}))}}function bn(t){Ir(t),Kr(t),W.classList.remove("arrived");let e=[...rt.children],n=rt.getBoundingClientRect().height;rt.getAnimations().forEach(a=>a.cancel()),e.forEach(a=>{a.classList.add("leaving"),Object.assign(a.style,{position:"absolute",left:"0",right:"0",top:"0",pointerEvents:"none"}),a.inert=!0}),rt.appendChild(t.el),t.el.style.pointerEvents="none",setTimeout(()=>t.el.style.pointerEvents="",320),Ft.scrollTop=0;let r=ce(),o=t.el.getBoundingClientRect().height;_(rt,[{height:`${n}px`},{height:`${o}px`}],{duration:360,easing:"cubic-bezier(.25,1,.5,1)"}),de(r),e.forEach(a=>_(a,[{opacity:1,transform:"none",filter:"none"},{opacity:0,transform:"scale(.96)",filter:"blur(2px)"}],{duration:200,easing:"cubic-bezier(.2,0,0,1)",fill:"forwards"}).onfinish=()=>a.remove()),_(t.el,[{opacity:0,transform:"scale(.96)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:280,delay:110,easing:"cubic-bezier(.2,0,0,1)",fill:"backwards"})}function Ve(t){if(!St())return ht(t);ze(),It.push(t),bn(t())}function si(){It.length<2||(ze(),It.pop(),bn(It[It.length-1]()))}function qr(t,e=[]){if(!St())return t();let n=rt.getBoundingClientRect().height;rt.getAnimations().forEach(v=>v.cancel());let r=rt.lastElementChild,o=new Map;r==null||r.querySelectorAll("*").forEach(v=>{(!(v instanceof SVGElement)||v instanceof SVGSVGElement)&&o.set(v,v.getBoundingClientRect())}),t();let a=ce(),c=rt.getBoundingClientRect().height;Math.abs(c-n)>1&&_(rt,[{height:`${n}px`},{height:`${c}px`}],{duration:U.duration,easing:U.easing}),de(a);let g=new Set;for(let[v,u]of o){if(!v.isConnected||!u.width||!u.height)continue;let M=v.getBoundingClientRect();if(!M.width||!M.height)continue;let b=u.left-M.left,A=u.top-M.top;if(Math.abs(b)<.5&&Math.abs(A)<.5)continue;g.add(v);let O=v.parentElement;for(;O&&O!==r&&!g.has(O);)O=O.parentElement;O&&O!==r||_(v,[{transform:`translate(${b}px, ${A}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing})}for(let v of e)v&&_(v,[{opacity:0,filter:"blur(4px)"},{opacity:1,filter:"none"}],{duration:280,easing:Y})}function Gr(){W==null||W.classList.add("arrived")}var Ur=()=>Ft==null?void 0:Ft.scrollTo({top:0,behavior:"smooth"}),wn=t=>St()&&rt.contains(t)&&!t.closest(".leaving");function li(){let t=null;W.addEventListener("pointerdown",n=>{let r=n.target;!r.closest(".vhead")||r.closest("button, a, input")||(t={y:n.clientY,t:performance.now(),dy:0,v:0},W.setPointerCapture(n.pointerId))}),W.addEventListener("pointermove",n=>{if(!t)return;let r=n.clientY-t.y,o=performance.now(),a=r>0?r:-qn(-r,W.offsetHeight);t.v=(a-t.dy)/Math.max(1,o-t.t),t.dy=a,t.t=o,W.style.transform=`translateY(${a}px)`,At.style.opacity=String(Math.max(0,1-Math.max(0,a)/420))});let e=()=>{if(!t)return;let{dy:n,v:r}=t;if(t=null,Gn(n,r,W.offsetHeight))return ft();let o=W.style.transform;W.style.transform="",At.style.opacity="",n!==0&&_(W,[{transform:o},{transform:"none"}],{duration:U.duration,easing:U.easing})};W.addEventListener("pointerup",e),W.addEventListener("pointercancel",e)}function Ct(t,e={}){return i("div",{class:`vhead${e.back?" center":""}${e.acts?" with-acts":""}`},e.back?i("button",{type:"button",class:"knob back","aria-label":"Back",onclick:si},F("chevron")):null,i("h2",{},t))}var Ht=t=>i("p",{class:"vsub"},t),Kt=(...t)=>i("p",{class:"hint"},...t);function Wr(){ht(()=>{let t=Zt();return{el:i("div",{class:"view"},Ct("Open on another device"),Ht("Point its camera at the code: this page opens there."),xe(t,!0),re(t)),label:"Open on another device"}})}var ci='',je=null,Me=null,Ye=null;function Mn(t){if(Me)return Me;je=i("header",{class:"crumbs"}),Me=i("div",{class:"page-body"}),t.replaceChildren(i("div",{class:"edge-fade top","aria-hidden":"true"}),i("div",{class:"edge-fade bot","aria-hidden":"true"}),Ye=i("main",{class:"page"},je,Me));let e=()=>document.body.classList.toggle("scrolled",scrollY>2);return addEventListener("scroll",e,{passive:!0}),e(),Me}function Cn(t){Ye==null||Ye.classList.toggle("single",t)}function kn(t=!1,e=!1){var o;if(!je)return;let n=t?null:(o=dt())==null?void 0:o.person,r=i("span",{class:n?"":"cur","aria-current":n?null:"page"},Ut());je.replaceChildren(i("span",{class:"cr-mark"},_t(ci)),i("nav",{class:"cr-path","aria-label":"Breadcrumb"},r,n?[F("chevron"),i("span",{class:"cur","aria-current":"page"},n.name)]:null),...n&&!e?[i("button",{type:"button",class:"knob cr-qr","aria-label":"Open on another device",onclick:Wr},F("qr"))]:[])}function Vr(t,e,n=10){let r=g=>(Tt(g).getDay()+6)%7,o=Xt(t,-r(t)),a=Xt(e,6-r(e)),c=[];for(let g=o;g<=a;g=Xt(g,1))if(c.push({day:g,kind:gn*7)return null;return c}var di=/^([01]?\d|2[0-3]):([0-5]\d)$/;function zr(t){let e=di.exec(t.trim());return e?+e[1]*60+ +e[2]:null}var Ce=t=>(t%1440+1440)%1440,jt=t=>`${String(Math.floor(Ce(t)/60)).padStart(2,"0")}:${String(Ce(t)%60).padStart(2,"0")}`;function Qe(t,e,n){let[r,o]=t.split("-"),a=zr(r!=null?r:""),c=zr(o!=null?o:"");if(a==null||c==null)return null;let g=e==null?0:n-e;return{from:Ce(a+g),to:Ce(c+g),yours:e!=null}}var Yr=t=>t.fromCe(Math.floor(t/60)+e);function Qr(t){let e=Tt(t);return{days:new Date(e.getFullYear(),e.getMonth()+1,0).getDate(),day:e.getDate()}}var Xr={phone:{b:'',f:'',d:''},mobile:{b:'',f:'',d:''},tablet:{b:'',f:'',d:''},computer:{b:'',f:'',d:''},router:{b:'',f:'',d:''},other:{b:'',f:'',d:""},plus:{b:'',f:'',d:''},globe:{b:'',f:'',d:''},home:{b:'',f:'',d:''},shield:{b:'',f:'',d:''},chart:{b:'',f:'',d:''},calendar:{b:'',f:'',d:''},clock:{b:'',f:'',d:''},pause:{b:'',f:'',d:''},server:{b:'',f:'',d:''},link:{b:'',f:'',d:''},key:{b:'',f:'',d:''},lock:{b:'',f:'',d:''},check:{b:'',f:'',d:''},trash:{b:'',f:'',d:''},refresh:{b:'',f:'',d:''},app:{b:'',f:'',d:null},file:{b:'',f:'',d:''}},ui=()=>Se("amnezia","").replace(/^]*>/,"").replace(/<\/svg>$/,""),pi=0;function fi(t,e="grey",n="gi"){var c;let r=(c=Xr[t])!=null?c:Xr.other,o=`gl${++pi}`,a=r.d===null?`${ui()}`:`${r.d}`;return`${r.f}${r.b}${r.b}${r.f}${r.f}${r.f}${a}`}var j=(t,e="grey",n="gi")=>_t(fi(t,e,n));function Xe(t,e,n,r){return i("div",{class:`notice ${t}`},j(e,t==="bad"?"red":"orange"),i("div",{class:"t"},n?i("b",{},n):null,i("span",{},r)))}function hi(t){var n;let e=Qe(t,(n=dt())==null?void 0:n.tz_offset,-new Date().getTimezoneOffset());return e?`${jt(e.from)}–${jt(e.to)} ${e.yours?"your time":"(router time)"}`:`${t.replace("-","–")} (router time)`}function En(t){switch(t.state){case"server_off":return["server","Server is disabled","Your devices can’t connect until it’s enabled again."];case"no_server":return["server","No server yet","You haven’t been added to one."];case"quota":return["chart","Out of data","Nothing gets through until it resets."];case"expired":return["calendar","Access ended","Your devices can’t connect until it’s extended."];case"hours":return["clock","Outside your hours",`Open ${hi(t.hours)}.`];default:return["pause","Access paused","Your devices can’t connect until it’s resumed."]}}function Jr(t){if(t.state!=="active")return Xe(t.state==="quota"||t.state==="expired"?"bad":"warn",...En(t));let e=_e(t.expires,Pt());return fe(t,e)?Xe("warn","calendar",`Access ${Wn(e)}`,`On ${pe(t.expires)}.`):null}function mi(t){let e=i("div",{class:"view"},Ct("Open the link securely"),Ht("Connection settings only travel encrypted"),i("div",{class:"center-col secure"},j("lock","blue","gi xl"),i("p",{},"This page is open without encryption. To add or set up a device, open the same link over HTTPS:")),i("a",{class:"btn accent block",href:t},F("lock"),i("span",{},"Open securely")),Kt("The browser may warn that the certificate is not trusted: it is this router’s own. Choose to continue (“Advanced” → “Proceed”)."));return e.lastElementChild.classList.add("secure-note"),{el:e,label:"Open the link securely"}}var ke=t=>ht(()=>mi(t));function ue(){let t=dr();return t?(ke(t),!0):!1}var gi={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:""},vi={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(t){let e={};for(let[n,r]of Object.entries(vi))t[n]!=null&&t[n]!==""&&(e[r]=String(t[n]));return e}function xi(t,e){var v;let n=t.amnezia,r=(v=n.obfuscation)!=null?v:{},o=u=>r[u]!=null&&r[u]!==""?String(r[u]):gi[u],a=n.host.replace(/^\[(.*)\]$/,"$1"),c={H1:o("h1"),H2:o("h2"),H3:o("h3"),H4:o("h4"),I1:o("i1"),I2:o("i2"),I3:o("i3"),I4:o("i4"),I5:o("i5"),Jc:o("jc"),Jmin:o("jmin"),Jmax:o("jmax"),S1:o("s1"),S2:o("s2"),S3:o("s3"),S4:o("s4"),...yi(r),allowed_ips:n.allowed_ips,client_ip:n.client_ip,client_priv_key:n.client_priv_key,client_pub_key:n.client_pub_key,config:t.conf.replace(/\r?\n/g,`\r
+`),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;nt.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.max(U.duration,f.duration),l=h?U:f,L=h?f:U;cancelAnimationFrame(M);let x=()=>{let C=Lt()?p:performance.now()-E,R=v();if(!R){M=0;return}r.style.left=`${H+(R[0]-H)*l.at(C)}px`,r.style.right=`${$+(R[1]-$)*L.at(C)}px`,M=C
{M||u()}).observe(o),{el:o,sync(A){A!==e&&(e=A,g(),u())}}}var oo={vpn:"amnezia",awg:"amneziawg",wg:"wireguard"},io=t=>`dl.app.${t.id}`;function ao(t){try{let e=localStorage.getItem(io(t));return e==="vpn"||e==="awg"||e==="wg"?e:null}catch{return null}}function so(t,e){try{localStorage.setItem(io(t),e)}catch{}}function Gt(t,e=!1){var a,c;let n=[i("span",{class:"b-ic"},F(t.mark)),i("span",{class:"b-t"},i("span",{class:"b-top"},t.top),i("span",{class:"b-main"},t.main)),F(t.onclick||(a=t.href)!=null&&a.startsWith("vpn:")?"chevron":"open")],r=`badge${e?" primary":""}`;if(t.onclick)return i("button",{type:"button",class:r,onclick:t.onclick},n);let o=(c=t.href)==null?void 0:c.startsWith("vpn:");return i("a",{class:r,href:t.href,target:o?null:"_blank",rel:"noopener noreferrer"},n)}function lo(t,e,n){let r=n?Zn(t):Jn(t,e);return r?r.alt?[i("div",{class:"badges2"},Gt(r),Gt(r.alt)),Kt(r.alt.why)]:[Gt(r)]:[Kt(`Get ${at[t]} on the ${er[e]} and come back here.`)]}var no=t=>i("ol",{class:"howto"},t.map(([e,n])=>i("li",{},e.replace(/ → $/," ›"),n?[" ",i("b",{},n)]:null))),Mi=(t,e)=>i("button",{type:"button",onclick:e},t);function co(t){let e=t.app(),n=at[e],r=t.pf==="ios"||t.pf==="android",o=t.same()&&r,a=v=>pt(t.key,"Key copied",v.currentTarget),c=e==="vpn"&&o&&!ln(t.pf)?Wt(he(t.cfg.filename),t.key):null;if(e==="vpn"&&o&&(ln(t.pf)||c))return[Gt(c?{top:"Then come back here and tap",main:"Send to AmneziaVPN",mark:"amnezia",onclick:()=>void c()}:{href:t.key,top:"Then come back here and tap",main:"Open in AmneziaVPN",mark:"amnezia"},!0),Kt(c?"Pick AmneziaVPN in the share sheet. Not there? ":"Nothing opened? ",Mi("Copy the key",a)," and add it in the app.")];if(e==="vpn")return[Gt({top:"The connection as one key",main:"Copy the key",mark:"copy",onclick:a},!0),no([["Open AmneziaVPN",""],["Add server › ","Insert key"],["Paste the key and connect",""]])];let g=r?Wt(t.cfg.filename,t.cfg.conf):null;return[Gt(g?{top:t.same()?`Straight into ${n}`:`Send it to the ${t.there}`,main:"Share the file",mark:"share",onclick:()=>void g()}:{top:"Then import it in the app",main:"Download the file",mark:"download",onclick:()=>Ue(t.cfg.filename,t.cfg.conf)},!0),no(tr(e,t.pf,t.cfg.filename,!!g&&t.same()))]}function uo(t){let e=t.app(),n=(o,a,c)=>i("button",{type:"button",class:"btn soft sm",onclick:c},F(o),i("span",{class:"lbl"},a));if(e==="vpn"){let o=he(t.cfg.filename),a=!!Wt(o,t.key);return[i("p",{class:"desc"},`Send it to the ${t.there} in a message or a note, then in AmneziaVPN: Add server › Insert key.`),i("div",{class:"btnrow2"},n("copy","Copy the key",c=>pt(t.key,"Key copied",c.currentTarget)),n(a?"share":"download",a?"Share as a file":"Download the key",()=>ye(o,t.key)))]}let r=!!Wt(t.cfg.filename,t.cfg.conf);return[i("p",{class:"desc"},`Send it to the ${t.there}, then import `,i("b",{},t.cfg.filename),` in ${at[e]}.`),i("div",{class:"btnrow2"},n(r?"share":"download",r?"Share the file":"Download the file",()=>ye(t.cfg.filename,t.cfg.conf)),n("copy","Copy the configuration",o=>pt(t.cfg.conf,"Configuration copied",o.currentTarget)))]}function ro(t,e){if(/^\s*\[.+\]\s*$/.test(t))return i("span",{class:"sec"},t);let n=/^(\s*[A-Za-z0-9]+\s*=)\s*(.*)$/.exec(t);if(!n)return document.createTextNode(t);let r=/^(\s*)(PrivateKey|PresharedKey)\b/.test(t);return i("span",{},i("span",{class:"k"},n[1])," ",r&&!e?i("span",{class:"mask"},"••••••••••••••••"):n[2])}function po(t){let e=!1,n=i("pre",{class:"conf"}),r=()=>n.replaceChildren(...t.conf.split(`
+`).flatMap((u,M)=>M?[`
+`,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(){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&&clearTimeout(o),document.removeEventListener("visibilitychange",M)}}var mo=t=>new Promise(e=>setTimeout(e,t));async function xo(t,e,n){t.connected(),Gr(),Ur(),await mo(400),wn(t.el)&&(e.style.overflow="hidden",_(e,[{height:`${e.offsetHeight}px`,opacity:1,filter:"none"},{height:"0px",opacity:0,filter:"blur(4px)"}],{duration:520,easing:Y,fill:"forwards"}),_(t.el,[{marginBottom:"18px"},{marginBottom:"0px"}],{duration:520,easing:Y,fill:"forwards"}),await mo(2400),wn(t.el)&&(Yt(()=>Mt({flash:n.id})),ft()))}async function Ci(t){try{return await ut(`devices/${t.id}/config`)}catch(e){return e instanceof Nt&&e.httpsUrl?ke(e.httpsUrl):wt(e.message,!0),null}}async function Je(t,e){if(ue())return;let n=async()=>{let r=await Ci(t);if(!r)return;let o=await Ln(r,r.server);ht(()=>wo(t,r,o))};e instanceof HTMLButtonElement?await zt(e,n):await n()}async function Ze(t,e){let n=await Ln(e,e.server);Ve(()=>wo(t,e,n))}function bo(t,e,n){return i("div",{class:"step"},i("span",{class:"step-n"},t),i("div",{class:"step-b"},typeof e=="string"?i("span",{class:"step-t"},e):e,n))}function ki(t,e,n){let r=t.hidden?0:t.getBoundingClientRect().height;if(t.getAnimations().forEach(g=>g.cancel()),n){t.hidden=e;return}t.style.overflow="hidden",t.hidden=!1;let o=e?0:t.getBoundingClientRect().height,[a,c]=e?[1,0]:[0,1];_(t,[{height:`${r}px`,opacity:a,filter:`blur(${4-a*4}px)`},{height:`${o}px`,opacity:c,filter:`blur(${4-c*4}px)`}],{duration:U.duration,easing:U.easing}).onfinish=()=>{t.style.overflow="",t.hidden=e}}function wo(t,e,n){var ot,it;let r=He(),o=Xn(cr()),a=t.kind==="phone"||t.kind==="tablet",c=t.kind==="router",g=Qn(t.kind,r),v=g?"same":c?"router":a?"away":"pc-away",u=ar(t.kind),M=o.filter(G=>!c||G.id!=="vpn"),b=(ot=ao(t))!=null?ot:c?"awg":"vpn";M.some(G=>G.id===b)||(b=M[0].id);let A={d:t,cfg:e,key:n,pf:r,there:u,app:()=>b,same:()=>g},O=[],B=()=>{if(M.length<2)return null;let G=eo(M.map(V=>({value:V.id,label:V.name,icon:oo[V.id]})),b,V=>{b=V,so(t,V),O.forEach($t=>$t.sync(V)),qr(p)});return O.push(G),G.el},P=i("span",{class:"step-t"}),H=i("div",{class:"step-box"}),$=i("div",{class:"step-box"}),d=i("div",{class:"step-box"}),m=i("div",{class:"step-box"}),s=null,h=null,f=null,E=v==="away"?ho(()=>({...b==="vpn"?{text:n,msg:"Key copied",file:he(e.filename)}:{text:e.conf,msg:"Configuration copied",file:e.filename},app:at[b]})):null;function p(){Z(P,c?`Get ${at[b]} on the router`:`Get ${at[b]}`,void 0,{whole:!0}),qe(H,lo(b,r,c)),c?$.firstChild||Rt($,po(e)):qe($,co(A));let G=b==="vpn"?Zr(n):e.conf;s&&h&&s.el.isConnected?f!==b&&(s.swap(G),h.set(b)):(h=fo(b),s=vn(G,[h.el]),d.replaceChildren(s.el)),f=b,qe(m,uo(A)),E==null||E.sync()}p();let l=nr(Zt(),t.id),L=()=>[a?vn(l,[i("span",{},"Point its camera at the code: the link opens there.")]).el:i("p",{class:"desc"},`Open this link on the ${u} to set it up there.`),re(l)],x=()=>bo("1",P,[B(),H]),C=()=>bo("2",c?"Import the configuration":"Add the connection",[$]),R=i("div",{class:"setup"});if(jn(navigator.userAgent)&&R.appendChild(Xe("warn","shield",null,"Open this page in Safari or Chrome: the store opens from here, but the app handoff does not.")),v==="same"){let G=i("div",{class:"steps-wrap"},i("div",{class:"steps-gap"}),x(),C()),V=qt([{icon:j("link"),title:`Not on the ${u} right now?`,body:L()}],{inset:!0,onToggle:($t,lt,rn)=>ki(G,lt,rn)});R.append(V.el,G)}else v==="router"?R.append(x(),C()):v==="away"?R.appendChild(qt([{icon:j("link"),title:`Open your link on the ${u}`,body:L()},{icon:j("app"),title:"Already has the app",body:[B(),d]}],{inset:!0,open:1}).el):R.appendChild(qt([{icon:j("link"),title:`Open your link on the ${u}`,body:L()},{icon:j("key"),title:"Copy or save the connection",body:[B(),m]}],{inset:!0,open:0}).el);let I=go(t),z=!1;Fr(yo(t,()=>{z||(z=!0,xo(I,R,t))},I.gaveUp)),Yt(()=>Mt());let Q=v==="same"?"Two steps, about a minute":c?"The packages and the file for OpenWrt":`The app goes on the ${u}.`;return{el:i("div",{class:"view"},Ct(`Set up ${t.name}`,{acts:!!E}),Ht(Q),I.el,R),label:`Set up ${t.name}`,acts:(it=E==null?void 0:E.el)!=null?it:null}}var mt=navigator.userAgent,ko=/iPad/.test(mt)||/Macintosh/.test(mt)&&navigator.maxTouchPoints>1;function Le(){return ko||/Tablet/i.test(mt)||/Android/.test(mt)&&!/Mobile/.test(mt)?"tablet":/Android|iPhone|Mobile/i.test(mt)?"phone":"computer"}var Ei=[[/^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"]],Tn="",Li=(async()=>{var e;let t=navigator.userAgentData;if(!t||!/Android/.test(mt))return"";try{let n=((e=(await t.getHighEntropyValues(["model"])).model)!=null?e:"").trim();if(!n||n==="K")return"";let r=Ei.find(([o])=>o.test(n));Tn=r?`${r[1]} (${n})`:/^SM-/.test(n)?`Galaxy ${n}`:n}catch{}return Tn})();function Ti(t){return/iPhone/.test(mt)?"iPhone":ko?"iPad":/Android/.test(mt)?Tn||(t==="tablet"?"Android tablet":"Android phone"):/CrOS/.test(mt)?"Chromebook":/Mac OS X/.test(mt)?"Mac":/Windows/.test(mt)?"Windows PC":/Linux/.test(mt)?"Linux PC":sn[t]}var Mo={computer:"PC",mobile:"Mobile",router:"Router",other:"Other"},Ee=t=>t==="phone"||t==="tablet"?"mobile":t,Co=t=>t!=="mobile"?t:Le()==="tablet"?"tablet":"phone";function Te(){let t=dt();if(!(!t||t.locked)){if(!t.can_add)return wt(`You have reached your limit of ${t.person.device_limit} devices`,!0);ue()||ht(Ai)}}function Ai(){let t=dt(),e=t.person,n=["computer","mobile","router","other"].filter(d=>t.kinds.some(m=>Ee(m)===d)),r=n.includes(Ee(Le()))?Ee(Le()):n[0],o=!1,a=new Set(e.devices.map(d=>d.name.toLowerCase())),c=d=>{let m=d===Ee(Le())?Ti(Co(d)):d==="mobile"?"Phone":sn[d];if(!a.has(m.toLowerCase()))return m;for(let s=2;s<20;s++)if(!a.has(`${m} ${s}`.toLowerCase()))return`${m} ${s}`;return m},g=i("div",{class:"kinds",role:"radiogroup","aria-label":"What is it?"});g.style.setProperty("--n",String(n.length));let v=n.map(d=>{let m=i("button",{type:"button",class:"kind",role:"radio","aria-label":Mo[d],onclick:()=>O(d)},i("span",{class:"kind-tile"},j(d,"blue")),i("span",{class:"kind-lbl"},Mo[d]));return g.appendChild(m),m}),u=i("input",{type:"text",maxlength:48,required:!0,"aria-label":"Name",autocomplete:"off"}),M=i("button",{class:"go ready",type:"submit","aria-label":"Create connection"},F("arrow")),b=i("p",{class:"hint bad-t",hidden:!0}),A=d=>{if(!b.hidden)return Z(b,d);b.textContent=d,b.hidden=!1,_(b,[{opacity:0,transform:"translateY(-4px)"},{opacity:1,transform:"none"}],{duration:220,easing:Y})};u.value=c(r),u.addEventListener("input",()=>{o=!0,M.classList.toggle("ready",!!u.value.trim()),b.hidden=!0}),Li.then(()=>{!o&&r===Ee(Le())&&(u.value=c(r))});function O(d){r=d,v.forEach((m,s)=>{let h=n[s]===d;m.classList.toggle("on",h),m.setAttribute("aria-checked",String(h))}),o||(u.value=c(d),M.classList.add("ready"))}O(r);let B=i("form",{class:"field",autocomplete:"off"},u,M);B.addEventListener("submit",d=>{d.preventDefault();let m=u.value.trim();if(m){if(a.has(m.toLowerCase()))return A("You already have a device with this name.");zt(M,async()=>{try{let s=await ut("devices",{name:m,kind:Co(r)});xt(s.state),Mt({pop:s.id});let h=s.state.person.devices.find(f=>f.id===s.id);await Ze(h,s.config)}catch(s){if(s instanceof Nt&&s.httpsUrl)return ke(s.httpsUrl);A(s.message)}})}});let P=i("button",{type:"button",class:"btn soft block",onclick:()=>Ve(Si)},F("qr"),i("span",{},"Add it from the device")),H=e.device_limit-e.devices.length,$=i("div",{class:"view"},Ct("Add a device"),Ht(`${H} of ${e.device_limit} slots free`),g,Kt("Phones and tablets get a smaller packet size that suits mobile networks."),B,b,i("div",{class:"or"},"OR"),P);return $.querySelector(".hint").classList.add("kinds-note"),{el:$,label:"Add a device"}}function Si(){let t=or(Zt());return{el:i("div",{class:"view"},Ct("Open on the device",{back:!0}),Ht("Point its camera at the code: your page opens there with this device ready to add."),xe(t,!0),re(t)),label:"Open on the device"}}function Eo(t){let e=i("button",{type:"button",class:`btn ${t.cls}`,onclick:r=>zt(r.currentTarget,t.run)},i("span",{},t.action));return{el:i("div",{class:"view"},i("div",{class:"center-col ask"},j(t.icon,t.tone,"gi xl"),i("h3",{},t.title),i("p",{},t.text),i("div",{class:"btnrow"},i("button",{type:"button",class:"btn soft",onclick:()=>ft()},"Cancel"),e))),label:t.title,asks:!0}}function Lo(t){ht(()=>{let e=i("input",{type:"text",maxlength:48,"aria-label":"Device name",autocomplete:"off"});e.value=t.name;let n=i("button",{class:"go",type:"submit","aria-label":"Save"},F("check"));e.addEventListener("input",()=>n.classList.toggle("ready",!!e.value.trim()&&e.value.trim()!==t.name));let r=i("form",{class:"field",autocomplete:"off"},e,n);return r.addEventListener("submit",o=>{o.preventDefault();let a=e.value.trim();!a||a===t.name||zt(n,async()=>{try{let c=await ut(`devices/${t.id}`,{action:"rename",name:a});xt(c.state),Yt(()=>{Mt(),wt("Renamed")}),ft()}catch(c){wt(c.message,!0)}})}),setTimeout(()=>e.select(),60),{el:i("div",{class:"view"},Ct(`Rename ${t.name}`),r),label:`Rename ${t.name}`}})}function An(t){var n;if(ue())return;let e=((n=dt())==null?void 0:n.here)===t.id;ht(()=>Eo({icon:"refresh",tone:"orange",title:`Reconnect ${t.name}?`,text:e?"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()=>{var r;try{let o=await ut(`devices/${t.id}`,{action:"reconnect"});xt(o.state),Mt(),await Ze((r=o.state.person.devices.find(a=>a.id===t.id))!=null?r:{...t,handshake:0},o.config)}catch(o){wt(o.message,!0)}}}))}function To(t){ht(()=>Eo({icon:"trash",tone:"red",title:`Remove ${t.name}?`,text:"Its connection stops working at once. You can add it again later.",action:"Remove",cls:"red",run:async()=>{try{let e=await ut(`devices/${t.id}`,{action:"delete"});xt(e.state),Yt(()=>{let n=document.querySelector(`.dev[data-id="${CSS.escape(t.id)}"]`),r=()=>{Mt(),wt("Device removed")};if(!n)return r();_(n,[{opacity:1,transform:"none",filter:"none"},{opacity:0,transform:"scale(.9)",filter:"blur(6px)"}],{duration:220,easing:J,fill:"forwards"}).onfinish=r}),ft()}catch(e){wt(e.message,!0)}}}))}var Sn=(t,e)=>t.access!=="internet"&&t.state==="active"&&!e.disabled;function $i(t,e){return t.disabled?["","Disabled"]:t.config_stale&&t.handshake?["warn-t","Settings changed"]:t.online&&e.state==="quota"?["warn-t","Connected, no data left"]:t.online&&e.state==="hours"?["warn-t","Connected, outside your hours"]:t.online?["ok-t","Connected"]:t.handshake?["",`Last connected ${Un(t.handshake,te())}`]:["warn-t","Not set up yet"]}function _i(t,e){return[...Sn(e.person,t)?[{label:"Copy IP address",icon:"copy",run:()=>pt(t.address,"IP address copied")},...t.hostname?[{label:"Copy local address",icon:"home",run:()=>pt(t.hostname,"Address copied")}]:[],null]:[],...t.disabled?[]:[{label:"Rename",icon:"edit",run:()=>Lo(t)},{label:"Reconnect",icon:"refresh",tone:"warn",run:()=>An(t)},{label:"Remove",icon:"trash",tone:"bad",run:()=>To(t)}]]}function Pi(t){return t===0?"Today":t===1?"Yesterday":Tt(Xt(Pt(),-t)).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"})}function Di(t,e){let n=t.spark.reduce((c,g)=>c+g,0),r=i("span",{class:"use-lbl"},"Last 7 days"),o=i("span",{class:"use-val num","data-t":`${t.id}:use`},ct(n)),a;if(e)a=i("button",{type:"button",class:"upd-pill","aria-label":"Update the connection",title:"Its settings changed: update the connection",onclick:()=>An(t)},F("refresh"),i("span",{},"Update"));else{let c=Math.max(1,...t.spark);a=i("div",{class:"spark"}),t.spark.forEach((g,v)=>{let u=t.spark.length-1-v,M=i("i",{class:u===0?"today":""});M.style.height=`${Math.max(3,Math.round(g/c*34))}px`,M.addEventListener("pointerenter",()=>{bt(r,Pi(u)),bt(o,ct(g))}),M.addEventListener("pointerleave",()=>{bt(r,"Last 7 days"),bt(o,ct(n))}),a.appendChild(M)})}return i("div",{class:"dev-use"},i("div",{class:"use-txt"},r,o),a)}function Bi(t,e){let n=e.person,r=!!e.locked,o=e.here===t.id,[a,c]=o?["here-t","This device"]:$i(t,n),g=!t.handshake&&!t.disabled,v=t.config_stale&&!g&&!r&&!t.disabled,u=!o&&t.handshake&&!t.online&&!t.disabled&&!t.config_stale?new Date(t.handshake*1e3).toLocaleString("en-GB"):v?"Settings changed, update needed":c,M=_i(t,e),b=r||!M.length?null:i("button",{type:"button",class:"knob more","aria-label":`${t.name} options`,"aria-haspopup":"menu","aria-expanded":"false"},F("more"));return b==null||b.addEventListener("click",()=>Or(b,M)),i("article",{class:`dev${o?" is-here":""}${t.disabled?" off":""}`,"data-id":t.id},i("div",{class:"dev-top"},j(t.kind,o?"blue":"grey"),i("div",{class:"dev-id"},i("span",{class:"dev-name","data-t":`${t.id}:name`},t.name),i("span",{class:`dev-stat ${a}`,title:u,"data-t":`${t.id}:stat`},c)),b),g&&r?null:g?i("button",{type:"button",class:"btn tint block setup-btn","aria-label":`Set up ${t.name}`,onclick:A=>Je(t,A.currentTarget)},F("qr"),i("span",{},"Connect")):Di(t,v))}var Hi=t=>i("div",{class:"dev first","data-id":"first"},j("plus","blue"),i("b",{},"Add your first device"),i("p",{},"Two steps, about a minute: get the app, then add the connection."),i("button",{type:"button",class:"btn accent block",onclick:Te},F("plus"),i("span",{},t?"Add this phone":"Add this device"))),Oi=()=>i("button",{type:"button",class:"dev add","data-id":"add",onclick:Te},j("plus"),i("span",{},"Add device"));function Ao(){return i("section",{class:"devices",id:"devices","aria-label":"Your devices"},i("div",{class:"sec-head"},i("h2",{},"Your devices"),i("span",{class:"aside num"})),i("div",{class:"dgrid"}),i("p",{class:"note-s limit",hidden:!0}))}function So(t,e,n={}){let r=e.person,o=t.querySelector(".dgrid"),a=o.childElementCount>0,c=new Map([...o.querySelectorAll("[data-id]")].map($=>[$.dataset.id,$.getBoundingClientRect()])),g=Fe(o),u=Pe(r.devices).sort(($,d)=>+(d.id===e.here)-+($.id===e.here)).map($=>Bi($,e)),M=e.locked?0:Math.max(0,r.device_limit-r.devices.length),b=matchMedia("(max-width: 959px)").matches||/Android|iPhone|iPad/.test(navigator.userAgent);!r.devices.length&&M?u.push(Hi(b)):e.can_add&&!e.locked&&u.push(Oi()),o.classList.toggle("empty",!r.devices.length),o.replaceChildren(...u);for(let $ of u){let d=c.get($.dataset.id),m=$.getBoundingClientRect();$.dataset.id===n.pop?_($,[{opacity:0,transform:"scale(.9)",filter:"blur(6px)"},{opacity:1,transform:"none",filter:"none"}],{duration:kt.duration,easing:kt.easing}):d&&(d.left!==m.left||d.top!==m.top)?_($,[{transform:`translate(${d.left-m.left}px, ${d.top-m.top}px)`},{transform:"none"}],{duration:U.duration,easing:U.easing}):!d&&a&&_($,[{opacity:0,transform:"scale(.9)",filter:"blur(6px)"},{opacity:getComputedStyle($).opacity,transform:"none",filter:"none"}],{duration:U.duration,delay:60,easing:U.easing,fill:"backwards"}),$.dataset.id===n.flash&&$.animate([{boxShadow:"inset 0 0 0 1.5px var(--ok)"},{boxShadow:"inset 0 0 0 1.5px transparent"}],{duration:1800,easing:"ease-out"})}a&&Ke(o,g);let A=t.querySelector(".sec-head .aside"),O=`${r.devices.length} of ${r.device_limit}`;a?Z(A,O):A.textContent=O,A.classList.toggle("warn-t",r.devices.length>r.device_limit);let B=t.querySelector(".limit"),P=B.hidden,H=e.can_add||!!e.locked;if(B.textContent=`You have reached your limit of ${r.device_limit} devices. Remove one to add another.`,B.getAnimations().forEach($=>$.cancel()),a&&!P&&H){let $=_(B,[{opacity:1,filter:"none"},{opacity:0,filter:"blur(4px)"}],{duration:200,easing:J,fill:"forwards"});$.onfinish=()=>{B.hidden=!0,$.cancel()}}else B.hidden=H,a&&P&&!H&&_(B,[{opacity:0,transform:"translateY(6px)",filter:"blur(4px)"},{opacity:1,transform:"none",filter:"none"}],{duration:420,easing:Y})}var $n=t=>i("p",{class:"desc"},t),en=(t,e)=>`${(t/e*100).toFixed(2)}%`;function Ri(t){let e=(n,r,o,a)=>i("div",{class:`reach-tile${n?"":" off"}`},j(r,n?"blue":"grey","gi rt-ic"),i("b",{},o),i("span",{class:"rt-sub"},n?a:"Not included"),i("span",{class:"rt-mark","aria-label":n?"Included":"Not included"},F(n?"check":"minus")));return i("div",{class:"reach2"},e(t!=="internet","home","Home network","Devices at home"),e(t!=="lan","globe","Internet","Through the router"))}function Ni(t,e){let n=Pe(t.devices).filter(c=>c.hostname&&Sn(t,c));if(!n.length)return[];let r=n[0].hostname,o=r.indexOf("."),a=o>0?r.slice(o):"";return[i("span",{class:"lbl-s"},e?"Devices at home and on this VPN reach yours as ":"Other devices at home reach yours as ",i("span",{class:"mono"},`name${a}`)),i("div",{class:"names"},n.map(c=>{let g=c.hostname.indexOf(".");return i("button",{type:"button",class:"namechip",title:c.name,"aria-label":`Copy ${c.hostname}`,onclick:v=>pt(c.hostname,"Address copied",v.currentTarget)},i("span",{},g>0?[c.hostname.slice(0,g),i("span",{class:"faint"},c.hostname.slice(g))]:c.hostname),F("copy"))}))]}function Ii(t){let e=2*Math.PI*6,n=t>=100?" bad":t>=90?" warn":"";return _t(``)}function Fi(t){let e=i("i",{class:t>=100?"bad":t>=90?"warn":""});return e.style.width=`${t.toFixed(1)}%`,i("div",{class:"meter"},e)}function Ki(t,e,n){var B,P;let{days:r,day:o}=Qr(Pt()),a=(B=t.month_days)!=null?B:[],c=Math.max(1,...a),g=H=>Tt(`${Pt().slice(0,8)}${String(H).padStart(2,"0")}`).toLocaleDateString("en-GB",{day:"numeric",month:"short"}),v=i("b",{class:"num","data-t":"m-used"},ct(e)),u=i("span",{}," used"),M=i("span",{class:"mread"},v,u),b=i("div",{class:"mbars"});for(let H=0;H=o){b.appendChild(i("i",{class:"future"}));continue}let $=(P=a[H])!=null?P:0,d=i("i",{class:H===o-1?"today":""});d.style.height=`${Math.max(3,Math.round($/c*64))}px`,d.addEventListener("pointerenter",()=>{bt(v,ct($)),bt(u,` on ${g(H+1)}`)}),d.addEventListener("pointerleave",()=>{bt(v,ct(e)),bt(u," used")}),b.appendChild(d)}let A=i("span",{class:"td"},"Today");A.style.left=en(o-.5,r);let O=i("div",{class:"month-axis"},i("span",{class:o<=4?"hide":""},g(1)),A,i("span",{class:o>=r-3?"hide":""},g(r)));return i("div",{class:"month"},b,O,i("div",{class:"month-read"},M,i("span",{class:`num${t.state==="quota"?" bad-t":""}`,"data-t":"m-left"},t.quota_limit?`${ct(Math.max(0,t.quota_limit-e))} left`:"No limit")),t.quota_limit?Fi(n):null)}function qi(t,e){let n=a=>Tt(a).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short"}),r=Vr(Pt(),t.expires),o=r?i("div",{class:"cal","aria-hidden":"true"},i("div",{class:"cal-h"},["M","T","W","T","F","S","S"].map(a=>i("span",{},a))),i("div",{class:"cal-g"},r.map((a,c)=>{let g=i("i",{class:a.kind,title:n(a.day)});return g.style.setProperty("--i",String(c)),g}))):null;return i("div",{class:`until${fe(t,e)?" soon":""}`},i("div",{class:"until-num"},i("b",{class:"num"},String(e)),i("span",{},`${e===1?"day":"days"} left`),i("span",{class:"until-sub"},`Ends ${n(t.expires)}`)),o)}function Gi(t,e){let n=-new Date().getTimezoneOffset(),r=Qe(t,e,n);if(!r)return null;let o=jr(te(),r.yours?n:e!=null?e:n),a=Yr(r),c=a.some(([u,M])=>o>=u&&oi("span",{},u))))}function Ui(t,e=1){let n=t.person,r=n.quota_used||n.month[0]+n.month[1],o=n.quota_limit?Math.min(100,r/n.quota_limit*100):0,a=n.quota_period==="total"&&!!n.quota_gb,c=_e(n.expires,Pt()),g=n.expires?i("span",{class:"until-val"},i("span",{class:"num","data-t":"until-date"},pe(n.expires).replace(/ \d{4}$/,"")),c!=null?i("span",{class:`num ${c<0?"bad-t":fe(n,c)?"warn-t":"ok-t"}`,"data-t":"until-left"},c>=0?`${c} day${c===1?"":"s"}`:"ended"):null):i("span",{},"No end date"),v=[n.expires?c!=null&&c<0?$n(`It ended on ${pe(n.expires)}.`):qi(n,c!=null?c:0):null,n.hours?Gi(n.hours,t.tz_offset):null];return qt([{icon:j(n.access==="internet"?"globe":n.access==="lan"?"home":"shield"),title:zn[n.access],body:[Ri(n.access),...Ni(n,!!t.server.device_mesh)]},{icon:j("chart"),title:a?"Data used":"Data this month",val:i("span",{class:"data-val"},n.quota_limit?Ii(o):null,i("span",{class:"num","data-t":"data-val"},`${ct(r)}${n.quota_limit?` / ${ct(n.quota_limit)}`:" · no limit"}`)),valHide:!0,body:[a?$n(`${ct(r)} of ${ct(n.quota_limit)} in total.`):Ki(n,r,o),$n(n.quota_limit?a?"A total for your whole access, it does not reset.":"Resets on the 1st.":"No data limit. The count starts again on the 1st.")]},{icon:j("calendar"),title:"Access until",val:g,valHide:!!n.expires&&(c!=null?c:0)>=0,body:v}],{open:e})}function $o(){return i("section",{class:"access",id:"access","aria-label":"Your access"},i("div",{class:"sec-head"},i("h2",{},"Your access")),i("div",{class:"acc-slot"}))}var tn=null;function _o(t,e){let n=Ui(e,tn?tn.openIndex():1),r=Fe(t);t.querySelector(".acc-slot").replaceChildren(n.el),tn&&Ke(t,r),tn=n}Kn(document.documentElement);var nn=document.getElementById("app"),Ot=null,_n=!1;function Po(){let t=[...nn.querySelectorAll(".crumbs, .notice, .sec-head, .dgrid > *, .note-s:not([hidden]), .acc-slot .acc-row, .gone")],e=t.map(n=>getComputedStyle(n).opacity);t.forEach((n,r)=>_(n,[{opacity:0,transform:"translateY(10px)",filter:"blur(4px)"},{opacity:e[r],transform:"none",filter:"none"}],{duration:520,delay:60+r*40,easing:Y,fill:"backwards"})),nn.querySelectorAll(".logo .sun").forEach(n=>_(n,[{transform:"translateY(7px)"},{transform:"none"}],{duration:900,delay:150,easing:Y,fill:"backwards"})),_n=!0}function Do(t={}){let e=dt();if(!e)return;if(e.person.state==="paused"){document.title=Ut();let[r,o,a]=En(e.person);return Pn(r,o,a,!1,"orange")}let n=Mn(nn);Cn(!1),kn(),document.title=Ut(),Ot||(Ot={notice:i("div",{class:"notice-slot"}),devices:Ao(),access:$o()},Rt(n,Ot.notice,i("div",{class:"cols"},Ot.devices,Ot.access))),Rt(Ot.notice,Jr(e.person)),So(Ot.devices,e,t),_o(Ot.access,e),_n||Po()}pr(Do);function Pn(t,e,n,r=!1,o="grey"){Ot=null;let a=Mn(nn);Cn(!0),kn(r,!0),Rt(a,i("div",{class:"gone"},j(t,o),i("h1",{},e),i("p",{},n))),_n||Po()}function Bo(){xt(null),ft(!0),Pn("key","This link no longer works","Ask for a new one.",!0)}function Ho(){let t=dt(),e=rr(location.hash),n=ir(location.hash);if(!t||!e&&!n)return;if(history.replaceState(null,"",location.pathname+location.search),n)return Te();let r=t.person.devices.find(o=>o.id===e);r&&!r.handshake&&!r.disabled&&!t.locked&&Je(r)}addEventListener("hashchange",Ho);async function Wi(){try{xt(await ut("state")),!St()&&!be()&&Do(),Ho()}catch(t){Oe(t)?Bo():dt()||Pn("server","The page could not load",t.message)}}document.addEventListener("keydown",t=>{t.key==="Escape"&&(be()?Bt(!0):St()&&ft(!0))});!Jt||!lr?Bo():Wi();})();
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
index ddacfef..7ca8097 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/awg.uc
@@ -6,7 +6,7 @@
import { readfile, stat, unlink } from 'fs';
import {
- q, sh, sh_out, rand_int, rand_bytes, valid_key, ip2int, translit, ensure_dir, write_file, read_json, write_json, lock, unlock,
+ 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
} from 'dawnline.util';
import * as core from 'dawnline.core';
@@ -336,25 +336,6 @@ export function obf_neutral(o) {
return true;
};
-/*
- * The .conf file name doubles as the tunnel name in WireGuard apps (15
- * characters at most): the device first, so a person's devices stay apart,
- * and a number when the cut would still make two of them alike.
- */
-function conf_filename(m, p, dev) {
- let label = (d) => trim(substr(trim(replace(lc(translit(d.name + '-' + p.id)), /[^a-z0-9]+/g, '-'), '-'), 0, 15), '-');
- let order = sort(map(p.devices, (id) => m.devices[id]),
- (a, b) => (a.created - b.created) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
- let seen = {};
- for (let d in order) {
- let l = label(d);
- let n = seen[l] = (seen[l] ?? 0) + 1;
- if (d.id == dev.id)
- return (n > 1 ? trim(substr(l, 0, 15 - length(`-${n}`)), '-') + `-${n}` : l) + '.conf';
- }
- return label(dev) + '.conf';
-}
-
/**
* The junk a device sends is its own: within the preset's own ranges, the
* count and sizes are shifted a little by the device (deterministic, so the
@@ -423,7 +404,8 @@ export function client_config(m, dev) {
name: dev.name,
person: p.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',
has_private_key: dev.private_key != '',
amnezia: {
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
index f95b9a7..42a9889 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/core.uc
@@ -81,7 +81,6 @@ export function load(c) {
portal_alt: g('portal_alt'),
portal_cert: g('portal_cert'),
portal_key: g('portal_key'),
- portal_title: g('portal_title'),
// Where unknown portal links go instead of a bare 404 (empty = 404).
portal_redirect: g('portal_redirect'),
default_device_limit: g('default_device_limit'),
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc
index 270f1f6..d5016ac 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/migrate.uc
@@ -57,6 +57,14 @@ export function uhttpd() {
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
* `settings.migrated` (a list), so they run exactly once.
@@ -101,4 +109,5 @@ export function run() {
word_codes();
uhttpd();
auto_mtu();
+ portal_title();
};
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc
index b036ae4..421bfdf 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/portal.uc
@@ -29,7 +29,7 @@
// that answers anything not shaped like a link (its not_found() twin).
import { stat, readfile } from 'fs';
-import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, tunnel_name, VERSION, RUN_DIR } from 'dawnline.util';
+import { read_json, write_json, ensure_dir, lock, unlock, cloudflare_ip, ip2int, today, VERSION, RUN_DIR } from 'dawnline.util';
import * as core from 'dawnline.core';
import * as awg from 'dawnline.awg';
import * as live from 'dawnline.live';
@@ -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.
const LOCKED = {
- paused: 'Your access is paused by the admin.',
- expired: 'Your access has ended. Ask the admin to extend it.',
+ paused: 'Your access is paused.',
+ expired: 'Your access has ended.',
};
function html_escape(s) {
@@ -241,11 +241,16 @@ function rate_action(r) {
/* ---------- 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. */
function shell(r) {
// The build's time joins the version so every update busts the hour-long asset cache.
let v = `?v=${VERSION}.${stat(`${ASSETS}/portal.js`)?.mtime ?? 0}`;
- let base = r.base, title = r.title;
+ let base = r.base, title = place(r);
headers(r, '200 OK', {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self'; " +
@@ -338,17 +343,24 @@ function need_https(r) {
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. */
function state(r) {
let m = r.m, person = r.person;
let usage = core.load_usage();
let v = view.person_view(m, person, usage, live.dump(m), view.states(m, usage));
v.state = person_state(m, person, usage);
+ // 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];
// The device this page was opened from, through the tunnel or beside it.
let here = view.device_here(v.devices, r.peer);
return {
- title: r.title,
person: v,
here,
server: {
@@ -367,6 +379,8 @@ function state(r) {
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,
};
}
@@ -383,15 +397,6 @@ function api_state(r) {
send_json(r, '200 OK', state(r));
}
-/**
- * A configuration as the person gets it: the file, and so the tunnel the apps
- * name after it, is the server's name. The admin's downloads keep the device
- * in the name: one browser fetches many of them.
- */
-function own_config(c) {
- return c ? { ...c, filename: `${tunnel_name(c.server)}.conf` } : c;
-}
-
function api_add(r) {
need_open(r);
need_https(r);
@@ -401,7 +406,7 @@ function api_add(r) {
rate_action(r);
let res = guard(r, () => devices.add(r.person.id, b.name, b.kind, { by: 'portal', public_key: b.public_key }));
reload(r);
- send_json(r, '200 OK', { id: res.id, config: own_config(res.config), state: state(r) });
+ send_json(r, '200 OK', { id: res.id, config: res.config, state: state(r) });
}
function api_config(r, id) {
@@ -409,7 +414,7 @@ function api_config(r, id) {
need_open(r);
need_https(r);
awg.mark_issued(r.m, d.id);
- send_json(r, '200 OK', own_config(awg.client_config(r.m, d)));
+ send_json(r, '200 OK', awg.client_config(r.m, d));
}
/** POST /devices/ { action }: what each action does; the answer carries the new state. */
@@ -424,7 +429,7 @@ const ACTIONS = {
if (!devices.ready())
fail(r, '503 Service Unavailable', NOT_READY);
let config = guard(r, () => devices.reconnect(d.id, { by: 'portal', person: r.person.id, defer: d.address == r.peer }));
- return { config: own_config(config) };
+ return { config };
},
'delete': (r, d, b) => {
guard(r, () => devices.remove(d.id, { by: 'portal', person: r.person.id }));
@@ -490,7 +495,6 @@ export function handle(io) {
method: env.REQUEST_METHOD ?? 'GET',
peer: env.REMOTE_ADDR ?? '',
buckets: buckets(env),
- title: m.settings.portal_title || 'Dawnline',
// The port in the visitor's address bar ([v6]:port, name:port, or the default).
hsts: https && (match(host, /:([0-9]+)$/)?.[1] ?? '443') == '443',
person: null,
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
index d7acdef..6709dbf 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/schema.uc
@@ -107,9 +107,9 @@ export function to_int(v, dflt, lo, hi) {
/* ---------- 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;
- * 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 = {
portal_enabled: { type: 'bool', dflt: false, restart: true },
@@ -117,7 +117,6 @@ export const SETTINGS = {
portal_alt: { type: 'hosts', dflt: [], restart: true, msg: 'Other addresses must be hostnames or IP addresses.' },
portal_port: { type: 'int', dflt: 8443, min: 1, max: 65535, restart: true,
msg: 'Choose a free port between 1 and 65535 (not 22, 53, 80 or 443).' },
- portal_title: { type: 'text', dflt: 'Dawnline', max: 64, msg: 'Portal title: up to 64 characters on one line.' },
portal_redirect: { type: 'url', dflt: '', msg: 'Redirect must be a full http:// or https:// address.' },
portal_cert: { type: 'file', dflt: '', restart: true },
portal_key: { type: 'file', dflt: '', restart: true },
@@ -226,10 +225,6 @@ export function validate(key, val) {
if (!match(val, /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/))
bad(spec, key);
}
- else if (t == 'text') {
- if (ulength(val) > spec.max || match(val, /[[:cntrl:]]/))
- bad(spec, key);
- }
return val;
};
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc
index b51c63f..e5e2f55 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/util.uc
@@ -4,7 +4,7 @@
import { open, readfile, writefile, rename, mkdir, stat, unlink, popen, lsdir } from 'fs';
-export const VERSION = '0.9.0';
+export const VERSION = '0.10.0';
/** GitHub repository with Dawnline releases (updates and the installer). */
export const REPO = 'tickcount/luci-app-dawnline';
export const RUN_DIR = '/var/run/dawnline';
diff --git a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc
index cf8e050..a697fa2 100644
--- a/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc
+++ b/package/luci-app-dawnline/root/usr/share/ucode/dawnline/view.uc
@@ -16,6 +16,11 @@ export function spark(rec, n) {
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. */
function config_stale(m, d) {
m._issued ??= awg.issued();
diff --git a/scripts/capture-screenshots.mjs b/scripts/capture-screenshots.mjs
index 7fda3c1..a217797 100755
--- a/scripts/capture-screenshots.mjs
+++ b/scripts/capture-screenshots.mjs
@@ -10,11 +10,13 @@
//
// scripts/capture-screenshots.mjs [--router https://router.lan] [--person id]
// [--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);
// --name does the same for a person's name in any case, and for their initials.
// Public IPv4 addresses are always swapped for documentation ones (203.0.113.x).
+// --demo shows a made-up cast instead of the router's people (scripts/screenshot-demo.mjs):
+// the router's answers are rewritten in the headless browser on their way to the page.
import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -22,12 +24,20 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createInterface } from 'node:readline';
+import { demoRpc } from './screenshot-demo.mjs';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const RAW = join(ROOT, 'docs', 'screenshots', 'raw');
const SCALE = 2;
-const args = { router: 'https://outline.lan', person: '', mask: [], names: [], only: [] };
+const args = {
+ router: 'https://outline.lan',
+ person: '',
+ mask: [],
+ names: [],
+ only: [],
+ demo: false,
+};
for (let i = 2; i < process.argv.length; i++) {
const a = process.argv[i];
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 === '--name') args.names.push(v().split('=', 2));
else if (a === '--only') args.only = v().split(',');
+ else if (a === '--demo') args.demo = true;
else die(`unknown argument ${a}`);
}
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)}`,
width: 1400,
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: `(() => {
- 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) => {
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 };
})()`,
},
- {
- name: 'access',
- url: () => `${LUCI}/server?section=access`,
- width: 1400,
- ready: 'section.dl-ifcard details',
- // The home network card alone, its folded lists closed.
- prep: `(() => {
- const card = [...document.querySelectorAll('section.dl-ifcard')].find((s) => s.querySelector('details'));
- card.querySelectorAll('details[open]').forEach((d) => (d.open = false));
- card.setAttribute('data-shot', '');
- })()`,
- clip: `(() => {
- const r = document.querySelector('[data-shot]').getBoundingClientRect();
- return { x: r.left - 12, y: r.top - 12, width: r.width + 24, height: r.height + 24 };
- })()`,
- },
{
name: 'portal',
url: (s) => s.portal,
@@ -156,7 +162,17 @@ const MASK = `((pairs, inits) => {
if (!doc.has(m)) doc.set(m, '203.0.113.' + (24 + doc.size));
return doc.get(m);
};
- const swap = (s) => pairs.reduce((t, [a, b]) => t.split(a).join(b), s).replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, ip);
+ // 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);
for (let n; (n = w.nextNode()); ) {
const ini = inits.find(([a]) => n.nodeValue.trim() === a);
@@ -203,6 +219,7 @@ async function connect(wsUrl) {
let id = 0;
const pending = new Map();
const waiters = [];
+ const listeners = [];
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (msg.id && pending.has(msg.id)) {
@@ -210,6 +227,7 @@ async function connect(wsUrl) {
pending.delete(msg.id);
msg.error ? fail(new Error(msg.error.message)) : ok(msg.result);
} else if (msg.method) {
+ for (const l of listeners.filter((x) => x.method === msg.method)) l.fn(msg.params);
for (const w of waiters.filter((x) => x.method === msg.method)) {
waiters.splice(waiters.indexOf(w), 1);
w.ok(msg.params);
@@ -222,7 +240,8 @@ async function connect(wsUrl) {
ws.send(JSON.stringify({ id, method, params }));
});
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));
@@ -255,10 +274,40 @@ async function main() {
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const page = await connect(pages.find((p) => p.type === 'page').webSocketDebuggerUrl);
await page.send('Page.enable');
- await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'dark' }] });
+ 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 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);
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.
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 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.
- const s = { person: args.person, portal: '' };
await go(`${LUCI}/server?section=people`);
await waitSel('.dl-srvbody a[href*="dawnline/person"]');
if (!s.person)
- s.person = await evaluate(
- `new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`,
- );
+ s.person = await evaluate(`new URL(document.querySelector('.dl-srvbody a[href*="dawnline/person"]').href).searchParams.get('id')`);
s.portal = await evaluate(`L.require('rpc').then((rpc) =>
rpc.declare({ object: 'luci.dawnline', method: 'person_links', params: ['id'] })(${JSON.stringify(s.person)}))
.then((r) => r.link ?? r.links?.[0] ?? '')`);
diff --git a/scripts/frame-screenshots.py b/scripts/frame-screenshots.py
index eff3b32..eaeab92 100755
--- a/scripts/frame-screenshots.py
+++ b/scripts/frame-screenshots.py
@@ -1,12 +1,16 @@
#!/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/.png at SCALE device pixels
per CSS pixel (scripts/capture-screenshots.mjs takes them); the framed images
-are written to docs/screenshots/.png at the same scale. Needs a
+are written to docs/screenshots/.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/.png, FLOW_MARGIN around each). Needs a
Chromium-based browser for the headless render (BROWSER=/path/to/chrome,
default: Brave or Chrome on macOS).
-Run: scripts/frame-screenshots.py
+Run: scripts/frame-screenshots.py [name ...] (all of them when no name is given)
"""
import os
import shutil
@@ -18,16 +22,18 @@ import tempfile
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
RAW = os.path.join(ROOT, 'docs', 'screenshots', 'raw')
OUT = os.path.join(ROOT, 'docs', 'screenshots')
+FONT = os.path.join(ROOT, 'package', 'luci-app-dawnline', 'root', 'usr', 'share', 'dawnline', 'portal', 'assets',
+ 'geist-latin-wght-normal.woff2')
-# name -> what the address bar shows
-SHOTS = {
- 'overview': 'router.lan · Dawnline',
- 'people': 'router.lan · Dawnline · People',
- 'person': 'router.lan · Dawnline · Myata',
- 'portal': 'vpn.example.com/kamiro-telosu-bavine',
- 'access': 'router.lan · Dawnline · Home · Access',
+SHOTS = ['overview', 'people', 'person', 'portal']
+# name -> the steps in front of its page, in order (raw captures). Taken with demo data, not on a router:
+# adding a device there would add one.
+FLOWS = {
+ 'portal': ['portal-add-1', 'portal-add-2', 'portal-add-3'],
}
-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
CANDIDATES = [
@@ -39,26 +45,18 @@ CANDIDATES = [
]
TEMPLATE = """